Python if關鍵字



在Python中,if關鍵字允許我們建立條件語句。如果給定的條件為True,則將執行if語句塊。if關鍵字區分大小寫。

語法

以下是Pythonif關鍵字的語法:

if condition:
    statement1
	statement2

示例

在上面,我們討論了if關鍵字的語法。現在,讓我們用一個基本示例來理解if關鍵字:

var= 24
if var> 10:
    print("The Given Condition Is Satisfied ")

輸出

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

The Given Condition Is Satisfied

if關鍵字區分大小寫

Pythonif關鍵字區分大小寫。如果在if關鍵字中將i大寫,則會得到一個SyntaxError

示例

讓我們用一個例子來理解:

If True:
    print("Positive number")

輸出

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

File "E:\pgms\Keywords\if.py", line 2
    If True:
       ^^^^
SyntaxError: invalid syntax

if關鍵字在False條件下

如果給定的表示式不滿足或為False,則不會執行if塊。在這種情況下,將執行if塊之外的語句。

示例

讓我們用一個條件為False的例子來理解:

var=False
if var:
    print("This statements will not be excecuted as the condition is False.")
    
print("This statements gets excecuted as it is outside the if block.")

輸出

This statements gets excecuted as it is outside the if block.

巢狀if

如果我們在另一個if塊內使用一個或多個if塊,則稱為巢狀if。當有多個條件需要檢查時,我們使用巢狀if語句:

x=4
if True:
    print("This statement get excecuted.")
    if x%2==0:
            print("The given number is even number.")        

輸出

This statement get excecuted.
The given number is even number.
python_keywords.htm
廣告