用户输入后如何重新启动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 "))


沧海一幻觉
浏览 153回答 3
3回答

翻翻过去那场雪

我认为最好先进入一个while循环,然后从用户那里获取输入或确定答案是否正确以及其他问题......# coding: utf-8# Start of the 1st Questionredo="y"A1=-1 # can be any integer but not the correct answern1, n2 = 2, 3while (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)

汪汪一只猫

这种程序结构没有意义。你可以做:while True:    num1 = int(input("num1 "))    num2 = int(input("num2 "))    op = '+'    calc = -1    if op == "+":        while calc != num1 + num2:            calc = int( input(f"Whats {num1} {op} {num2}?"))    elif op == "-":        pass # code the others     elif op == "*":        pass # code the others     elif op == "/":        pass # code the others - use float where needed instead of int         # comparing floats is difficult due to float math rounding imperfection    print("Correct!" , num1, op, num2,"=",calc)    again = input("Again? Y  to do it again: ").lower()    if again != "y":         break    # leaves the while True

桃花长相依

为此,您可以定义一个函数。也许它比你在课堂上做的要复杂一点,但它仍然很基础,所以你可以轻松学习它:) 使用函数时,请记住在第一次调用它以便它可以工作。这是一个例子: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 循环。但我认为这是你在课堂上的工作,所以我就这样吧:)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python