python - 用户输入后如何重新启动while循环
问题描述
我刚刚开始编码,我正在慢慢理解它。对于我的班级,我们必须制作一个儿童程序来练习他们的数学,并询问他们是否愿意再试一次,如果它是正确的。如果他们输入 Y,我无法理解如何让我的 while True 循环重新启动。有什么提示吗?这是我的代码:
#Addition
A = int(input("What is %i + %i =" %(N1, N2)))
while add != N1 + N2:
add = int(input("Incorrect, what is %i + %i = " %(N1,N2)))
while add == N1 + N2:
repeat =(input("Correct! would you like to try again? Y/N "))
if repeat == 'n':
break
if repeat == 'y':
continue
if op == "-":
#Subrtraction
s = int(input("What is %i - %i =" %(N1, N2)))
while s != N1 - N2:
s = int(input("Incorrect, what is %i - %i = " %(N1,N2)))
while s == N1 - N2:
repeat =(input("Correct! would you like to try again? Y/N "))
if op == "*":
#Multiply
m = int(input("What is %i - %i =" %(N1, N2)))
while m != N1 * N2:
m = int(input("Incorrect, what is %i - %i = " %(N1,N2)))
while m == N1 * N2:
repeat =(input("Correct! would you like to try again? Y/N "))
解决方案
为此,您可以定义一个函数。也许它比你在课堂上做的要复杂一点,但它仍然很基础,所以你可以轻松学习它:) 使用函数时,请记住在第一次调用它以便它可以工作。这是一个例子:
def function_name():
while True:
'''your code'''
repeat =(input("Correct! would you like to try again? Y/N "))
if repeat == "y":
function_name() # wach time the user say "y" the code calls the function again.
break # the break will finish the while loop and will close the program.
function_name() # that's where I call the function the first time.
顺便说一句,如果您正在使用该函数,则实际上不必使用 while 循环。但我认为这是你在课堂上的工作,所以我就这样吧:)
推荐阅读
- exception - F* 在匹配体中引发异常
- flutter - 将 RTL 添加到 ListView.builder 水平颤动
- ramda.js - RamdaJS - 如何使用具有同步和异步功能的管道?
- python - exec() 函数返回无
- powerquery - 如何将重复的行旋转到excel中的不同列
- android - Android-Kotlin 控制来自 firebase push() 的可为空字符串
- django - 使用 facebook 验证 graphql 的正确方法
- django - 在 django 中使用 URL 模板标签的问题
- r - 确定汽车和非汽车模式之间最多1小时的时差
- ssl-certificate - 使用 HTTPS 服务的 SSL 证书先决条件