簡體   English   中英

在這種情況下,由於“ else”語句不起作用,如何顯示“ Error”消息?

[英]How to get the the “Error” message printed in this situation because the “else” statement doesn't work?

編寫程序,讀取輸入的三個整數a,b和c。 如果整數c等於1,則程序在輸出(打印)上顯示a + b的值; 如果c為2,則程序顯示ab的值; 如果c等於3,則輸出將為a的值 最后,如果將值4分配給c,則程序將顯示a ^ 2 + b a的值。 如果c包含另一個值,程序將顯示消息“錯誤”

a = int(input())
b = int(input())
c = int(input())

if c == 1:
    print(a + b)

if c == 2:
    print(a - b)

if c == 3:
    print(a * b)

if c == 4:
    print(a**2 + b*a)

else:
    print('Error')

您的if工作正常,但邏輯有些偏離。

使用if elifelse

if c==something:
    print("this")
elif c==something_else:
    print("that")
else:
    print("error") 

在第一個if語句之后,應該使用elif ,它是“ else if”的縮寫。 沒有錯誤消息是因為沒有錯誤,您只是邏輯錯了。 編譯器將獨立處理每個if語句,因此else運行只要c不為4。

好像您已經明白了,只需使用elif而不是ifs鏈,您還可以在input('Here')中添加一條消息,該消息將在提示輸入時顯示

a = int(input("Enter a number: ))

b = int(input("Enter a number: ))

c = int(input("Enter a number: ))

if c == 1 :
    print(a + b)
elif c == 2 :
    print(a - b)
elif c == 3 :
    print(a * b)
elif c == 4 :
    print(a**2 + b*a)
else:
    print('Error')

你快到了 程序的主要問題是if語句是獨立的,而問題語句表明它們不應該是獨立的。 將其更改為elif語句,這意味着您的Error分支僅在c評估為不在集合{1, 2, 3, 4}的整數時才執行。


問題1:程序(可能)的控制流很差

在大多數編程語言中, if語句是一種基本構造,用於在表達式為true時有條件地執行代碼塊。 在下面的類Python偽代碼,后面的代碼if只執行塊如果通過評估獲得的值EXPRESSION為真:

if EXPRESSION:
    # Do something only if EXPRESSION is true

# Execution continues here after the "if" block irrespective of
# whether EXPRESSION was true and the body of the "if" statement
# was executed.

您可以使用else分支來擴充if語句。 在這種情況下,如果EXPRESSION評估結果為true,則執行if語句的主體, if條件的評估結果為true,則執行分支的另一分支( else分支)(根據排除中間的定律,則為false) ):

if EXPRESSION:
    # As before, control is passed here if EXPRESSION is true.
else:
    # If EXPRESSION was false, control is passed to this arm.

# After executing either the "if" arm or the "else" arm, control
# returns to the outer scope outside the "if" statement.

更復雜的構造使用else-if構造允許您嵌套 “ if”語句。 例如,假設我們正在實現一個簡單的呼叫控制器,該控制器會嘗試使用固定電話聯系某人,如果他們的便攜式電話不可用,則呼叫他們的便攜式電話,否則將發送電子郵件。 利用上面的知識,我們可以這樣寫:

if answers(fixed_telephone):
    # Connect to the fixed telephone to communicate
else:
    if answers(portable_telephone):
        # Connect to the portable telephone to communicate
    else:
        # Not available on either telephone. Send an email.

您可以想象,如果存在許多嵌套的“ if”條件,則此邏輯將很快變得復雜,這在實際情況中並不罕見。 大多數編程語言都提供了一種將嵌套的“ if”語句拉到頂層的結構。 在Python中,這是elif ,上面的等效代碼是:

if answers(fixed_telephone):
    # ...
elif answers(portable_telephone):
    # ...
else:
    # ...

(為簡潔起見,省略了評論)。

在當前編寫的代碼中, 除了最后一個if c == 4 之外 ,每個if語句都將獨立執行,如果c不等於if c == 4 ,它將落入else分支。因為您希望c的測試相互進行排他性,即,如果通過了較早的案例,您不希望發生任何事情,並且僅希望在未執行任何案例的情況下打印錯誤,則應使用嵌套的if語句,最好使用上述elif語言構造來實現。


問題2:程序采用格式正確的整數

您的程序還假定從STDIN讀取的abc是格式正確的整數。 如果輸入的值無法解析為整數,則它將在int(...)調用中在進行整數轉換時崩潰,並且不會掉線到達您的print('Error')行。 這是Python引發異常的示例,因為遇到了解釋器本身無法恢復的問題。 控制流將不會開始執行if塊,因此將永遠不會執行print語句。

如果您想解決問題,則當int(...)方法無法將提供的值解析為整數時,需要捕獲該錯誤。 這意味着要學習捕獲異常,您可以在Python文檔中找到更多信息

(提示:當無法解析到int的輸入時,Python將引發類型為ValueError的內置異常,因此您需要使用try... catch包裹那些填充三個變量abc的調用try... catch塊來捕獲這樣的錯誤:

try:
    a = int(input())
catch ValueError:
    # Implement logic to handle this error, which may include
    # returning an error from your function, setting a default
    # value, or taking some action. You can optionally take
    # some action locally, such as print a log message, and then
    # re-raise the exception so it propagates to this method's
    # callers (using the "raise" keyword).

暫無
暫無

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

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