首先,我只想说我最近开始编程,所以我不是很好。这是我的问题:
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的数字。
我很抱歉这个错误的解释,但我尽力了,再一次,我最近开始编程。
答案 0 :(得分:3)
我会这样做:
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)
请记住,您可以一次测试多个条件!
答案 1 :(得分:2)
使用逻辑or
来测试单个while
中的条件:
while not 1 <= x <= 100:
x = int(input("The number must be in range [1, 100]: "))
这将迭代while
循环,直到用户输入小于1或大于100的输入。您还可以注意到,如果用户继续输入无效输入,这将导致无限循环。我会让你弄清楚如何解决这个问题。
答案 2 :(得分:1)
In Python, unlike other programming languages, expressions like a < b < c have the interpretation that is conventional in mathematics。这意味着您可以像这样编写while
- 循环:
x = int(input("Write a number between 1-100: "))
while not 1 <= x <= 100:
x = int(input("The number must be in the range 1-100: "))
else:
print ("The number is:", x)