Python3 Try/Except Block - python

Can someone please help me understand the following issue...
I'm having problems executing my try/except block in my simple number guessing game. The function containing my error handling works fine if I remove the integer portion of the initial input. But if I do this, the rest of the game doesn't work, because from my understanding Python3 takes input and stores it as a string. So how can I get my exception to execute? Any help is much appreciated.
Thanks,
# number game
import random
print ("Welcome to the guessing number game!\n\n")
winning_number= random.randrange(1, 11)
guess = int(input("Can you guess the lucky number.\nHint it's between 1 and 10!\n"))
def is_number(guess):
try:
int(guess)
except ValueError:
print ('You need to type a number\n')
guess = int((input("Please input a number\n")))
game(guess)
def compare(guess):
if guess > winning_number:
print ("Wrong, you're guess is too high.\n")
guess = int(input("Guess againn\n"))
game(guess)
else:
print ("Wrong, you're guess is too low.\n")
guess = int(input("Guess again\n"))
game(guess)
def game(guess):
is_number(guess)
if guess == winning_number:
print ("You win!, You guessed the number!")
else:
compare(guess)
game(guess)
Here is what I get when I input anything other than an integer...
Welcome to the guessing number game!
Can you guess the lucky number.
Hint it's between 1 and 10!
f
Traceback (most recent call last):
File "C:/Users/mickyj209/PycharmProjects/Practice/NumberGuess.py", line 10, in
guess = int(input("Can you guess the lucky number.\nHint it's between 1 and 10!\n"))
ValueError: invalid literal for int() with base 10: 'f'
Process finished with exit code 1

