如果循环中有一个循环,如何中断程序?

2024-06-12 15:18:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在尝试在Python上做一个对数计算器。我离完成它只有一步之遥。代码如下:

import math
print("Welcome to logarithm calculator")

while True:
    try:
        inlog = int(input("Enter any value greater than zero to lookup its logarithm to    the base 10\n"))
        outlog = math.log(inlog, 10)
        print(outlog)

        # Here, the program will ask the user to quit or to continue
        print("Want to check another one?")
        response = input("Hit y for yes or n for no\n")

        if response == ("y" or "Y"):
            pass
        elif response == ("n" or "N"):
            break
        else:
            #I don't know what to do here so that the program asks the user to quit or continue if the response is invalid?

    except ValueError:
        print("Invalid Input: Make sure your number is greater than zero and no alphabets. Try Again.")

直到“我想再次以”或“我想”的方式回答“程序”之后。若我在这里添加另一个while循环,那个么若用户输入“y”,那个么使用pass语句就可以了。但是当用户回答为“n”时,它不会破坏程序,因为它会让我们进入外循环。 那么如何解决这个问题呢?在


Tags: orthetoinputresponsemathprogramprint
3条回答

你可以这样做:

stop=False
while True:
    try:
        inlog = int(input("Enter any value greater than zero to lookup its logarithm to    the base 10\n"))
        outlog = math.log(inlog, 10)
        print(outlog)

        # Here, the program will ask the user to quit or to continue
        print("Want to check another one?")

        while True:
            response = input("Hit y for yes or n for no\n")
            if response == ("y" or "Y"):
                stop = False
                break
            elif response == ("n" or "N"):
                stop = True
                break
            else:
                continue
        if stop:
            break
except ValueError:
        print("Invalid Input: Make sure your number

可以在初始值为“false”的值之外定义布尔参数。在每次运行外部循环的开始,您可以检查这个布尔值,如果它是真的,那么还可以中断外部循环。之后,当您想在内部循环中结束外部循环时,只需在中断内部循环之前使该值为true。这样外环也会断开。在

您可以将该测试移到其他函数:

def read_more():
    while True:
        print("Want to check another one?")
        response = input("Hit y for yes or n for no\n")

        if response == ("y" or "Y"):
            return True
        elif response == ("n" or "N"):
            return False
        else:
            continue

然后在函数中,只需测试此方法的返回类型:

^{pr2}$

请注意,如果用户继续输入错误的输入,您可以进入无限循环。你可以限制他最多尝试几次。在

相关问题 更多 >