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

2024-04-24 06:41:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在为学校做一个小项目,我们需要设置一个1到3之间的难度,但是当有人输入一个错误的数字,他们会得到一行,说请在1和3之间选择,但问题应该重复本身,现在代码刚刚结束,当你输入一个错误的数字。你知道吗

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))

Tags: 项目代码inputis错误not数字this
3条回答

“当难度在0以下,难度在4以上时,永远不可能是真的,因为没有同时小于0和大于4的数字。格式化条件最可读的方法是使用range

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,因为循环已经确保值在有效范围内;无需再次检查。你知道吗

while循环0 > difficulty > 4从不执行,因为该条件的计算结果总是False,因为0 > 4False,因此我将while循环重构为while difficulty > 4 or difficulty < 0:,它检查难度是小于0还是大于4,也正如@deceze指出的那样,if是不需要的,因为该条件只在我们确保难度介于0和4之间,不包括0和4

所以答案变为

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))

输出看起来像

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:实现

然后答案将改为

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))

试着这样做:

difficulty = int(input("Enter input :"))
while difficulty<1 or difficulty>3:
  difficulty = int(input("Enter input between 1 and 3 :"))
print("correct input:",difficulty)

相关问题 更多 >