Reputation: 11
Please don't be too harsh because I'm new to coding. The problem I'm having is that the function catch_error_str does not work. For example, when I enter "2" as an input then it says last_name is 2 instead of catching the error.
def catch_error_str():
unvalid = True
while unvalid:
try:
string = str(input())
unvalid = False
return string
except ValueError:
print("You must not enter any numbers")
def surname ():
print("What is the surname of the lead booker ")
last_name = catch_error_str()
print(last_name)
print("Welcome to Copington Adventure Theme Park's automated ticket system\nplease press any button to see the ticket prices.")
enter = input()
print("\nAdult tickets are £20 each \nChild tickets are £12 each \nSenior citizen tickets are £11 each")
surname()
Upvotes: 0
Views: 40
Reputation: 438
If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised.
https://docs.python.org/3/library/functions.html#input
Upvotes: 0
Reputation: 71
Input returns a string even if the user input is a digit.
name = input(“Enter last name: “)
if name.isdigit():
unvalid = True
Upvotes: 0
Reputation: 4472
Python don't have a problem to covert a number to a string and because of that, there is no error rasing.
You can try
def catch_error_str():
unvalid = True
while unvalid:
try:
string = str(input())
if not string.isalpha():
raise ValueError
unvalid = False
return string
except ValueError:
print("You must not enter any numbers")
The isalpha()
method of string will check if the input not containing numbers and if so it will raise the value error.
Upvotes: 2
Reputation: 18367
The value that is returned from Input()
is of type str
therefore, the conversion won't generate an error that you can catch with ValueError
. Instead you should try to check the type()
of the variable. Also, you are requiring the input within the try. I would use something like this:
def catch_error_str():
unvalid = True
while unvalid:
string = input()
try:
string = float(string)
print("You must not enter any numbers")
except ValueError:
unvalid = False
return string
Since floats/ints can be converted to strings without any problem, I'm facing the problem the other way around. I am trying to convert it into a float, if I'm able to, it's because the value is numeric, hence the error. If I am not able to, then that means it will generate ValueError because it is text
Upvotes: 0