我不知道如何让 catch_error_yn 工作。有人可以解释为什么该功能不起作用以及如何修复它吗?
def catch_error_yn():
unvalid = True
while unvalid:
try:
response = "Yes"
response = "No"
unvalid = False
return response
except ValueError:
print("please only enter 'Yes' or 'No' with capitals on Y or N:")
def carpark():
print("Do you want a free parking space, please answer 'Yes' or 'No' with capital letters on Y or N")
response = catch_error_yn
print(response)
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")
carpark()
答案 0 :(得分:0)
当你调用你的函数时,你必须添加空括号。我还根据我认为的预期目的修复了 catch_error_yn()
函数。这是更正后的代码:
def catch_error_yn():
while True:
userR = input("Do you want a free parking space, please answer 'Yes' or 'No' with capital letters on Y or N\n")
if userR == "Y":
return "Yes"
elif userR == "N":
return "No"
else:
print("Invalid Answer")
def carpark():
response = catch_error_yn()
print(response)
enter = input("Welcome to Copington Adventure Theme Park's automated ticket system\nplease press any button to see the ticket prices.\n")
print("\nAdult tickets are £20 each \nChild tickets are £12 each \nSenior citizen tickets are £11 each")
carpark()
答案 1 :(得分:0)
代码中似乎有一个小错误,即您没有将 input()
传递给 catch_error_yn()
函数。
我正在对您的代码的意图做出一些假设,并在此处添加修改后的工作代码:
def catch_error_yn():
unvalid = True
while unvalid:
try:
#get input inside the function
response = input()
# check if it is valid if, not raise an error
if response not in ['Y', 'N'] :
raise ValueError()
return response
except ValueError:
print("please only enter 'Yes' or 'No' with capitals on Y or N:")
def carpark():
print("Do you want a free parking space, please answer 'Yes' or 'No' with capital letters on Y or N")
response = catch_error_yn()
print(response)
print("Welcome to Copington Adventure Theme Park's automated ticket system\nplease press any button to see the ticket prices.")
print("\nAdult tickets are £20 each \nChild tickets are £12 each \nSenior citizen tickets are £11 each")
carpark()