如何检查用户输入是否为 1 到 9 之间的 + 整数?如果存在 ValueError 或负整数,则用户输入存储为 0

问题描述 投票:0回答:1

我需要编写一段代码来检查用户输入是否为 1 到 9 之间的正整数。如果提供了字符串或负整数,程序将显示一条消息“您尚未输入有效数字 - 0 已而是被存储了。”下面的代码确实有效。但是如果用户输入是-5,错误消息会显示两次,而我只需要它显示一次。我做错了什么,但我不知道是什么。

try:
    x = input("Enter the first number:")
    x = int(x)
except:
    print("You have not entered a valid number - 0 has been stored instead")
    x = 0
if x < 1 or x > 9:
    print("You have not entered a valid number - 0 has been stored instead")
    x = 0
print(x)
python if-statement input integer try-catch
1个回答
0
投票

您的问题答案如下:

try:
    x = input("Enter the first number:")
    x = int(x) 
    if 1<=x<=9: #this checks if the input is inbetween 1 and 9
        pass #here you can add an action that you want to happen when the if clause is true
    else:
        print("This number is out of the valid range (1,9). 0 has been stored instead")
        x=0
except ValueError:
        print("Error: You have not entered a valid value - 0 has been stored instead")
        x=0

print(x)
© www.soinside.com 2019 - 2024. All rights reserved.