A try except within a while loop Python 2.7 - python

Below is my code for guessing a random number. I had to check the input to make sure it was an integer and within the 1-20 range. Everything is working. It outputs the right response if it is not an integer or is out of range but then it continues through the while loop. I thought the try except would send it back before it continued. What have I done incorrectly here? I cannot figure out the problem. Thank you for any help!
import random
tries = 0
name=(raw_input('Hello! What is your name? '))
number = random.randint(1, 20)
print('Hello, ' + name + ', I am thinking of a number between 1 and 20.')
while tries < 6:
guess = (raw_input('Take a guess.' ))
try:
guess = int(guess)
except ValueError:
print 'You did not enter a valid number, try again.'
tries = tries + 1
if guess<1 or guess>20:
print 'Your guess is not between 1 and 20'
if guess < number:
print 'Your guess is too low.'
if guess > number:
print 'Your guess is too high.'
if guess == number:
break
if guess == number:
print 'Good job, ',name,'! You guessed my number in ',tries,' guesses!'
if guess != number:
print 'Sorry, The number I was thinking of was ',number

All you do is when a ValueError is raised is to have an extra line printed. If you want your loop to start from the beginning, add continue in the except block. If you want to count invalid inputs as tries, move the line where you increment tries to the beginning of your loop.
tries += 1 # increment tries here if invalid inputs should count as a try, too
# increment tries after the except block if only valid inputs should count as a try
# get input here
try:
guess = int(guess)
except ValueError:
# inform user that the input was invalid here
continue # don't execute the rest of the loop, start with the next loop
You can either put another continue where you check whether the number is too high or too low:
if guess<1 or guess>20:
print 'Your guess is not between 1 and 20'
continue
or use an if/elif construct:
if guess<1 or guess>20:
print 'Your guess is not between 1 and 20'
elif guess < number:
print 'Your guess is too low.'
elif guess > number:
print 'Your guess is too high.'
else: # guess == number
break
I recommend the if/elif. Having multiple continues in a loop can make it hard to follow.

You told it to print something, but Python doesn't know that you don't want it to do other things during that iteration. Sometimes you might want it to go on only if there was an error. To say "skip this loop", use continue:
try:
guess = int(guess)
except ValueError:
print 'You did not enter a valid number, try again.'
continue

You need to continue after both tests and only increment the tries once you have successfully passed the tests.
import random
tries = 0
name=(raw_input('Hello! What is your name? '))
number = random.randint(1, 20)
print('Hello, ' + name + ', I am thinking of a number between 1 and 20.')
while tries < 6:
guess = (raw_input('Take a guess.' ))
try:
guess = int(guess)
except ValueError:
print 'You did not enter a valid number, try again.'
continue
if guess<1 or guess>20:
print 'Your guess is not between 1 and 20'
continue
tries = tries + 1
if guess < number:
print 'Your guess is too low.'
if guess > number:
print 'Your guess is too high.'
if guess == number:
break
if guess == number:
print 'Good job, ',name,'! You guessed my number in ',tries,' guesses!'
if guess != number:
print 'Sorry, The number I was thinking of was ',number

Related

ValueError: Name undefined in python

I am getting "Name undefined warning while compiling with try-catch block". Please give some idea about this error.
NAME UNDEFINED ERROR IMAGE
# Importing random package
import random
try:
top_range = int(input("Enter the range:"))
except ValueError:
print("Please enter he Integer Number")
# Getting the random number from system
sys_guess = random.randint(0, top_range)
print("System Guess =", sys_guess)
print("Try to GUESS the Number within 3 entries, MAXIMUM 3 guess......!")
# making for increment
guess = 0
# Guessing the number
while sys_guess >= 0:
user_input = int(input("Enter guessed number: "))
if sys_guess != user_input:
# incrementing the wrong value
guess += 1
print("Wrong Guess-->")
if guess == 2:
print("you have only one guess left")
if guess > 2:
print("Maximum number of guess tried, Failed to obtain the guess!!!!!")
break
else:
# incrementing the correct value
guess += 1
print("!HURRAY***CORRECT GUESS***!")
if sys_guess == user_input:
break
# printing the total number of guess
print("Total Guesses=", guess)
Stick the try catch block in a loop that will continue endlessly until the user enters a valid number. If there is an exception at the moment the top_range value is never defined thus the error.
while True:
try:
top_range = int(input("Enter the range:"))
break
except ValueError:
print("Please enter he Integer Number")

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")

