首先,我只想说我最近才开始接触编程,所以我不是很好。这是我的问题:
x = int(input("Write a number between 1-100: "))
while x > 100:
x = int(input("The number must be less than 101: "))
while x < 1:
x = int(input("The number must be higher than 0: "))
else:
print ("The number is:",x)
有一种方法可以通过这样做来欺骗代码:
Write a number between 1-100: 101
The number must be less than 101: 0
The number must be higher than 0: 101
The number is: 101
我基本上不希望用户能够写出大于 100 或小于 1 的数字。
对于糟糕的解释,我深表歉意,但我已尽力而为,再一次,我最近开始编程。
请您参考如下方法:
我会这样做:
x = int(input("Enter a number in the range [1, 100]: "))
while not (1 <= x <= 100):
x = int(input("That number isn't in the range [1, 100]!: "))
else:
print ("The number is:",x)
当然,您可以使用嵌套的 if 语句来让您的提示更详细地说明错误,如下所示:
x = int(input("Enter a number in the range [1, 100]: "))
while not (1 <= x <= 100):
if x > 100:
x = int(input("The number must be less than 101: "))
else:
x = int(input("The number must be greater than 0: "))
else:
print ("The number is:",x)
请记住,您可以一次测试多个条件!
