提问人:Big_Port 提问时间:7/21/2023 更新时间:7/21/2023 访问量:47
我的代码跳过了 does not through the whole else 语句
My code skips the does not go through the whole else statement
问:
因此,我正在制作一个数学游戏,用户可以尝试三次来回答问题,如果没有,它会显示答案并转到下一个问题,但是我的代码只允许他们在进入下一个问题之前出错一次。我做错了什么
nQuestions = 0
cAnswers = 0
attempts = 0
lvl = get_level()
while nQuestions != 10:
if attempts == 0:
x, y = generate_integer(lvl)
answer = x + y
sum = int(input(f"{x} + {y} = "))
if sum == answer:
cAnswers += 1
attempts = 0
nQuestions +=1
continue
else:
attempts += 1
if attempts == 3:
print(f"{x} + {y} = {answer}")
attempts = 0
nQuestions += 1
continue
答:
0赞
Niveditha S
7/21/2023
#1
这是因为您的代码只允许用户输入一次。当尝试次数少于 3 次时,您应该要求用户再次输入(重试)。
以下作品:
nQuestions = 0
cAnswers = 0
lvl = get_level()
while nQuestions < 10:
x, y = generate_integer(lvl)
answer = x + y
#sum = int(input(f"{x} + {y} = "))
attempts = 0
while attempts<3:
sum = int(input(f"{x} + {y} = "))
if sum == answer:
cAnswers += 1
nQuestions +=1
break
else:
attempts += 1
if attempts == 3:
print(f"{x} + {y} = {answer}")
nQuestions += 1
评论
1赞
ShadowRanger
7/21/2023
注意:由于 Python 允许 else
链接到 while
和 for
循环,您可以只替换为 .如果退出时没有 ,则该块将执行,如果由于 (或 或抛出异常)而退出,则该块将被跳过。if attempts == 3:
else:
else:
while
break
break
return
评论
if attempts == 0:
sum = int(input(f"{x} + {y} = "))