Catch wrong input within dict? - python

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

Related

Is there any way to trigger an exception for incorrect string inputs in Python?

I am creating a text-to-speech synthesizer in Python. To allow maximum flexibility and user-friendliness, the program allows the user to edit variables, like speech rate or volume. I made a try-except-else loop to catch any wrong inputs. The problem with this is that the if an input is invalid, the exception is not triggered until later in the program. The inputs that are not being caught are strings. Is there any way to trigger an exception if certain keywords are not inputted, like:
while True:
try:
var = input("Choose your speech rate (Slow, Normal, or Fast): ")
except var != "Slow", "Normal", "Fast" :
print("\nPlease try again.")
continue
else:
break
Thanks!
You don't need to raise an exception. Just use an if/else statement instead.
Also, to check if var is either one of Slow, Normal or Fast, check it's membership on a set with those elements using the in keyword:
while True:
var = input("Choose your speech rate (Slow, Normal, or Fast): ")
if var not in {"Slow", "Normal", "Fast"}:
print("\nPlease try again.")
else:
break

check if input equals a specific string without repeating code

So im making a simple console menu for my program.
# Example menu program
menu = """
OPTIONS
1. Option 1
2. Option 2
"""
while True:
uinput = input(menu)
if uinput == "quit": # repetitive code
break
elif uinput == "1":
uinput = input("Input parameters: ")
if uinput == "quit": # repetitive code
break
process_params(uinput, option=1)
elif uinput == "2:
uinput = input("Input parameters: ")
if uinput == "quit": # repetitive code
break
process_params(uinput, option=2)
Whenever the user types quit into any one of those inputs, the loop breaks.
The problem is my program contains a lot of input functions, and I don't want to check if uinput == "quit" every time have an input function. Is there a way to do this? I thought of making a custom input function that checks the input every time, but you can't call break from another function.
The easiest way to break out of a loop (or do anything else exceptional that breaks the normal control flow) from an inner function call without threading a bunch of returns and checks back through multiple scopes is to raise an Exception.
class QuitException(Exception):
pass
def get_input(msg: str) -> str:
uinput = input(msg)
if uinput == "quit":
raise QuitException()
return uinput
while True:
try:
option = get_input(menu)
if option in {"1", "2"}:
process_params(
get_input("Input parameters: "),
option=int(option)
)
except QuitException:
break
I'm not too sure, but is this what it's supposed to do?
menu = """
OPTIONS
1. Option 1
2. Option 2
"""
while True:
print(menu)
uinput = input("Input parameters: ")
if uinput == "quit": # repetitive code
break
if uinput == "1" or uinput == "2":
process_params(uinput, option=int(uinput))
That is a very good question and you almost have the right answer - yes to a dedicated custom input function. Then, the only missing puzzle piece is using exceptions as flow control!
I couldn't find a nice documentation link quickly but I found a good post about it here.
Python is built with using exceptions as a tool to control your code flow in mind. They perform faster than if statements (unless they occur frequently which isn't our case) and let's you write with very few if statements. It might seem unnatural, at first, but it is Pythonic.
The idea is to raise an exception in custom_input for special cases such as "quit". You maintain the logic of when the program should exit (such as "quit", "exit" or others if you need) in one place and indicate to the calling stack (other functions chain) that a special case needs to be handled by raise-ing an exception.
def custom_input(prompt):
value = input(prompt)
if value == 'quit':
raise KeyboardInterrupt("User requested to exit.")
else:
return value
def main():
try:
while True:
value = custom_input(prompt = "Input parameters")
except KeyboardInterrupt:
print("Thank you, come again! Bye!")
And you can use custom_input several times, only needing if statements for menu choices. But, having the quit logic in one place rather than repeating the code.
Couldn't post from my phone fast enough :(
Hopefully this helps. I'm a little unsure what you are requesting.
User_Input = ""
while User_Input != 'quit':
User_Input = input('Get Some Input')

How to use isalpha to loop back when an alphabetical character isn't entered

I am a little confused as to why the loop ends. I was trying to make it so that if someone inputs numbers it loops back and asks the question again however it seems to just end. Any help would be greatly appreciated.
while True:
first_name = input("Please enter your first name. ")
try:
if first_name.isalpha() == False:
print("Please don't use alphanumeric characters ")
except:
if first_name.isalpha() == True:
print()
else:
break
The try-except-else and if-else blocks seem to be kind of mixed up. The except block will only be executed if an exception is thrown within the try: block body, and this doesn't happen normally in this code.
The else: block attached to try: will be executed every time the try: block *doesn't* throw an exception. So in this case it will execute thebreak` statement every time.

How do I use an elif statement properly?

Please don't judge me.. I've only been working with Python for a month now.
While laying in my bed I thought of making this and created it in a few minutes but I made to many else and if statements and my code just looks so messy, I kept adding things that weren't needed..(For fun :D)
Anyways, here is my code.. If you could tell me how to use the "elif" statements properly that'd be awesome.(I'm still learning python)
Question: I've tried using an elif statement multiple times and I keep getting an error. How do I fix this?
key = True # Game key, if this is false the program won't work.
print("Please type a password: ") # Asking for users password
Pass = input()
print("Thank you for typing your password, please make sure it's secure by trying again..") # Ask them to confirm their password by re-typing it
Again = input()
if Pass == Again:
print("Thank you for choosing a working password, please create your character")
print("Please type your username without numbers")
else:
print("Something's wrong with your password or username!")
# Has user confirm if his information is correct
User = input()
print("checking..")
if User.isalpha() and key == True:
print("So your Username is " + User + " and your chosen password is: " + str(Pass))
else:
print("Either your key is broken or something is wrong..")
if len(User) >= 4: # Checking if the chosen username has 4 or more characters in it
print("The length of your Username is: ")
print(str(len(User)))
print("If this information is correct please type 'true' or 'false'")
else:
print("Please type a username longer than 4 characters!")
answer = input() # I kinda fucked up because my coding is dirty and unorganized lol..
if answer == str(True):
print("Thank you, we're setting up your account! :D")
else:
print("Please re-run the program and fix your information!")
We can't debug code you haven't posted, and (as is to be expected - you are on a learning exercise here, and there's a lot to think about) your program structure isn't very helpful. For example, when the user enters non-matching passwords you tell them about it, but nevertheless continue to ask them for their username. Don't worry about this, you will soon learn how to fix it.
Since you ask about the elif, it is basically a syntax abbreviation for else if that avoids going to multiple indentation levels. Suppose you wanted a value of '1' or '2' to take different actions, and to declare other values invalid. You could write
if value == '1':
#take action appropriate to 1
else:
if value == '2':
# take action appropriate to 2
else:
raise ValueError("Allowed inputs are '1' or '2'")
Note that the different actions are at different indentation levels. The more cases you have to consider, the more levels of indentation you have to introduce. So it's generally felt to be more readable to write
if value == '1':
# Take action appropriate to 1
elif value == '2':
# Take action appropriate to 2
else:
raise ValueError("Allowed inputs are '1' or '2'")
Now all the actions and decisions are at the same indentation levels. That's pretty much all there is to it. If you leave the else case off then you won't take any actions at all, so it's normally used to specify the default action, in this case raising an exception.
PS: If you want to be sure the user has entered two matching passwords before you proceed, look at the while loop, which allows you to repeat a set of actions until some condition (in this case the passwords being equal) is true.
Here is an example if if/elif/else statement in python3:
test = 'mytest'
if test == 'not_my_test':
print('nope')
elif test == 'mytest':
print('yay')
else:
print('something else')
You can find more information here : https://docs.python.org/3/tutorial/controlflow.html
EDIT:
As a general remark, you should not define variable using capital letters (PEP convention: https://www.python.org/dev/peps/pep-0008/?)
So using Elif
if Pass == Again:
print("Thank you for choosing a working password, please create your character")
print("Please type your username without numbers")
elif Pass != Again:
print("Something's wrong with your password or username!")
Though what is this error you're getting, we can't really help you without it.

python 3: try except not working to check isalpha function

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

Categories

Resources