1

首先,我只想说我最近开始编程,所以我不是很好。这是我的问题:

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 的数字。

我很抱歉解释不好,但我尽了最大努力,而且,我最近又开始编程了。

4

3 回答 3

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)

请记住,您可以一次测试多个条件!

于 2013-09-15T18:34:42.430 回答
2

使用逻辑or来测试一个单一的条件while

while not 1 <= x <= 100:  
    x = int(input("The number must be in range [1, 100]: "))

这将迭代while循环,直到用户输入小于 1 或大于 100 的输入。您还可以注意到,如果用户继续输入无效输入,这将导致您进入无限循环。我会让你弄清楚如何解决这个问题。

于 2013-09-15T18:26:12.927 回答
1

在 Python 中,与其他编程语言不同,像 a < b < c 这样的表达式具有数学中的常规解释。这意味着您可以while像这样编写 -loop:

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)
于 2013-09-15T18:34:27.487 回答