I'm trying to check that what's entered at the input function is all alpha characters. Basically I want to ensure numbers are not entered. However when I type a number such as 4 nothing happens. I don't even see an exception error. Also if i type anything besides "take honey" or "open door" it doesn't start the bear_room function. Haaalp. Thanks in advance!
def bear_room():
print("there's a bear here")
print("the bear has a bunch of honey")
print("the fat bear is front of another door")
print("how are you going to move the bear?")
choice = str(input("(Taunt bear, take honey, open door?: "))
try:
if choice.isalnum() == False:
if choice == "take honey":
print("the bear looks at you then slaps your face off")
elif choice == "open door":
print("get the hell out")
else:
bear_room()
except Exception as e:
print(str(e))
print("numbers are not accepted")
bear_room()
bear_room()
There's nothing to trigger an exception because code-wise it's perfectly legitimate to enter a number. It will check choice.isalnum(), it will be True for a number, and then bear_room() will be recursively called. You want the else part to contain the printing that you've got in the exception, then just get rid of the exception handler.
You have a few problems here.
First, don't cast your input to an str. It is already coming in as a string from input.
Second, is that you will never raise an exception with how you are looking to catch the exception you are looking to catch, because your input is outside the try/except. Not only that, but you will not raise an exception if you enter something like abcd1234. That is still a valid string.
Bonus problem you have. Never catch an open Exception. Always be explicit with what kind of exception you want to catch. However, you don't need to do a try/except here. Instead, just check if you have valid entries and proceed with your logic.
Simply, remove your try/except and even your isalnum check, and just check if the string entered matches what you are looking for. If it does not, output some kind of error message:
def bear_room():
print("there's a bear here")
print("the bear has a bunch of honey")
print("the fat bear is front of another door")
print("how are you going to move the bear?")
choice = input("(Taunt bear, take honey, open door?: ")
if choice == "take honey":
print("the bear looks at you then slaps your face off")
elif choice == "open door":
print("get the hell out")
else:
print("Invalid entry")
bear_room()
bear_room()
Related
I've run into a bug where the program seems to think that my input into an input statement isn't within the parameters, when it clearly is.
This is the code i'm having trouble with:
time.sleep(1.5)
print()
print()
print("You have chosen", horsechoice)
time.sleep(1)
print("How much do you want to bet?")
while True:
try:
moneyinput = int(input())
racebegin(moneyinput)
break
except:
print("Not a valid amount of money.")
continue
Even when I input an integer, it still states that I didn't input a valid amount of money.
If you only want to check the input validity, you should wrap the try/except only around the int(input()) call, not racebegin(). Your code is probably catching an error in racebegin().
It's also a good idea to narrow down the type of error you're catching with except:. Doing that might have prevented the problem in the original code, unless racebegin() was also raising ValueError.
while True:
try:
moneyinput = int(input())
break
except ValueError:
print("Not a valid amount of money.")
racebegin(moneyinput)
I'm trying to display the error message "This doesn't work" when a user enters an input that does not match a key in the dict. Currently, when they enter a correct input (ie, "Audi" or "Ferrari", It'll display the "This works, Audi" but If incorrectly entered, nothing happens. Why? I could easily do it with if/elif but I want to tackle the error handling side. Thanks
while car_search !="Q" or car_search !="q":
try:
if car_search in car_dict.keys():
car = car_dict[car_search]
print("This works", car.make)
except KeyError:
print("This doesn't work")
I corrected a bit your code and added comments
# if you want to capture both a lowercase and uppercase characters,
# you can do something like:
# notice you might need a rstrip to eliminate newline characters
# in case your search_car comes from a console input
while car_search.lower().rstrip() != "q":
# this is the EAFP approach. Try accessing the key, and handle
# the exception if the key does not exist
try:
car = car_dict[car_search]
print("This works", car.make)
except KeyError:
print("This doesn't work")
# here you have to request a new car_search,
# otherwise you will run again and again the same option
car_search = input("Input a car to search (q to exit)")
You can also use the LBYL approach, so you first check if the key exist before trying to access it.
while car_search.lower().rstrip() != "q":
if car_search in car_dict.keys():
print("This works", car.make)
else
print("This doesn't work")
car_search = input("Input a car to search (q to exit)")
I am brand new to programming and I'm building a guessing game for fun as a first program. I've already figured out the following:
How to set a specific number for them to guess between 1-50 (for example)
What happens when they guess outside the parameters
Number of guesses and attempts to "break the game"
Included while loops full of if statements
What I can't seem to figure out though is how to stop the user from inputting anything other than a number into the game. I want them to be able to, but I'd like to print out a personal error message then exit the while loop. (Essentially ending the game).
This is as close as I've been able to guess:
if guess == number:
print('Hey wait! That\'s not a number!')
print('Try again tomorrow.')
guessed = True
break
I get the error: "ValueError: invalid literal for int() with base 10" and I'm clueless on how to figure this out. I've been reading about isdigit and isalpha and have tried messing around with those to see what happens, but I get the same error. Maybe I'm just putting it in the wrong section of code
Any hints? :)
Thank you!
Use try/except to handle exceptions:
try:
guess = int(input("What's your guess? "))
except ValueError:
print("Hey wait! That's not a number!")
print("Try again tomorrow.")
guessed = True
break
# otherwise, do stuff with guess, which is now guaranteed to be an int
You can use a try / except to attempt the cast to an integer or floating point number and then if the cast fails catch the error. Example:
try:
guessInt = int(guess)
except ValueError:
print('Hey wait! That\'s not a number!')
print('Try again tomorrow.')
guessed = True
break
I have this code running in a number guessing game I have written, it runs perfectly fine if the player follows the instructions, but as we all know users never do. If the user enters just a space or any string thats not the word hint then it crashes saying invalid literal for int() with base 10: when trying to convert the value of guess to an integer. Is there any way around this or am I just going to have to live with the crashes?
while repeat==1:
repeat=0
level1number=str(level1number)
guess=input("What is your guess? ")
guess=guess.lower()
if guess==level1number:
print("Well done, You have guessed my number!")
elif guess=="hint":
print("Hints are not available until level 3")
repeat=1
elif guess!=level1number:
print("Sorry that is not my number, you have lost a life. :(")
lives=lives-1
repeat=1
if lives<=0:
print("You have lost all your lives, so this means I win")
print("The program will now end")
exit()
input("")
level1number=int(level1number)
guess=int(guess)
if guess<level1number:
print("The target number is higher")
else:
print("The target number is lower")
Use something as
if guess.isdigit() ...
(method isdigit() returns true if and only if all characters of a given string are digits, i.e. 0 to 9).
while repeat==1:
repeat=0
level1number=str(level1number)
guess=input("What is your guess? ")
guess=guess.lower()
if guess==level1number:
print("Well done, You have guessed my number!")
elif guess=="hint":
print("Hints are not available until level 3")
repeat=1
elif guess!=level1number:
print("Sorry that is not my number, you have lost a life. :(")
lives=lives-1
repeat=1
if lives<=0:
print("You have lost all your lives, so this means I win")
print("The program will now end")
exit()
input("")
level1number=int(level1number)
try:
guess=int(guess)
if guess<level1number:
print("The target number is higher")
else:
print("The target number is lower")
except:
print("Try again. Not a number")
Using try/except block would solve your problem. Have a look
Edit: In the question. you mentioned that you get an error when something other than a number is entered. Actually, it is an exception that is thrown when your code tries to convert your input string to a number when it is not possible(guess = int(guess)) due to the input not being a number, just like a space. So, what my code does, is that it catches the exception, and does not allow the program to terminate with the exception.
Just try it once. I know you are beginner but it is better to learn about exception handling as soon as possible, before you write more and more complex codes and applications.
Hope it helps!!
The second rule for If-Statements here, which has me confused states that:
If this else should never run because it doesn't make sense, then you must use a die function in the else that prints out an error message and dies, just like we did in the last exercise. This will find many errors.
Here's the code from the last exercise:
def dead(why):
print why, "Good job!"
exit(0)
def start():
print "You are in a dark room."
print "There is a door to your right and left."
print "Which one do you take?"
choice = raw_input("> ")
if choice == ‘left’:
bear_room()
else:
dead(‘You stumble around the room until you starve.’)
Is it essentially saying that you must successfully terminate the program if a condition is not met?
Yes, the idea is:
import sys
def die(msg):
print msg
sys.exit(1)
if condition:
# do stuff
else:
die('This cannot happen!')
You could also use an assert instead, or raise an exception, or anything else that would fail catastrophically. This helps you validate at runtime that the clause you didn't expect to execute, really didn't run.
IMHO you shouldn't get too hung up on how this die is done, exactly. The important point the referred text tries to make is that when you're sure some condition is true, you might as well assert it forcefully so that you can catch runtime bugs.
The guide is trying to show you that you can see the choice that a user gives when it's something that you don't check for in your if statement. If your else looks like:
else:
dead(choice)
You will be able to see what the user input that you didn't expect.
The problem is that the syntax only allows for "Left", when the prompt allows entry of anything. In other words, if I enter "Bob", I will starve. I should be trapping for anything that isn't appropriate and "die"ing at that point (or helping the user make an appropriate decision).
This is an attempt at teaching error handling and die. You would rewrite it such that you allow accurate entry or die (no exit). If you don't choose left, there is no other choice even though the prompt states there are two choices.
If you truly expect only 'left' to be added, a better way of checking for unexpeted input would be
if choice != ‘left’:
dead(‘You stumble around the room until you starve.’)
bear_room()
That way you still validate that the input is what you expected, but it saves indentation and space for the main logic.