Python else 關鍵字



在 Python 中,else 關鍵字用於條件語句。只有當 if 條件為 False 時,才會執行 else 程式碼塊。此關鍵字在語法上依賴於 if 關鍵字。如果我們在沒有 if 語句的情況下使用 else 關鍵字,我們將得到一個 SyntaxError

語法

以下是 Python else 關鍵字的語法:

if condition:
       statement1
	   statement2
else:
    statement3
	statement4

示例

以下是 Python else 關鍵字的基本示例:

if False:
    print("Hello")
else:
    print("Hello world")

輸出

以下是上述程式碼的輸出:

Hello world

在函式中使用 else 關鍵字

else 關鍵字也可以用於函式中以檢查條件語句。

示例

這裡,我們定義了一個名為 fun1 的函式來檢查數字是否為 正數

def fun1(num):
    if num<0:
        return False
    else:
        return True
x=9
print(x,"is a positive number :",fun1(x))
y=-4
print(y,"is a positive number :",fun1(y))

輸出

以下是上述程式碼的輸出:

9 is a positive number : True
-4 is a positive number : False

在迴圈中使用 else 關鍵字

else 關鍵字用於基於條件語句的 迴圈

示例

讓我們嘗試理解迴圈中的 else 關鍵字:

x=[1,2,3,4]
for i in x:
    if i%2==0:
        print(i,"is a even number in the list")
    else:
        print(i,"is not a even number in the list")

輸出

以下是上述程式碼的輸出:

1 is not a even number in the list
2 is a even number in the list
3 is not a even number in the list
4 is a even number in the list

在沒有 if 語句的情況下使用 else 關鍵字

else 關鍵字依賴於 if 條件。如果我們在沒有 if 條件的情況下使用 else 程式碼塊,我們將得到一個 SyntaxError

示例

else: 
    print("Hello")

輸出

以下是上述程式碼的輸出:

 File "E:\pgms\Keywords\else.py", line 28
    else:
    ^^^^
SyntaxError: invalid syntax

將 else 關鍵字與 elif 一起使用

當有多個條件語句要檢查時,我們可以使用 elif。如果所有給定的條件都為 False,則將執行 else 程式碼塊。

示例

這裡,是 else 與 elif 關鍵字一起使用的示例:

if False:
    print("Welcome")
elif False:
    print("To")
elif False:
    print("the")
else:
    print("Welcome to Tutorials Point")

輸出

以下是上述程式碼的輸出:

Welcome to Tutorials Point

將 else 與 try & except 塊一起使用

我們還可以將 else 關鍵字與 tryexcept 塊一起使用。在這種情況下,只有當 try 程式碼塊不引發任何錯誤時,才會執行 else 程式碼塊。

示例

讓我們嘗試執行 else 與 try 和 except 塊一起使用:

x = 5
try:
    x < 10
    print("This statement is executed")
except:
  print("Something went wrong")
else:
  print("This statement is executed only if try block is executed without raising any errors")

輸出

以下是上述程式碼的輸出:

This statement is executed
This statement is executed only if try block is executed without raising any errors

巢狀 else

當在一個 else 程式碼塊內有多個 else 時,稱為 巢狀 else

示例

這裡,是巢狀 else 的示例:

if False:
    print("This is not executed")
else:
    if False:
        print("Hello World")
    else:
        print("This statement is executed")

輸出

以下是上述程式碼的輸出:

This statement is executed
python_keywords.htm
廣告
© . All rights reserved.