Reputation: 75
This is a simple program I am working on to learn python because I am a beginner. How would I add an exception if the user types something other that y,Y,n,N. I have searched everywhere but can't seem to find what exception to use? Thanks for everyone's help.
EDIT:I adjusted my code. The only thing that is not working is if(welcomeString.strip().lower() != 'n' or 'y'): welcomeString = input('Not a valid choice\nWould you like to reverse a string?(y/n):'). It does not realize the user types in y or n. It works for other letters though.
EDIT2: Everything is working as expected until the user types in an invalid input a second time. The first time it will say "Not a valid choice", but the second time, the program will exit out.
import sys
welcomeString = input('Welcome to String Reverser\nWould you like to reverse a string?(y/n)')
if not welcomeString.strip().lower() in ['n','y']:
welcomeString = input('Not a valid choice\nWould you like to reverse a string?(y/n):')
if welcomeString.strip().lower() == 'n':
print("Thanks for using String Reverser")
while welcomeString.strip().lower() == 'y':
myString = input("What string would you like to reverse?:")
ReverseString = myString[::-1]
print (("Your Reversed String is %s") % ReverseString)
welcomeString = input("Would you like to reverse another string(y/n)")
Upvotes: 0
Views: 196
Reputation: 4735
In this case you do not really need an exception - an exception tends to be an exceptional case that prevents the program from continuing, if it can still continue but under certain circumstances due to user input or conditions it may use a Warning to signal that.
Here you can easily check input using any number of methods and repeat till you are able to get valid input :).
If you are determined to use exceptions:
You can look here for more details about how to use exceptions and here for how to subclass exceptions and make a user defined exception
So you can do 3 things:
1) have an assertion - this will cause an assertion error with your text as the statement to be seen as the error
a = 1
b = 2
assert a==b, "A does not Equal B"
an assert typically is for checking bounds - e.g. assert index >=0 and tends to be missing critical but you can use them for testing if it's your own personal code.
for your case you can have a switch statement / if-else chain like you currently do / have set operations. So as @Ketouem says above you can have a list of all the letters and check or a dict (if you had more letters such as 100 this would slightly faster).
The Python wiki gives general guidelines for good uses of an assert:
Places to consider putting assertions:
- checking parameter types, classes, or values
- checking data structure invariants
- checking "can't happen" situations (duplicates in a list, contradictory state variables.)
after calling a function, to make sure that its return is reasonable
-- Python Wiki
2) You can use one of the built in exceptions (look here) and raise one of those; e.g.
if(condition_not_met):
raise ValueError("You did not enter a correct option")
These typically have specific uses in mind though.
3) You can do what Numpy and many libraries do and create your own exceptions (you can also use a library's such as Numpy's LinAlgError, but unless you are manually catching and rethrowing usually these have domain specific uses.
To create your own exception you should subclass Exception not BaseException
e.g.
class MyInputError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
and later call this
if(condition_not_met):
raise MyInputError("Wrong input. Please try again")
lastly you can always use if then's and other control structures and then exit - but this isn't that common in Python and is more common in languages like C.
In general trying out something and catching errors is one of the more key paradigms in Python:
EAFP Easier to ask for forgiveness than permission. This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statements. The technique contrasts with the LBYL style common to many other languages such as C.
Upvotes: 1
Reputation: 25908
With regards to your edit, this is why your code isn't working:
if(welcomeString.strip().lower() != 'n' or 'y'):
This is not the right way to use or
. It evaluates to:
if(welcomeString.strip().lower() != ('n' or 'y')):
which evaluates to:
if(welcomeString.strip().lower() != 'n'):
which isn't what you want. Use this instead:
if not welcomeString.strip().lower() in ['n', 'y']:
Upvotes: 1
Reputation:
while True:
if welcomeString.strip().lower() == 'y':
...
elif welcomeString.strip().lower() == 'n':
...
break
else:
...
print("some error message")
sys.exit()
is definitely the most elegant solution in my opinion. If you are using python2 use raw_input
otherwise you will get an error since the user input could also be of type integer, float or bool (alternatively for python 2 you could also use if welcomeString in ['y', 'Y', 'N','n']:
.
Upvotes: 0
Reputation: 3857
You can use the good ol' assert to do some validation, that will throw an AssertionError if the condition is false
assert welcomeString not in ['n', 'N', 'y', 'Y'], "Validation Failed"
Alternatively you can raise a ValueError
if welcomeString.lower() not in ['n', 'y']:
raise ValueError("Invalid User Input")
Upvotes: -2
Reputation: 25676
Invalid user input should not normally result in an exception being thrown. Exceptions are for exceptional conditions. This isn't a hard-and-fast rule and you could argue that some standard exceptions don't follow it, but the way to deal with this kind of user input validation is regular flow control. Use an if
statement to check if it's valid, and if it's not, ask them again or take some other sensible action.
Upvotes: 4