如果循环中有循环,如何打破程序?

时间:2013-02-10 09:37:20

标签: python loops

我一直在尝试在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.")

在else语句之后,我希望程序要求用户一次又一次地响应,直到它是“y”或“Y”和“n”或“N”的有效响应。如果我在这里添加另一个while循环,如果用户输入“y”,它将适用于pass语句。但是当用户以“n”响应时它不会破坏程序,因为它会使我们进入外循环。 那么如何解决这个问题呢?

6 个答案:

答案 0 :(得分:4)

您可以将该测试移动到其他功能:

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

然后在你的函数中,只测试这个方法的返回类型:

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)

        if read_more():
            continue
        else:
            break

请注意,如果用户继续输入错误的输入,您可以进入无限循环。你可以限制他达到一些最大的尝试次数。

答案 1 :(得分:1)

您可以这样做:

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

答案 2 :(得分:0)

您可以在值之外定义一个布尔参数,初始值为'false'。在外部循环的每次运行开始时,您可以检查此布尔值,如果为true,则还要断开外部循环。之后,当你想在内部循环中结束外部循环时,只需在打破内部循环之前使值为true。这样外环也会破裂。

答案 3 :(得分:0)

试试这个:

import math
class quitit(Exception):
    pass
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?")
        while True: 
            response = input("Hit y for yes or n for no\n")
            if response == ("y" or "Y"):
                break
            elif response == ("n" or "N"):
                raise quitit
except quitit:
        print "Terminated!"        
except ValueError:
        print("Invalid Input: Make sure your number is greater than zero and no alphabets. Try Again.")

答案 4 :(得分:0)

如果用户输入的数字小于或等于零,则会产生您未考虑的异常。

至于突破循环,它不会太嵌套,你不能突破。如果你有更深的嵌套,那么我建议使用以下模板来打破嵌套循环。

def loopbreak():
  while True:
    while True:
      print('Breaking out of function')
      return
  print('This statement will not print, the function has already returned')

答案 5 :(得分:0)

stop=False
while not stop:
    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 = raw_input("Hit y for yes or n for no\n")
            if response == ("y" or "Y"):
                break
            elif response == ("n" or "N"):
                stop = True
                break
    except ValueError:
        print("Invalid Input: Make sure your number")