简体   繁体   中英

Using the “Break” Control Flow in Python 3

First time here. Thanks in advance for the help. I successfully met the requirements of the problem below. However, I am trying to learn to use the "break" statement to elegantly terminate the loop instead of having the program to crash.

As simple as it might sound, I get returned an error when using the "break" statement.

Perhaps it is because the "eval" mention, which is used to input numerical values and not strings such as "QUIT" to break the loop?

"Write an interactive Python calculator program. The program should allow the user to type a math expression, and then print the value of the expression. Include a loop so that the user can perform many calculations. Note: To quit early, the user can make the program crash by typing a bad expression or simply closing the window that the program the calculator program is running in. You'll learn better ways of terminating interactive programs in later chapters."

def main():
    print("This program allows you to get the result of a math expression!")
    while True:
        expr = eval(input("Enter a mathematical expression: "))
        print ("The result of the math expression is {}".format(expr))
        if expr == "QUIT":
            break
main()

Thoughts?

UPDATE

As suggested by Scott Hunter below, I brought the following changes to the code and it worked flawlessly. The "eval" statement did not recognized the string "QUIT" as "eval" is used to evaluate numerical values. Thanks Scott.

Here is the updated code:

def main():
    print("This program allows you to get the result of a math expression!")
    while True:
        expr =(input("Enter a mathematical expression: "))
        if expr == "QUIT":
            break
        else:
            expr = eval(expr)
        print ("The result of the math expression is {}".format(expr))
main()

You should wait to use eval until you know that the user hasn't entered QUIT ; something like this:

while True:
    expr = input(...)
    if expire == "QUIT":
        break
    expr = eval(expr)
    print( ... )

The break control doesn't end a program, but rather it "breaks out" of whatever code level you're at:

i = 1
while True:
    i += 1
    if i > 10:
        break
print('Hello!')

The break in the code above will end execution of the while loop. It will not end the entire program, so you will still see 'Hello' in the console. If you want to end a procedure completely, use return . If you are trying to exit the entire script, you can import sys and use sys.exit() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM