How to allow both integers and strings in input?
I just started learning Python about a week ago, and for one of my first projects I built a really simple random number guessing game as part of the course I'm in. However, I tried to add an extension to my code that would print something different if the word "no" was entered as an input, even though the input only accepts integers in my code. In a previous question, I learned that try/except could be used to print something if an error occurred, (such as by entering "no" instead of an integer) per the following template:
In turn, my code looks like this:
And the output I get when I enter no looks like this:
Enter a number between 1 and 21: no
Traceback (most recent call last): File "C:/Users/camer/Desktop/Python/randomintproject.py", line 3, in <module> guess = int(input("Enter a number between 1 and 21: ")) ValueError: invalid literal for int() with base 10: 'no'
If the template code works, then what am I doing wrong?
You're trying to convert all inputs to
inp = input('enter a number...') if inp.isnumeric(): # checks if input is numeric, i.e. 2, 39, 4592 etc inp = int(inp) else: # Was not numeric, i.e. was a letter, word or some character print "OK forget it"
Another way would be:
inp = input('enter a number...') try: # checks if input is numeric, i.e. 2, 39, 4592 etc inp = int(inp) except(ValueError): # Was not numeric, i.e. was a letter, word or some character try: inp = float(inp) # Let's try again, could be user entered 3.5 or some other float value. except(ValueError): print("OK forget it")
This would cover the cases @schwobaseggl mentions in the comments of this question.
Also please do not take pictures of your code, but paste it here.
random n = random.randint(1,21) guess = int(input("Enter a number between 1 and 21: ")) try: while guess != n: print ("WRONG!") guess = int(input("Enter a number between 1 and 24: ")) if guess == n: print ("RIGHT!") except ValueError: if guess == "no": print ("OK forget it") else: print ("no idea what you want")
The problem here is the first
guess = int(input("Enter a number between 1 and 24: "))is before the
tryclause, and is therefore not covered by it and therefore when it errors it is not caught. Simply remove that line and it'll work fine!
P.S I have just realised that this way, every time you run the program it will say "WRONG!" before you start. The simplest fix is just to add a boolean
firstand if it's
true, don't print "WRONG!", then set it to
falseafter the first iteration. Alternatively (but uglier in my opinion), create a second try except clause for the first input