我正在为学校做一个小项目,我们需要将难度设置为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))
答案 0 :(得分:1)
while循环0 > difficulty > 4
永远不会执行,因为该条件总是评估为False
,因为0 > 4
是False
,因此我将while循环重构为{{1 }}会检查难度是否小于0或大于4,也正如@deceze指出的那样,while difficulty > 4 or difficulty < 0:
是不需要的,因为条件只有在我们确保难度在0到4之间时才会出现,不包括0和4
所以答案变为
if
输出将类似于
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))
编写while循环的另一种方法是,我们需要确保如果输入小于0或大于4,我们希望继续运行循环,实际上可以通过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
< / p>
然后答案将更改为
while not 0 < difficulty < 4:
答案 1 :(得分:1)
尝试这样:
difficulty = int(input("Enter input :"))
while difficulty<1 or difficulty>3:
difficulty = int(input("Enter input between 1 and 3 :"))
print("correct input:",difficulty)
答案 2 :(得分:1)
“难度低于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
,因为循环已经确保该值在有效范围内;无需再次检查。
答案 3 :(得分:0)
尝试一点递归!
def getDiff():
difficulty = int(input("Difficulty: "))
if 0 < difficulty < 4:
print("The playing board was created with difficulty: " + str(difficulty))
return
else:
print("This is not a valid difficulty, please choose 1, 2 or 3")
getDiff()
getDiff()
返回难度
def getDiff():
difficulty = int(input("Difficulty: "))
if 0 < difficulty < 4:
print("The playing board was created with difficulty: " + str(difficulty))
return difficulty
else:
print("This is not a valid difficulty, please choose 1, 2 or 3")
getDiff()
difficulty = getDiff()