You forgot to save the value that time (guess = int(guess)), you're not returning anything there, and you're just having the program run the function but not making a decision based on the result. You also have an int(input(... in the exception handling, which could itself generate an exception which won't be caught. The initial guess isn't in a try block, either.
You could refactor this program:
def game():
print ("Welcome to the guessing number game!\n\n")
winning_number = random.randrange(1, 11)
print("Can you guess the lucky number?\nHint: it's between 1 and 10!\n")
while 1:
try:
guess = int(input("Please input a number\n"))
except ValueError:
continue
if guess > winning_number:
print('Wrong - your guess is too high.')
elif guess < winning_number:
print('Wrong - your guess is too low.')
else:
print('You win! You guessed the number!')
break

Related

Beginners Coding Error, While Loop Triggering 2 Messages

I am a beginner that just started learning python this Monday and one of the first hurdles I am getting into is while loops. I was trying to code a number guessing game and when I enter the correct answer it will give me "Wrong Guess" and "Correct Guess" as outputs. I have been staring at this problem wondering why this is happening but I can't figure it out. Can someone explain why this is happening? Thanks in advance!
secret_number = 9
guess = ''
i = 0
while guess != 9 and i < 3:
guess = int(input("Guess Number: "))
i += 1
print('Wrong Guess!')
if guess == 9:
print('Your Correct!')
if i == 3:
print('You lost!')
You need to trace your code line by line. Even if your answer was correct, the print('Wrong Guess!') would still execute.
Instead, I would check if the answer is correct inside the loop.
Note: there's a bug in your code - you should be using secret_number variable instead of explicitly writing 9.
You should also only add i for wrong guesses to prevent saying you lost although you did it in 3 tries.
while guess != secret_number and i < 3:
guess = int(input("Guess Number: "))
if guess == secret_number :
print('Your Correct!')
else:
print('Wrong Guess!')
i += 1
You were getting both the messages together when you entered 9 as the input because the input statement and the Wrong Guess statement are both in the same while loop. Meaning once the code asks you to guess a number, it would then increment i and then print Wrong Guess. Only after doing all three it would go back and check for the conditions of the while loop. Because the conditions fail, for guess = 9 the next lines of code are implemented. which give you the Correct Guess output.
To get the desired output do this,
secret_number = 9
guess = ''
i = 0
while True:
if i < 3:
guess = int(input("Guess Number: "))
if guess == secret_number:
print("Correct Guess")
break
else:
print("Wrong Guess")
i += 1
else:
print("You've run out of lives.")
break
This is another way to get what you're looking for:
secret_number = 9
guess = ''
i = 0
while guess!= secret_number and i<3:
guess = int(input("Guess Number:"))
if guess == secret_number:
print("Your Correct!")
break
print("Wrong Guess!")
i+=1
if i == 3:
print('You Lost!')

Input validation for number guessing game results in error

This is my first post in this community and I am a beginner of course. I look forward to the day I can help others out. Anyway, this is the a simple code and I would like it so that there is an error if the user enters a string. Unfortunately, it does not execute the way I'd like to, here's the code:
number = 1
guess = int(input('Guess this number: '))
while True:
try:
if guess > number:
print("Number is too high, go lower, try again")
guess = int(input('Guess this number: '))
elif guess < number:
print("Too low, go higher, try again")
guess = int(input('Guess this number: '))
else:
print("That is correct")
break
except (SyntaxError, ValueError):
print("You can only enetr numbers, try again")
When the program gets executed, and it asks me to "Guess this number: ", when I write any string e.g. "d", it gives the error:
Guess this number: d
Traceback (most recent call last):
File "Numberguess.py", line 5, in <module>
guess = int(input('Guess this number: '))
ValueError: invalid literal for int() with base 10: 'd'
Thank you for your time and support.
Welcome to Stack Overflow! Everyone needs to start somewhere
Take a look at the code below:
# import random to generate a random number within a range
from random import randrange
def main():
low = 1
high = 100
# gen rand number
number = gen_number(low, high)
# get initial user input
guess = get_input()
# if user did not guess correct than keep asking them to guess
while guess != number:
if guess > number:
print("You guessed too high!")
guess = get_input()
if guess < number:
print("You guess too low!")
guess = get_input()
# let the user know they guess correct
print(f"You guessed {guess} and are correct!")
def gen_number(low, high):
return randrange(low, high)
# function to get input from user
def get_input():
guess = input(f"Guess a number (q to quit): ")
if guess == 'q':
exit()
# check to make sure user input is a number otherwise ask the user to guess again
try:
guess = int(guess)
except ValueError:
print("Not a valid number")
get_input()
# return guess if it is a valid number
return guess
# Main program
if __name__ == '__main__':
main()
This was a great opportunity to include Python's random module to generate a random number within a range. There is also a nice example of recursion to keep asking the user to guess until they provide valid input. Please mark this answer as correct if this works and feel free to leave comments if you have any questions.
Happy Coding!!!
Take a look at this line:
guess = int(input('Guess this number: '))
You try to convert string to int, it's possible, but only if the string represents a number.
That's why you got the error.
The except didn't worked for you, because you get the input for the variable out of "try".
By the way, there is no reason to input in the if, so your code should look like this:
number = 1
while True:
try:
guess = int(input('Guess this number: '))
if guess > number:
print("Number is too high, go lower, try again")
elif guess < number:
print("Too low, go higher, try again")
else:
print("That is correct")
break
except (SyntaxError, ValueError):
print("You can only enetr numbers, try again")
I would just use .isdigit(). The string would be validated at that point and then you would turn it into an int if validation works.
guess = input('Guess this number: ')
if guess.isdigit():
guess = int(guess)
else:
print("You can only enter numbers, try again")
Also worth to mention that try/excepts are cool and they get the job done, but it's a good habit to try to reduce them to zero, instead of catching errors, validate data beforehand.
The next example would do it:
number = 1
while True:
# Step 1, validate the user choice
guess = input('Guess this number: ')
if guess.isdigit():
guess = int(guess)
else:
print("You can only enter numbers, try again")
continue
# Step 2, play the guess game
if guess > number:
print("Number is too high, go lower, try again")
elif guess < number:
print("Too low, go higher, try again")
else:
print("That is correct")
break
the problem is in the first line. when you convert the input from the user directly to int, when a user inputs a letter, the letter cannot be converted to int, which causes the error message you get.
to solve this you need to do
guess = input('Guess this number: ')
if not guess.isdigit():
raise ValueError("input must be of type int")

'<' not supported between cases - Number guessing game

I am trying to create a number guessing game in Python for a school project. I have made a basic game that will work fairly well, but I want to add in some exception handling in case the user enters something incorrectly. For example, this is a section of my code:
def Normal_Guess():
number = round(random.uniform(0.0, 100.0),2)
guess = ""
while guess != number:
try:
guess = float(input("Please guess a number between 0 and 100: "))
except ValueError or TypeError:
print ("That isn't even a number!")
if guess < number and guess >= 0:
print ("You need to guess higher!")
elif guess > number and guess <= 100:
print ("You need to guess lower!")
elif guess == number:
print("Congratulations! You guessed the number!")
elif guess < 0 or guess > 100:
print ("The number you guessed is not between 0 and 100")
else:
print("That isn't even a number!")
New_Game()
This works fine when the user enters a float or integer value as "guess", and the Try-Except clause I have seems to catch if the user enters anything but a number at first, but the program seems to also carry on to the "if" statements. I am getting a TypeError saying that "'<' not supported between instances of 'str' and 'float'".
I have tried encompassing the entire loop in a Try-Except clause, and that doesn't work. I have no clue what I am doing wrong. Any help is much appreciated.
First off, the way you are catching the exception is invalid. The value of the expression ValueError or TypeError is always just going to be ValueError because that is how short-circuiting works with two non-False arguments. To get both types of errors to trigger the block, use a tuple, like (ValueError, TypeError).
The problem is that even if an exception is caught in your code, it will continue on to the if block. You have four simple options to avoid this:
Use a continue statement in the except block to tell the loop to move on without processing the following if structure:
try:
guess = float(input("Please guess a number between 0 and 100: "))
except (ValueError, TypeError):
print ("That isn't even a number!")
continue
This is probably the cleanest and easiest of the four options.
Do not use an except block to respond to the error. Instead, rely on the fact that the value of guess is still "". For this to work, you will have to pre-initialize guess with every iteration of the loop instead of once outside the loop:
while guess != number:
guess = ""
try:
guess = float(input("Please guess a number between 0 and 100: "))
except (ValueError, TypeError):
pass
if guess == "":
print ("That isn't even a number!")
elif guess < number and guess >= 0:
...
Personally, I am not a fan of this approach because it requires an initialization in every loop. This is not bad, just not as clean as option #1.
A variation on this option is to check directly if guess is an instance of str. You can then initialize it to the user input, making the conversion operation cleaner:
while guess != number:
guess = input("Please guess a number between 0 and 100: ")
try:
guess = float(guess)
except (ValueError, TypeError):
pass
if isinstance(guess, str):
print ("That isn't even a number!")
elif guess < number and guess >= 0:
...
Use the else clause that is one of the possible elements of a try block. This clause gets executed only if no exception occurred:
try:
guess = float(input("Please guess a number between 0 and 100: "))
except (ValueError, TypeError):
print ("That isn't even a number!")
else:
if guess < number and guess >= 0:
...
While this option creates an added layer of indentation, it is a possibility worth keeping in mind for those cases where a plain continue won't work. This happens sometimes when you need to do additional processing for both error and non-error cases, before you branch.
Put the entire if block into the try block. This way it will only be executed if there is no error. This is my least favorite option because I like my try blocks to be as trimmed-down as possible to avoid catching exceptions I did not intend to. In Python, try is relatively less of a performance-killer than in a language like Java, so for your simple case, this is still an option:
try:
guess = float(input("Please guess a number between 0 and 100: "))
if guess < number and guess >= 0:
...
except (ValueError, TypeError):
print ("That isn't even a number!")
Try using an else statement.
Your except catch print, but let script continue running. It will continue to all of if statements even when the catch is hit. What you want to do is skip the main logic of your function when the except is hit. Use the ELSE clause of the try-catch-else-finally block.
import random
def Normal_Guess():
number = round(random.uniform(0.0, 100.0),2)
guess = ""
while guess != number:
try:
guess = float(input("Please guess a number between 0 and 100: "))
except (ValueError, TypeError):
print ("That isn't even a number!")
else:
if guess < number and guess >= 0:
print ("You need to guess higher!")
elif guess > number and guess <= 100:
print ("You need to guess lower!")
elif guess == number:
print("Congratulations! You guessed the number!")
elif guess < 0 or guess > 100:
print ("The number you guessed is not between 0 and 100")
else:
print("That isn't even a number!")
Normal_Guess()

Returning error when user inputs space into program [duplicate]

This question already has answers here:
ValueError: invalid literal for int() with base 10: 'stop'
(3 answers)
Closed 6 years ago.
Like many before me, I am brand new at this, so go easy if I haven't given all the information needed, and thank you in advance.
Before I start it's worth mentioning that the program itself is running fine, what i'm worried about is making sure I've thought of every possibly scenario. Here goes.
I'm receiving this error:
File "C:\Users\brand\Desktop\WIP Programs\Guess the number 31.July.py", line 15, in <module>
userGuess = int(input("I guess: "))
ValueError: invalid literal for int() with base 10: ' '
When I press the space bar for input, it returns this. I am not sure how to make it so that the program returns something useful, such as the ability to guess again. Here is my code, for reference:
import random
guessNum = 0
print("Welcome to the guess the number game! Please, tell me your name!")
user = input("My name is: ")
randNum = random.randrange(1, 10, 1) #Generates number
print("Okay, " + user + ", guess the random number, the range is 1 to 10.")
#Guessing phase
while guessNum < 3:
userGuess = int(input("I guess: "))
if userGuess > randNum:
print("Too high! Try again.")
guessNum = guessNum + 1
if userGuess < randNum:
print("Too low! Try again.")
guessNum = guessNum + 1
if userGuess == randNum:
print("Great! You guessed my number!")
break
else:
print("Please choose a valid answer.")
if userGuess == randNum:
print("If you would like to play again, please restart the program.")
if userGuess != randNum:
print("Nope. My number was: " + str(randNum))
If I have any unneeded or am lacking anything I should have, please feel free to correct me!
EDIT!
Going off of the first reply. I added .isdigit() into my code properly:
if (userGuess.isdigit()):
userGuess = input("I guess: ")
if userGuess > randNum:
print("Too high! Try again.")
guessNum = guessNum + 1
It keeps passing an exception saying that 'userGuess' is not defined. Fine! okay, So I define it in the beginning of my code next to user. Which upon running, returns
AttributeError: 'int' object has no attribute 'isdigit'
Also fine, so I add str(0) to userGuess to attempt a fix which then returns:
TypeError: unorderable types: str() > int()
It now lets me input a number, however I cannot figure out how to fix. Any advice?
When the user chooses a number, his input is returned as string.
Afterwards, you try to convert that string to an integer. This works fine for strings as "13" or "4", but doesn't for strings like " 3" or "2a". Therefore an exception is raised in such a case.
As workaround, you can check the string with the "isdigit()" method before converting it. That method will return True for strings containing only digits and False otherwise.
Your issue is that the line userGuess = int(input("I guess: ")) is converting to an integer value without checking if it's possible to do so. When it finds a character value, this will throw an exception since the conversion isn't possible.
You could prevent this with a try...catch but I think a better way is to use the isDigit() method to check if the value is only digits before you try and convert.
while guessNum < 3:
userGuess = input("I guess: ")
if (userGuess.isDigit()):
userGuess = int(userGuess)
if userGuess > randNum:
print("Too high! Try again.")
guessNum = guessNum + 1
...
if userGuess == randNum:
print("Great! You guessed my number!")
break
else:
print("Please choose a valid answer.")

Not sure what I'm doing wrong, Python number-guessing game [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 7 years ago.
import random
print("Hey there, player! Welcome to Emily's number-guessing game! ")
name=input("What's your name, player? ")
random_integer=random.randint(1,25)
tries=0
tries_remaining=10
while tries < 10:
guess = input("Try to guess what random integer I'm thinking of, {}! ".format(name))
tries += 1
tries_remaining -= 1
# The next two small blocks of code are the problem.
try:
guess_num = int(guess)
except:
print("That's not a whole number! ")
tries-=1
tries_remaining+=1
if not guess_num > 0 or not guess_num < 26:
print("Sorry, try again! That is not an integer between 1 and 25! ")
break
elif guess_num == random_integer:
print("Nice job, you guessed the right number in {} tries! ".format(tries))
break
elif guess_num < random_integer:
if tries_remaining > 0:
print("Sorry, try again! The integer you chose is a litte too low! You have {} tries remaining. ".format(int(tries_remaining)))
continue
else:
print("Sorry, but the integer I was thinking of was {}! ".format(random_integer))
print("Oh no, looks like you've run out of tries! ")
elif guess_num > random_integer:
if tries_remaining > 0:
print("Sorry, try again! The integer you chose is a little too high. You have {} tries remaining. ".format(int(tries_remaining)))
continue
else:
print("Sorry, but the integer I was thinking of was {}! ".format(random_integer))
print("Oh no, looks like you've run out of tries! ")
I'll try to explain this as well as I can... I'm trying to make the problem area allow input for guesses again after the user inputs anything other than an integer between 1 and 25, but I can't figure out how to. And how can I make it so that the user can choose to restart the program after they've won or loss?
Edit: Please not that I have no else statements in the problems, as there is no opposite output.
Use a function.Put everything in a function and call the function again if the user wants to try again!
This will restart the complete process again!This could also be done if the user wants to restart.
Calling the method again is a good plan.Enclose the complete thing in a method/function.
This will solve the wrong interval
if not guess_num > 0 or not guess_num < 26:
print("Sorry, try again! That is not an integer between 1 and 25! ")
continue
For the rest, you can do something like this
create a method and stick in your game data
def game():
...
return True if the user wants to play again (you have to ask him)
return False otherwise
play = True
while play:
play = game()

Categories