higher or lower game unexpected EOF while parsing - python

need help with a higher or lower game I think the problem has something to do with the loop. I have been told been told to add an except but I have no idea where to add it
print('Welcome to higher or lower game')
input('press enter to start.\n')
import random
Max = 10
Min = 0
num = random.randint(1, 10)
print('your starting number is a ' + str(num))
while 'well done.\n' :
guess = input('higher (h) or lower (l).\n')
new_num = random.randint(1, 10)
print('your new number is a ' + str (new_num))
try :
if new_num > num and guess == 'h':
print('well done.\n')
elif new_num < num and guess == 'l':
print('well done.\n')
break
if num and guess == 'l' and new_num > num and guess:
print('game over')
elif num and guess == 'h' and new_num < num and guess:
print('game over')
else:
print('game over you got a score of ' + str(score))

You do not have an except clause in the try statement. That clause is required unless you have a finally clause.

You really shouldn't have a try statement there. You could take it out and just go with some if and elif statements.
Example:
import random
number = random.randint(1,10)
lives = 3
Success = False
while lives > 0:
guess = int(input("What is your guess between 1 and 10? \r\n"))
if guess > number:
print("Too high! Go lower. \r\n")
lives -= 1
elif guess < number:
print("Too low! Go higher. \r\n")
lives -= 1
elif guess == number:
print("Congratulations, you win!")
global Success = True
break
if Success != True:
print("Sorry. Try again! The number was ", number, ".")
As far as I understand, try statements are mainly used for error handling.

Related

Python - How to return to previous function after calling another function?

Heres the copy of my code :) this game is part of my personal activity.
so after purchasing a clue (from: def game_hints) i want to return to def Game_process.
import random
SCORE = 0
ROUNDS = 1
def player_stats():
print(f"SCORE: {SCORE} | ROUNDS: {ROUNDS}")
def game_hints(USER_GUESS, Mystery_NUM):
print("Would you like purchase a hint for 5 points? [1/2]: ")
USER_HINT = int(input())
global SCORE
if USER_HINT == 1:
SCORE= SCORE - 5
if USER_GUESS > Mystery_NUM and Mystery_NUM % 2 == 0:
print("Mystery Num is even and try a smaller guess")
elif USER_GUESS > Mystery_NUM and Mystery_NUM % 2 == 1:
print("Mystery Num is odd and try a smaller guess")
elif USER_GUESS < Mystery_NUM and Mystery_NUM % 2 == 0:
print("Secret Num is even and try a larger guess")
elif USER_GUESS < Mystery_NUM and Mystery_NUM % 2 == 1:
print("Mystery Num is odd and try a larger guess")
def Game_Process():
global ROUNDS
while True:
if ROUNDS <= 10:
Mystery_NUM = random.randrange(10)
print(Mystery_NUM) #remove before final product
print("Guess the num [1-10]: ")
USER_GUESS = int(input())
if USER_GUESS == Mystery_NUM:
print("\nGood Job! +5 Coins!")
global SCORE
SCORE = SCORE + 10
ROUNDS += 1
player_stats()
else:
print("Wrong! Try Again")
game_hints(USER_GUESS, Mystery_NUM)
else:
print("Game Over!")
Game()
def Game():
user_opt = input("\"Welcome to Guess Game\" \nPress [Y] to Play or [N] to Exit: ").lower()
if user_opt == "n":
print("Good bye!")
exit()
elif user_opt == "y":
Game_Process()
else:
print("Invalid Input! [1/2]")
Game()
Game()
As shown below, this is the fuction for the hints. I was able to call this function but the only problem is that the after this fuction is done, it changes the Myster_Num.
def game_hints(USER_GUESS, Mystery_NUM):
print("Would you like purchase a hint for 5 points? [1/2]: ")
USER_HINT = int(input())
global SCORE
if USER_HINT == 1:
SCORE= SCORE - 5
if USER_GUESS > Mystery_NUM and Mystery_NUM % 2 == 0:
print("Secret Num is even and try a smaller guess")
elif USER_GUESS > Mystery_NUM and Mystery_NUM % 2 == 1:
print("Secret Num is odd and try a smaller guess")
elif USER_GUESS < Mystery_NUM and Mystery_NUM % 2 == 0:
print("Secret Num is even and try a larger guess")
elif USER_GUESS < Mystery_NUM and Mystery_NUM % 2 == 1:
print("Mystery Num is odd and try a larger guess")
First, you must remove the else statement in the game_hints function because it restarts a full GameProcess and therefore indeed recompute a mysterious number.
Then, when you exit game_hints and come back to GameProcess, you must not come back to the big loop because it will indeed recompute a mysterious number. The solution is to have an inner loop inside each round that you exit only if the player guessed the correct value using the break keyword.
def Game_Process():
SCORE = 0
ROUNDS = 1
while True:
if ROUNDS <= 10:
Mystery_NUM = random.randrange(10)
print(Mystery_NUM) # remove before final product
while True:
print("Guess the num [1-10]: ")
USER_GUESS = int(input())
if USER_GUESS == Mystery_NUM:
print("\nGood Job! +5 Coins!")
SCORE = SCORE + 10
ROUNDS += 1
player_stats()
break
else:
print("Wrong! Try Again")
game_hints(USER_GUESS, Mystery_NUM)
else:
print("Game Over!")
Game()

