Validate that integer is typed - python

I've looked up several of these questions and can't seem to apply it to my code correctly. I'm definitely new to Python and developed a number guessing game for practice. The last error handling I need is to make sure that anything typed that is not an integer, will return an error message. I was hoping to use an "if" statement like I have for other conditions, but will work with what I can get. Thanks!
(this is just a snippet. i didn't include the entire program)
def gamestart():
print(rndnumber)
for GuessAmount in range (1,11):
ActualGuess = int(input("Guess number " + str(GuessAmount) + ": "))
if ActualGuess < rndnumber:
print("HIGHER!")
if ActualGuess > rndnumber:
print("LOWER!")
if ActualGuess != rndnumber:
GuessAmount == GuessAmount + 1
if ActualGuess == rndnumber:
print("You Win!")
gameend()
print("")
print("Sorry, but you ran out of guesses.")
print("")
gameend()

Use try/except:
while True:
guess = input("Guess number " + str(GuessAmount) + ": ")
try:
guess_int = int(guess)
break
except ValueError:
print "please enter only integers"
Now you have your (converted to integer) input in guess_int.
If it was impossible to convert the input to integer, user gets warning and enters number once again.

Related

strings are throwing errors

In this project I am checking the number is even or odd with the help of user input. The problem I am stuck on is that when the user types a str character the whole project blows up. I want to write a program where even if the user typed a string the program won't blow up would print("Please type a number") a message like that.
type num = int(input("Enter a number: "))
if num % 2 == 0:
print(str(num) + ' is an even number')
else:
print(str(num) + ' is an odd number')
I tried try and except and even functions but I couldn't provide a logic to run the program.
Not sure why you are using typeat the beginning, but this may help you:
while True:
try:
num = int(input('Enter a number: '))
break
except ValueError:
print('Please type a number.')
continue
if num % 2 == 0:
print(str(num) + ' is an even number')
else:
print(str(num) + ' is an odd number')

Is there a way to make an integer input output a certain thing when a sting or float is inputted? [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed last year.
Here is my code:
x = 1
while x == 1:
fav_number = int(input("Guess my favorite number: "))
print()
if fav_number == 8:
print("Gongrats, you guessed it!")
x = 2
else:
print("Nope, try again!")
print()
In this example, I want it to also say "Nope, try again!" when the user inputs in a float or a string without crashing the program.
while True:
try: #Use the try/except block to raise exception if value is not integer
fav_number = int(input("Guess my favorite number: "))
print()
except ValueError: # if value is anything but integer, exception is raised
print("Invalid entry. Try again.")
else:
if fav_number == 8:
print("Gongrats, you guessed it!")
break #code ends when number is guessed
else:
print("Nope, try again!")
To make it more interesting, you can add a predefined number of attempts. If attempts are exhausted, code stops:
attempts = 5
while attempts > 0:
attempts -= 1
try: #Use the try/except block to raise exception if value is not integer
fav_number = int(input("Guess my favorite number: "))
print()
except ValueError: # if value is anything but integer, exception is raised
print("Invalid entry. Try again.")
else:
if attempts > 0:
if fav_number == 8:
print("Gongrats, you guessed it!")
break #code ends when number is guessed
else:
print("Nope, try again!")
print(f"You have {attempts} left")
else:
print("You have exhausted your attempts.")
You can, use eval in python for the string would convert int to int and float to float without exception. Check the documentation here: https://docs.python.org/3/library/functions.html#eval
So basically you can change the int to eval:
x = 1
while x == 1:
fav_number = eval(input("Guess my favorite number: "))
print()
if fav_number == 8:
print("Gongrats, you guessed it!")
x = 2
else:
print("Nope, try again!")
print()

Global variable not updated in while loop - Python

I'm new to Python but I can't seem to figure out why the declared "attempt" variable is not decremented if an incorrect attempt is submitted.
My thoughts are once a guess is submitted if it's not equal to the correctAnswer then the variable attempts should be decremeted by 1 so the print statement would say "You have 2 attempts left.
# You have 3 attempts to guess the correct word. If you don't you lose!
attempts = 3
correctAnswer = 32
while attempts != 0:
guess = input("How old is Dad?")
if guess != correctAnswer:
attempts = attempts - 1 #This should decrement if the attempt is incorrect
print("You have " + str(attempts) + " left")
else:
print("You lose!")
print("You are right!")
The variable is being updated but you have a problem with the input comparison and your print logic is kinda backwards, making the output look strange. The input function returns strings, and strings are never equal to integers. You need to convert the string to an integer. That will fail if you are given bad input so you can either check the value before you attempt a conversion or use a try/except block to catch errors.
You could pull the final success/failure condition out of the loop:
attempts = 3
correctAnswer = 32
while attempts != 0:
guess_str = input("How old is Dad?")
if not guess_str.isdigit():
attempts = attempts - 1
print("Please enter a number, yYou have " + str(attempts) + " left")
continue
guess = int(guess_str)
if guess != correctAnswer:
attempts = attempts - 1 #This should decrement if the attempt is incorrect
print("You have " + str(attempts) + " left")
else:
break
if attempts:
print("You are right!")
else:
print("You lose!")
But python while loops have an else clause that only runs if the while is not terminated with a break. Add a break to the success path and it will catch the fail path.
attempts = 3
correctAnswer = 32
while attempts != 0:
guess_str = input("How old is Dad?")
if not guess_str.isdigit():
attempts = attempts - 1
print("Please enter a number, yYou have " + str(attempts) + " left")
continue
guess = int(guess_str)
if guess != correctAnswer:
attempts = attempts - 1
print("You have " + str(attempts) + " left")
else:
print("You are right!")
break
else:
print("You lose!")

Getting error from implementing Try/Except

I am trying to add a try/except to my guessing game for non numerical entries from the user. Im not really sure how to implement it with my code but I did try but got an error saying:
ValueError: invalid literal for int() with base 10: 'v'
I am not sure how to rearrange my code to get it to work with the try/except.
def guessing_game(secret_number: int, user_guess: int):
num_tries: int = 0
user_name: str = input("Please enter your name: ")
print(f"Hello {user_name}, i am thinking of a number between 1 and 20")
secret_number: int = randint(1, 19)
user_guess: int = int(input("Guess what it is: "))
try:
while num_tries != 5:
if user_guess > secret_number:
user_guess = int(input("Your guess is too high. Try again: "))
elif user_guess < secret_number:
user_guess = int(input("Your guess is too low. Try again: "))
else:
print(f"Congrats {user_name}, {secret_number} was the number i was thinking of")
break
num_tries += 1
if user_guess != secret_number and num_tries == 5:
print(f"Sorry.The number I was thinking of was {secret_number}")
except ValueError:
print("Error, value must be numerical")
guessing_game(2, 8)
You're probably looking for something like this. No need to wrap everything in a function here (you weren't using the two arguments you passed in anyway).
The outer for loop handles stopping the game once all attempts are exhausted; Python's (quite unique) for/else structure handles losing the game.
The inner while loop loops for as long as the user is giving invalid input; you could add if not (1 <= user_guess <= 19): raise ValueError() in there to also have validation for whether the user is being silly and entering e.g. -1 or 69.
To simplify things, there's only one input() any more, and the game loop modifies the prompt for it.
from random import randint
user_name: str = input("Please enter your name: ")
print(f"Hello {user_name}, i am thinking of a number between 1 and 20")
secret_number: int = randint(1, 19)
prompt = "Guess what it is: "
for num_tries in range(5):
while True:
try:
user_guess: int = int(input(prompt))
break # out of the while
except ValueError:
print("Error, value must be numerical")
if user_guess > secret_number:
prompt = "Your guess is too high. Try again: "
elif user_guess < secret_number:
prompt = "Your guess is too low. Try again: "
else:
print(f"Congrats {user_name}, {secret_number} was the number i was thinking of")
break
else: # for loop was not `break`ed out of
print(f"Sorry. The number I was thinking of was {secret_number}")
Error explanation:
You are not correctly catching the exception because the input casting is outside the try block.
When user tries to enter a literal string, the line:
user_guess: int = int(input("Guess what it is: "))
raises ValueError because that string is not int-castable and the instruction is not inside the try, meaning that the default traceback handles the exception.
Just move that line inside the try block
try:
user_guess: int = int(input("Guess what it is: "))
Code improvement:
That been said, you need to organize your code better. First off your function should just do the matching between user input and secret number. Then you would create the loop and call that function for each user input:
def guessing_game(secret_number: int, user_guess: int):
if user_guess > secret_number:
print("Your guess is too high.")
elif user_guess < secret_number:
user_guess = print("Your guess is too low.")
else:
print(f"Congrats {user_name}, {secret_number} was the number i was thinking of")
return True
user_name = input("Please enter your name: ") # String casting is redundant here.
print(f"Hello {user_name}, i am thinking of a number between 1 and 20")
secret_number = randint(1, 19) # Why not (1,20) though?
# Here is the loop. It keeps prompting the user to enter a number and if the
# input represents a valid integer the function is called to compair them.
num_tries = 0
while True:
if num_tries == 5:
print(f"Sorry.The number I was thinking of was {secret_number}")
break
try:
user_guess = int(input("Guess what it is: "))
if guessing_game(secret_number, user_guess) == True:
break
except ValueError:
print("Error, value must be numerical")
num_tries += 1

Python, guess my number game [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
import random
print("hello, what is your name?")
GG = input()
print("well, " + GG + ", I am thinking of a number between 0 and 20")
number = random.randint(0,20)
try:
for taken in range(1,7):
print("Take a guess.")
guess = int(input())
if guess < number:
print("your guess is too low.")
elif guess > number:
print("your guess is too high.")
else:
break
except ValueError:
print("please enter a valid number")
if guess == number:
print("good job, "+ GG + " you guessed my number in " + str(taken) + " guesses")
else:
print("nope,the number i was thinking of was " + str(number))
If I want everytime when the player types an invalid input and the "Take a guess" game continues, how can I do?
Design
I think that you should separate, as far as possible, the two issues of looping on the responses and getting a validated response, and you can achieve this by writing a function that handles the problem of validating the user input.
Such a function needs to know how to prompt the user and what to tell the user if their input is invalid, so we must provide two arguments to the function, but we provide also reasonable defaults for the arguments...
To look at the correctness of the input, we use a try: ... except: ... clause, if the body of try raises an error, except looks at the error and if it is a particular one (for us, ValueError) the body of the except is executed.
The body of the except ends with a call to the function that we are defining, because this is another way of looping, if you consider what is happening... and in this case it is a simpler way of looping.
Implementation
That said, with the understanding of what we need in our function, we write it:
def get_integer(prompt='Enter an integer: ',
err_prompt='Not an integer, please try again.'):
answer = input(prompt)
try:
number = int(answer)
return number
except ValueError:
print(err_prompt)
return get_integer(prompt, err_prompt)
Testing
And now a bit of testing,
In [19]: get_integer()
Enter an integer: 1
Out[19]: 1
In [20]: get_integer()
Enter an integer: a
Not an integer, please try again.
Enter an integer: 1
Out[20]: 1
In [21]: get_integer(prompt='Un numero intero, per favore: ')
Un numero intero, per favore: 23.2
Not an integer, please try again.
Un numero intero, per favore: 22
Out[21]: 22
In [22]: get_integer(err_prompt='Naaaah!')
Enter an integer: q
Naaaah!
Enter an integer: 11
Out[22]: 11
In [23]:
Putting it all together
I've used your implementation, because for sure it is good enough, but I've changed a little the capitalization of the strings, no more try ... except as this is hidden in get_integer() and the introduction of an else clause to the for loop that is executed on normal termination, so that your user is informed of the reason why the program is stopping.
import random
def get_integer(prompt='Enter an integer: ',
err_prompt='Not an integer, please try again.'):
answer = input(prompt)
try:
return int(answer)
except ValueError:
print(err_prompt)
return get_integer(prompt, err_prompt)
print("Hello, what is your name?")
GG = input()
print("Well, " + GG + ", I am thinking of a number between 0 and 20...")
number = random.randint(0,20)
for taken in range(1,7):
print("Take a guess.")
guess = get_integer()
if guess < number:
print("Your guess is too low.")
elif guess > number:
print("Your guess is too high.")
else:
print("Your guess is exact!")
break
else:
print("Too many attempts. You lose!")
Wrap your input in some kind of while loop.
def checkIsValid(value):
#some validity checking function here.
‌
for taken in range(1,7):
print("Take a guess.")
guess = input()
isValid = checkIsValid(guess)
while (not isValid):
print("Invalid input")
guess = input()
isValid = checkIsValid(guess)
guess = int(guess)
#continue with the valid value.
'''
Created on 2016-3-24
#author: GuangFa
'''
import random
def get_name():
"""
Get name from the input.
:Usage:
get_name()
"""
print("hello,what is your name?")
name=raw_input()
return name
def get_number():
"""
Get number from the input.Return the number until the input is a valid number
:Usage:
get_number()
"""
is_number=False
while not is_number:
try:
number=input('please enter a valid number:')
except Exception ,e:
is_number=False
else:
is_number=True
return number
def guess():
"""
Guess the number.The system generates a random number,
Only 7 chances to guess the number.
:Usage:
guess()
"""
name=get_name()
print("well,%s, I am thinking of a number between 0 and 20"%name)
number = random.randint(0,20)
for taken in range(1,7):
print("Take a guess.")
guess=get_number()
if number==guess:
print ("good job, %s you guessed my number in %s guesses"%(name,str(taken)) )
break
if guess < number:
print("your guess is too low.")
elif guess > number:
print("your guess is too high.")
if taken==6:
print "nope,the number i was thinking of was " + str(number)
guess()

Categories

Resources