If input is not the specific type, print.. (Python) [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 5 years ago.
I would like to add an "if" statement to my code. If "guess" is not an integer, print ("You did not enter a number, please re-enter") and then repeat the code from the input area instead of the starting point. The following is my attempt, however when I enter a non-int at guess input, ValueError appears. Thanks in advance!
#This is a guess the number game.
import random
print ("Hello, what is your name?")
name = input()
print ("Well, " + name + " I am thinking of a number between 1 and 20, please take a guess.")
secretNumber = random.randint(1,20)
#Establish that they get 6 tries without specifically telling them
for guessesTaken in range(1, 7):
guess = int(input())
if type(guess) != int:
print ("You did not enter a number, please re-enter")
continue
if guess < secretNumber:
print ("The number you guessed was too low")
elif guess > secretNumber:
print ("The number you guessed was too high")
else:
break
if guess == secretNumber:
print ("Oh yeah, you got it")
else:
print ("Bad luck, try again next time, the number I am thinking is " + str(secretNumber))
print ("You took " + str(guessesTaken) + " guesses.")
Use a try and except:
for guessesTaken in range(1, 7):
try:
guess = int(input())
except ValueError:
print ("You did not enter a number, please re-enter")
continue
So you try to convert the input into an integer. If this does not work, Python will throw an ValueError. You catch this error and ask the user try again.
You can try a simple while loop that waits until the user has entered a digit. For example,
guess = input("Enter a number: ") # type(guess) gives "str"
while(not guess.isdigit()): # Checks if the string is not a numeric digit
guess = input("You did not enter a number. Please re-enter: ")
That way, if the string they entered is not a digit, they will receive a prompt as many times as necessary until they enter an integer (as a string, of course).
You can then convert the digit to an integer as before:
guess = int(guess)
For example, consider the following cases:
"a string".isdigit() # returns False
"3.14159".isdigit() # returns False
"3".isdigit() # returns True, can use int("3") to get 3 as an integer

Python3 Try/Except Block

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

How to add a loop to my python guessing game?

So I am very new to python as I spend most of my time using HTML and CSS. I am creating a small project to help me practice which is a number guessing game:
guess_number = (800)
guess = int(input('Please enter the correct number in order to win: '))
if guess != guess_number:
print('Incorrect number, you have 2 more attempts..')
guess2 = int(input('Please enter the correct number in order to win: '))
if guess2 != guess_number:
print('Incorrect number, you have 1 more attempts..')
guess2 = int(input('Please enter the correct number in order to win: '))
if guess2 != guess_number:
print()
print('Sorry you reached the maximum number of tries, please try again...')
else:
print('That is correct...')
elif guess == guess_number:
print('That is correct...')
So my code currently works, when run, but I would prefer it if it looped instead of me having to put multiple if and else statements which makes the coding big chunky. I know there are about a million other questions and examples that are similar but I need a solution that follows my coding below.
Thanks.
Have a counter that holds the number of additionally allowed answers:
guess_number = 800
tries_left = 3
while tries_left > 0:
tries_left -= 1
guess = int(input('Please enter the correct number in order to win: '))
if guess == guess_number:
print('That is correct...')
break
else:
print('Incorrect number, you have ' + str(tries_left if tries_left > 0 else 'no') + ' more attempts..')
If you don't know how many times you need to loop beforehand, use a while loop.
correct_guess = False
while not correct_guess:
# get user input, set correct_guess as appropriate
If you do know how many times (or have an upper bound), use a for loop.
n_guesses = 3
correct_guess = False
for guess_num in range(n_guesses):
# set correct_guess as appropriate
if correct_guess:
# terminate the loop
print("You win!")
break
else:
# if the for loop does not break, the else block will run
print("Out of guesses!")
You will get an error, TypeError: Can't convert 'int' object to str implicitly if you go with the answer you have selected. Add str() to convert the tries left to a string. See below:
guess_number = 800
tries_left = 3
while tries_left > 0:
tries_left -= 1
guess = int(input('Please enter the correct number in order to win: '))
if guess == guess_number:
print('That is correct...')
break
else:
print('Incorrect number, you have ' + (str(tries_left) if tries_left > 0 else 'no') + ' more attempts..')

Categories