首页 > 解决方案 > catch_error_yn 函数不起作用

问题描述

我不知道如何使 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()

标签: python

解决方案


代码中似乎有一个小错误,因为您没有将 传递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()

推荐阅读