用户输入后如何重新启动While循环

时间:2020-04-11 21:24:17

标签: python python-3.x

我刚刚开始编码,但我正在慢慢了解它。对于我的班级,我们必须制作一个儿童程序来练习他们的数学,并询问他们是否要重试是否正确。如果他们输入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 "))

3 个答案:

答案 0 :(得分:0)

这种程序结构没有意义。

您可以这样做:

let

答案 1 :(得分:0)

为此,您可以定义一个函数。也许它比您在课堂上做的要复杂一些,但是它仍然是非常基本的,因此您可以轻松学习它:) 使用函数时,请记住在第一次调用它,这样它将起作用。 这是一个例子:

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

答案 2 :(得分:0)

我认为最好先进入while循环,然后再从用户那里输入信息,或者确定答案是否正确以及其他问题……


# coding: utf-8

# Start of the 1st Question
redo="y"
A1=-1 # can be any integer but not the correct answer
n1, n2 = 2, 3

while (A1 != n1 + n2) or redo.lower()=="y":
    # ask the question
    A1 = int(input("What is the sum of %i and %i : " % (n1, n2)))

    # if answer is correct
    if A1 == n1 + n2:
        redo = input("Correct ! Would you like to try again? (Y/[N]) : ")
        if redo.lower() == "y":
            continue
        else:
            break
    else:
        print("Your Answer : %d is Incorrect!" % A1)