Number Game: Can't Win: Won't print: You Win, but ends script

My issue is that python script ends when I get the number right, but doesn't print: You win!
import random
number = random.randint(1,100) # This part works fine
guess = input('Guess a number between 1 and 100: ') #Asks question
guess = float(guess)
tries = 10
while guess != number and tries > 0 :
if guess < number: # This part works fine
print('Too low')
tries = tries - 1
print('You have %s tries left' % (tries))
if guess > number:
print('Too high') # This part is also good
tries = tries - 1
print('You have %s tries left' % (tries))
if tries == 0:
print('You lose!')
print('The answer was ' + str(number))
continue
if guess == number :
print('You win!') # Why doesn't this work?
#Python ends at this line if I get it right, but doesn't print: You win!
else :
guess = input('Try Again: ')
guess = float(guess)
pass # WHILE*
I'm only 11, and just started programming a couple months ago, please help me!
Your code fails the first condition if a guess is correct:
while guess != number and tries > 0 :
If a guess is complete the loop will break after your else statement and never returns to the if condition checking for a guess.
Since you can't continue past the loop until a correct answer is inputted you could always write this as follows:
import random
number = random.randint(1,100) # This part works fine
guess = input('Guess a number between 1 and 100: ') #Asks question
guess = float(guess)
tries = 10
while guess != number and tries > 0 :
if guess < number: # This part works fine
print('Too low')
tries = tries - 1
print('You have %s tries left' % (tries))
if guess > number:
print('Too high') # This part is also good
tries = tries - 1
print('You have %s tries left' % (tries))
if tries == 0:
print('You lose!')
print('The answer was ' + str(number))
continue
else :
guess = input('Try Again: ')
guess = float(guess)
print('You win!')
Bear in mind there's a bug in this that will cause you win to also be printed after the user runs out of guesses. I've decided to leave this here as I think it's easy to fix and would be good for you to resolve yourself to learn from. Feel free to write in the comments if you want me to do that for you however.
I would also recommend using code comments on your posts. In this case I would have presented the code for your question as follows:
import random
number = random.randint(1,100) # This part works fine
guess = input('Guess a number between 1 and 100: ') #Asks question
guess = float(guess)
tries = 10
while guess != number and tries > 0 :
if guess < number: # This part works fine
print('Too low')
tries = tries - 1
print('You have %s tries left' % (tries))
if guess > number:
print('Too high') # This part is also good
tries = tries - 1
print('You have %s tries left' % (tries))
if tries == 0:
print('You lose!')
print('The answer was ' + str(number))
continue
if guess == number :
print('You win!') # Why doesn't this work?
# Python ends at this line if I get it right, but doesn't print: You win!
else :
guess = input('Try Again: ')
guess = float(guess)
pass # WHILE*
When doing comparisons in your code, it is often best to try and only ask a particular question (do a comparison) once. Here I showed a way to restructure your two questions (correct guess & out of tries) to only do the questions once.
import random
number = random.randint(1, 100)
guess = input('Guess a number between 1 and 100: ') # Asks question
guess = float(guess)
tries = 10
while True:
tries -= 1
if guess < number:
print('Too low')
print('You have %s tries left' % (tries))
elif guess > number:
print('Too high')
print('You have %s tries left' % (tries))
else:
print('You win!')
break
if tries == 0:
print('You lose!')
print('The answer was ' + str(number))
break
guess = input('Try Again: ')
guess = float(guess)

