首页 > 解决方案 > 用户输入后如何重新启动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 "))

标签: pythonpython-3.x

解决方案


为此,您可以定义一个函数。也许它比你在课堂上做的要复杂一点,但它仍然很基础,所以你可以轻松学习它:) 使用函数时,请记住在第一次调用它以便它可以工作。这是一个例子:

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 循环。但我认为这是你在课堂上的工作,所以我就这样吧:)


推荐阅读