簡體   English   中英

在Python 3中使用“中斷”控制流

[英]Using the “Break” Control Flow in Python 3

第一次來這里。 先謝謝您的幫助。 我已成功滿足以下問題的要求。 但是,我試圖學習使用“ break”語句優雅地終止循環,而不是使程序崩潰。

聽起來很簡單,但是在使用“ break”語句時卻返回了錯誤。

也許是因為提到了“ eval”,它用於輸入數值而不是字符串(例如“ QUIT”)來打破循環?

“編寫一個交互式Python計算器程序。該程序應允許用戶鍵入數學表達式,然后打印該表達式的值。包括一個循環,以便用戶可以執行許多計算。注意:要提早退出,用戶可以通過鍵入錯誤的表達式或簡單地關閉計算器程序正在運行的程序的窗口,可以使程序崩潰。在后面的章節中,您將學到更好的終止交互式程序的方法。”

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()

思考?

UPDATE

正如下面的Scott Hunter所建議的那樣,我對代碼進行了以下更改,並且可以完美地工作。 “ eval”語句未識別字符串“ QUIT”,因為“ eval”用於評估數值。 謝謝斯科特。

這是更新的代碼:

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()

您應該等待使用eval直到您知道用戶尚未輸入QUIT為止; 像這樣的東西:

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

break控件不會結束程序,而是會“中斷”您所處於的任何代碼級別:

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

上面代碼中的break將結束while循環的執行。 它不會結束整個程序,因此您仍然會在控制台中看到'Hello' 如果要完全結束過程,請使用return 如果要退出整個腳本,則可以導入sys並使用sys.exit()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM