Try.
choice = input("enter v for validate, or enter g for generate").lower()
if (choice == "v") or (choice == "g"):
#do something
else :
print("Not a valid choice! Try again")
restartCode() #pre-defined function, d/w about this*
However, if you really want to stick with try/except you can store the desired inputs, and compare against them. The error will be a KeyError instead of a TypeError.
choice = input("enter v for validate, or enter g for generate").lower()
valid_choices = {'v':1, 'g':1}
try:
valid_choices[choice]
#do something
except:
KeyError
print("Not a valid choice! Try again")
restartCode() #pre-defined function, d/w about this
Answer from Rafael on Stack OverflowTry.
choice = input("enter v for validate, or enter g for generate").lower()
if (choice == "v") or (choice == "g"):
#do something
else :
print("Not a valid choice! Try again")
restartCode() #pre-defined function, d/w about this*
However, if you really want to stick with try/except you can store the desired inputs, and compare against them. The error will be a KeyError instead of a TypeError.
choice = input("enter v for validate, or enter g for generate").lower()
valid_choices = {'v':1, 'g':1}
try:
valid_choices[choice]
#do something
except:
KeyError
print("Not a valid choice! Try again")
restartCode() #pre-defined function, d/w about this
You are confused about what try/except does. try/except is used when an error is likely to be raised. No error will be raised because everything in your program is valid. Errors are raised only when there is an execution error in your code. Errors are not just raised when you need them to be.
You, however, want an error to be shown if the user does not enter a valid choice. You need to use an if/else logic instead, and print the error out yourself. And as a side note, the line choice == "v" and "g" does not test if choice is equal to 'v' or 'g'. It test if choice i equal to v and if the string 'g' is "truthy". Your estenially saying
if variable = value and True
I'm pretty sure that is not what you want. Here is how I would re-write your code.
if choice.lower() in {"v", "g"}: # if choice is 'v' or 'g'
# do stuff
else: # otherwise
print("Not a valid choice! Try again") # print a custom error message.
Python 3 except TypeError not working - Stack Overflow
except VS except valueError: what's the difference?
Typecheking code inside try...except TypeError
What's the point of "as e" in except blocks?
You actually don't need an exception check here. Also, your conditional statement will not raise that TypeError. Instead, simply use your conditional statement to continue your loop. This will also not require you to have to use any continue statement here either.
Furthermore, all input calls will return a string, so you do not need to cast as such. So, simply take your input without the str call:
while True:
user = input('Enter users sex:')
if user == 'female' or user == 'male':
break
else:
print('Please enter male or female')
print('The user is:', user)
If you were putting this in to a function, you can simply return your final result once satisfied and then print the "result" of what that function returns. The following example will help illustrate this:
def get_user_gender():
while True:
user = str(input('Enter users sex:'))
if user == 'female' or user == 'male':
break
else:
print('Please enter male or female')
return 'The user is: {}'.format(user)
user_gender = get_user_gender()
print(user_gender)
Small note, you will notice I introduced the format string method. It makes manipulating strings a bit easier getting in to the habit with dealing with your string manipulation/formatting in this way.
input() returns a string in Python 3. Calling str on it leaves it as it is, so it will never raise an exception.
You could get an error if you tried to do something like:
number = int(input("enter a number: "))
enter a number: abc
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-9-ec0ea39b1c6c> in <module>()
----> 1 number = int(input("enter a number: "))
ValueError: invalid literal for int() with base 10: 'abc'
because the string 'abc' can't be converted to an integer (in base 10, at least...)
Hi there,
I've been learning Python for some months now (still a beginner though!) and so far I encountered no issues when using a simple except in errors handling. But I came across except valueError many times in other people's codes, and I was wondering what was the difference between these two.
All I could find on the Internet was the use of the except valueError when raising an error, but I don't think I understood how it's different from except alone. Also it seems like this latter is barely mentioned anywhere I looked...
Any help appreciated!
I see this a lot
try:
do_something()
except ValueError as e:
do_something_else()Does "as e" serve any purpose here that I'm unaware of?