Skip to main content
 首页 » 编程设计

python之需要帮助在 python 中创建一个 try and catch 来验证数据类型和范围

2024年10月24日12虾米姐

我正在尝试创建一个 python 足球经理程序,该程序询问用户球员姓名,并询问球员进了多少球。进球数不能为负数或大于 6。我也在尝试获取代码以验证进球数是整数而不是字符串。这是我能做的最好的事情:

goals = "" 
while goals == "": 
    try: 
        goals = int(input("Enter goals scored")) 
    except ValueError: 
        print("Please enter an integer") 

我怎样才能获得同时检查范围的代码?正在做:

while goals == "" and goals not in range(0,6): 
    #Try catch loop 

不起作用。

请您参考如下方法:

您需要使用or,而不是and。

如果输入不是 int,您将得到一个 ValueError,并且 goals 将保持 ""。如果你没有得到一个 ValueError 一个有效的 int 被分配给 goals,所以你需要检查范围:

while goals == ""  or goals not in range(0,6):