我正在为学校做一个小项目,我们需要在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))发布于 2019-05-10 07:24:00
when循环0 > difficulty > 4从不执行,因为该条件总是计算为False,因为0 > 4是False,因此我会将when循环重构为while difficulty > 4 or difficulty < 0:,这将检查困难是否小于0,还是大于4,也像@deceze指出的那样,if不需要,因为只有当我们确保我们的困难在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))输出将类似于
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))发布于 2019-05-10 07:25:32
就像这样:
difficulty = int(input("Enter input :"))
while difficulty<1 or difficulty>3:
difficulty = int(input("Enter input between 1 and 3 :"))
print("correct input:",difficulty)发布于 2019-05-10 07:30:03
“困难小于0,困难大于4”不可能是真的,因为没有一个同时小于0和大于4的数字。
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,因为循环已经确保该值在有效范围内;无需再次检查。
https://stackoverflow.com/questions/56072608
复制相似问题