不能在while循环中使用while循环来工作

时间:2015-03-26 23:01:11

标签: python loops while-loop

while loop == True:                                                                             #creates loop, and uses previously defined 'loop'
    try:
        ans = int(input("What is the answer to " + str(num1) + " x " + str(num2) + " ? "))      #asks question and requires a user input
        correct = (ans == num1 * num2)
        if correct:
            invtimer()
            print("You are correct! ")
            break                                                                               #if the answer is correct, it prints 'You are correct!' and breaks to avoid the loop
        else:
            invtimer()
   while loop == True:
            showans = input('''Wrong answer.
Would you like to see the answer? (yes)(y)
or try again? (no)(n) ''')
            if showans in ["yes", "y", "Yes", "Y"]:
                invtimer()
                print("The answer is " + str(num1 * num2) + "!")
                break
            elif showans in ["no", "n", "No", "N"]:
                loop == False
            else:
                print("That is not an option! ") 
                loop == False
    except ValueError:
        print("That is not a number! ") 

我需要帮助才能获得第二个循环== False以在循环时链接回第一个循环。当我运行它时,它会一直回到第二个while循环。

1 个答案:

答案 0 :(得分:3)

您使用的是==运算符。此运算符仅用于条件语句和循环,而不是在分配变量时使用。当您将False分配给变量时,请使用=代替

while loop == True:                                                                             #creates loop, and uses previously defined 'loop'
    try:
        ans = int(input("What is the answer to " + str(num1) + " x " + str(num2) + " ? "))      #asks question and requires a user input
        correct = (ans == num1 * num2)
        if correct:
            invtimer()
            print("You are correct! ")
            break                                                                               #if the answer is correct, it prints 'You are correct!' and breaks to avoid the loop
        else:
            invtimer()
        while loop == True:
            showans = input('''Wrong answer.
Would you like to see the answer? (yes)(y)
or try again? (no)(n) ''')
            if showans in ["yes", "y", "Yes", "Y"]:
                invtimer()
                print("The answer is " + str(num1 * num2) + "!")
                break
            elif showans in ["no", "n", "No", "N"]:
                loop = False
            else:
                print("That is not an option! ") 
                loop = False
    except ValueError:
        print("That is not a number! ")