首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >重复一个问题,直到得到一个好答案

重复一个问题,直到得到一个好答案
EN

Stack Overflow用户
提问于 2019-05-10 07:18:24
回答 4查看 70关注 0票数 0

我正在为学校做一个小项目,我们需要在1到3之间设置一个困难,但是当有人输入一个错误的号码时,他们会收到一条线,上面写着请在1到3之间选择,但是这个问题应该重复一遍,现在当你输入一个错误的号码时,代码就会终止。

代码语言:javascript
复制
difficulty = int(input("Difficulty: "))

while 0 > difficulty > 4:
    print("This is not a valid difficulty, please choose 1, 2 or 3")
    difficulty = int(input("Difficulty: "))

if 0 < difficulty < 4:
    print("The playing board was created with difficulty: " + str(difficulty))
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2019-05-10 07:24:00

when循环0 > difficulty > 4从不执行,因为该条件总是计算为False,因为0 > 4False,因此我会将when循环重构为while difficulty > 4 or difficulty < 0:,这将检查困难是否小于0,还是大于4,也像@deceze指出的那样,if不需要,因为只有当我们确保我们的困难在0到4之间(不包括0和4)时,才需要if

所以答案改变为

代码语言:javascript
复制
difficulty = int(input("Difficulty: "))

#Check if difficulty is less than 0, or greater than 4
while difficulty < 0 or difficulty > 4:
    print("This is not a valid difficulty, please choose 1, 2 or 3")
    difficulty = int(input("Difficulty: "))

print("The playing board was created with difficulty: " + str(difficulty))

输出将类似于

代码语言:javascript
复制
Difficulty: -1
This is not a valid difficulty, please choose 1, 2 or 3
Difficulty: 5
This is not a valid difficulty, please choose 1, 2 or 3
Difficulty: 2
The playing board was created with difficulty: 2

编写while循环的另一种方法是,我们需要确保如果输入小于0或大于4,我们希望继续运行循环,这实际上可以由while not 0 < difficulty < 4:实现。

然后答案将更改为

代码语言:javascript
复制
difficulty = int(input("Difficulty: "))

#Check if difficulty is less than 0, or greater than 4
while not 0 < difficulty < 4:
    print("This is not a valid difficulty, please choose 1, 2 or 3")
    difficulty = int(input("Difficulty: "))

print("The playing board was created with difficulty: " + str(difficulty))
票数 1
EN

Stack Overflow用户

发布于 2019-05-10 07:25:32

就像这样:

代码语言:javascript
复制
difficulty = int(input("Enter input :"))
while difficulty<1 or difficulty>3:
  difficulty = int(input("Enter input between 1 and 3 :"))
print("correct input:",difficulty)
票数 1
EN

Stack Overflow用户

发布于 2019-05-10 07:30:03

“困难小于0,困难大于4”不可能是真的,因为没有一个同时小于0和大于4的数字。

代码语言:javascript
复制
difficulty = int(input("Difficulty: "))

while difficulty not in range(1, 4):
    print("This is not a valid difficulty, please choose 1, 2 or 3")
    difficulty = int(input("Difficulty: "))

print("The playing board was created with difficulty: " + str(difficulty))

您还可以省略if,因为循环已经确保该值在有效范围内;无需再次检查。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56072608

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档