How to go about repeating or ending a function by a simple yes or no answer? [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 6 years ago.
I wanted to create a guessing game to get more comfortable programming, The user has up to 100 guesses(yes more than enough). If the number is too high or too low it have them type in a new input, if its correct it will print correct.Now I simply want to have it setup to where I ask them would they like to play again. I think I have an idea of to set it up, by separating them into two functions?
I am aware that is not currently a function but should put this as a fucntion and then put my question as an if statement in its own function?
import random
randNum = random.randrange(1,21)
numguesses = 0
while numguesses < 100:
numguesses = numguesses + 1
userguess = int(input("What is your guess [1 through 20]?"))
if userguess < 1:
print("Too Low")
print("Please enter a valid guess [1-20]!")
elif userguess > 20:
print("Too High")
elif userguess == randNum:
print("Correct")
print("you used",numguesses,"number of guesses")
Here's a simple way to do as you asked.I made a function and when you get the thing correct it asks if you want to play again and if you enter "yes" then it resets the vars and runs the loop again. If you enter anything but "yes" then it breaks the loop which ends the program.
import random
def main():
randNum = random.randrange(1,21)
numguesses = 0
while numguesses < 100:
numguesses = numguesses + 1
userguess = int(input("What is your guess [1 through 20]?"))
if userguess < 1:
print("Too Low")
print("Please enter a valid guess [1-20]!")
elif userguess > 20:
print("Too High")
elif userguess == randNum:
print("Correct")
print("you used",numguesses,"number of guesses")
x = input("would you like to play again?")
if x == "yes":
main()
else:
break
main()
Here is another way to do
import random
randNum = random.randrange(1,21)
numguesses = 0
maxGuess = 100
print("Guessing number Game - max attempts: " + str(maxGuess))
while True:
numguesses +=1
userguess = int(input("What is your guess [1 through 20]? "))
if userguess < randNum:
print("Too Low")
elif userguess > randNum:
print("Too High")
else:
print("Correct. You used ",numguesses," number of guesses")
break
if maxGuess==numguesses:
print("Maximum attempts reached. Correct answer: " + str(randNum))
break
import random
randNum = random.randrange(1, 21)
guess = 0
response = ['too low', 'invalid guess', 'too hight', 'correct']
def respond(guess):
do_break = None # is assigned True if user gets correct answer
if guess < randNum:
print(response[0])
elif guess > randNum:
print(response[2])
elif guess < 1:
print(response[1])
elif guess == randNum:
print(response[3])
do_continue = input('do you want to continue? yes or no')
if do_continue == 'yes':
# if player wants to play again start loop again
Guess()
else:
# if player does'nt want to play end game
do_break = True # tells program to break the loop
# same as ''if do_break == True''
if do_break:
#returns instructions for loop to end
return True
def Guess(guess=guess):
# while loops only have accesse to variables of direct parent
# which is why i directly assigned the guess variable to the Fucntion
while guess < 100:
guess -= 1
user_guess = int(input('What is your guess [1 through 20]?'))
# here the respond function is called then checked for a return
# statement (note i don't know wheter this is good practice or not)
if respond(user_guess):
# gets instructions from respond function to end loop then ends it
break
Guess()
Yet another way with two while loops
answer = 'yes'
while answer == 'yes':
while numguesses < 100:
numguesses = numguesses + 1
userguess = int(input("What is your guess [1 through 20]?"))
if userguess < 1:
print("Too Low")
print("Please enter a valid guess [1-20]!")
elif userguess > 20:
print("Too High")
elif userguess == randNum:
print("Correct")
print("you used",numguesses,"number of guesses")
break #Stop while loop if user guest, hop to the first loop with answer var
answer = raw_input("Would you like to continue? yes or no\n>")

Python 3.4 :While loop not looping

Python loop isn't wanting to loop back if the user's guess is greater than or less than the randomly generated value. It either exits the loop or creates an infinite loop. Where am I going wrong?
import random
correct = random.randint(1, 100)
tries = 1
inputcheck = True
print("Hey there! I am thinking of a numer between 1 and 100!")
while inputcheck:
guess = input("Try to guess the number! " )
#here is where we need to make the try statement
try:
guess = int(guess)
except ValueError:
print("That isn't a number!")
continue
if 0 <= guess <= 100:
inputcheck = False
else:
print("Choose a number in the range!")
continue
if guess == correct:
print("You got it!")
print("It took you {} tries!".format(tries))
inputcheck = False
if guess > correct:
print("You guessed too high!")
tries = tries + 1
if guess < correct:
print("You guessed too low!")
tries = tries + 1
if tries >= 7:
print("Sorry, you only have 7 guesses...")
keepGoing = False
The problem is with this line:
if 0 <= guess <= 100:
inputcheck = False
This will terminate the loop whenever the user enters a number between 0 and 100. You can rewrite this part as:
if not 0 <= guess <= 100:
print("Choose a number in the range!")
continue
The correct code is below:
import random
correct = random.randint(1, 100)
tries = 1
inputcheck = True
print("Hey there! I am thinking of a numer between 1 and 100!")
while inputcheck:
guess = input("Try to guess the number! " )
#here is where we need to make the try statement
try:
guess = int(guess)
except ValueError:
print("That isn't a number!")
continue
if 0 > guess or guess > 100:
print("Choose a number in the range!")
continue
if guess == correct:
print("You got it!")
print("It took you {} tries!".format(tries))
inputcheck = False
if guess > correct:
print("You guessed too high!")
tries = tries + 1
if guess < correct:
print("You guessed too low!")
tries = tries + 1
if tries > 7:
print("Sorry, you only have 7 guesses...")
inputcheck = False
The problem here was that you were setting inputcheck to False when the value of guess was in between 0 and 100. This changed the value of while to False and the loop was exiting since while wasn't True anymore.
Also, you should change the last if case in the while loop since this now fixes the case of running indefinitely:
if tries > 7:
print("Sorry, you only have 7 guesses...")
inputcheck = False

Python random number generator

The code works fine, but I can't figure out how to completely restart the program. I put continue in the code and I know that is not correct, because I want it to restart completely after you guess the correct number and it displays 'Congratulations! You guessed my number in _ guesses.
import random
guesses = 0
number = random.randint(1, 100)
print('I am thinking of a number between 1 and 100.')
while guesses < 100:
guess = int(input('Guess? '))
guesses = guesses + 1
if guess < number:
print('Your guess is too low.')
if guess > number:
print('Your guess is too high.')
if guess == number:
continue
if guess == number:
guesses = str(guesses)
print('Congratulations! You guessed my number in ' + guesses + ' guesses!')
If you want to keep on guessing and start the game automatically, you need to do a recursive call:
import random
def guess_func():
number = random.randint(1, 100)
guesses = 0
while True:
guess = int(raw_input("Enter your guess: "))
if guess < number:
print('Your guess is too low.')
guesses += 1
if guess > number:
print('Your guess is too high.')
guesses += 1
if guess == number:
print "Congratulations! You guessed my number in [{}] guesses".format(guesses)
print "Let's keep on guessing!"
return guess_func()
guess_func()
so like this:
while True:
guesses = 0
while guesses < 100:
if guesses == 100:
break
...
if guess == number:
print ...
yorn = input "do you want to try again?")
if yorn == 'n':
break
so just wrap your code in an outer while, obviously i skipped a lot of your code

Categories

Resources