我需要编写一段代码来检查用户输入是否为 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)
您的问题答案如下:
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)