我有这段代码:
def begin(): # the main attraction.
print("Select difficulty level\n")
print("E - Easy. Data set is 5 numbers long, and the set is sorted\n")
print("M - Medium. Data set is 7 numbers long and the set is sorted\n")
print("H - Hard. Data set is 10 numbers long and the set is not sorted\n")
difficultySelect = input()
if difficultySelect == "E" or "e":
worksheet.beginGameLoop("easy")
elif difficultySelect == "M" or "m":
worksheet.beginGameLoop("med")
elif difficultySelect == "H" or "h":
worksheet.beginGameLoop("hard")
def beginGameLoop(gameDifficulty):
if gameDifficulty == "easy":
length = 5
sorting = True
elif gameDifficulty == "med":
length = 7
sorting = True
elif gameDifficulty == "hard":
length = 10
sorting = False
for questions in range(10):
invalidPrinted = False
questions, answer, qType = worksheet.createQuestion(length, sorting)
当我运行它时,它似乎停留在easy-mode的变量上。可能是什么问题? 编辑:整个事情是here.
答案 0 :(得分:3)
问题在于:
if difficultySelect == "E" or "e":
worksheet.beginGameLoop("easy")
elif difficultySelect == "M" or "m":
worksheet.beginGameLoop("med")
elif difficultySelect == "H" or "h":
它应该是:
if difficultySelect == "E" or difficultySelect == "e":
worksheet.beginGameLoop("easy")
elif difficultySelect == "M" or difficultySelect == "m":
worksheet.beginGameLoop("med")
elif difficultySelect == "H" or difficultySelect == "h":
甚至更好:
if difficultySelect in ("E", "e"):
worksheet.beginGameLoop("easy")
elif difficultySelect in ("M", "m"):
worksheet.beginGameLoop("med")
elif difficultySelect in ("H", "h"):
声明if x == 'a' or 'b'
将永远为真。在Python中,or
语句的结果是False
或第一个不是False
的计算语句的值。因此,在您的情况下,True
如果difficultySelect
等于E
或e
,则为e
。并且False
始终不是{{1}} - 这就是为什么始终满足第一个条件。
答案 1 :(得分:0)
看起来你的for
循环缩进太多了。
if gameDifficulty == "easy":
length = 5
sorting = True
elif gameDifficulty == "med":
length = 7
sorting = True
elif gameDifficulty == "hard":
length = 10
sorting = False
for questions in range(length):
invalidPrinted = False
questions, answer, qType = worksheet.createQuestion(length, sorting)