Python if Keyword



In Python, The if keyword allows us to create a conditional statements. If the given condition is True than the block of if statement will be executed. if keyword is case-sensitive.

Syntax

Following is the syntax of Python if keyword −

if condition:
    statement1
	statement2

Example

In the above, We have discussed the syntax of if keyword. Now, lets understand if keyword with a basic example −

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

Output

Following is the output of the above code −

The Given Condition Is Satisfied

if keyword is case-sensitive

The Python if keyword is case-sensitive. If i is capitalized in the if keyword than we will get a SyntaxError.

Example

Let understand with an example −

If True:
    print("Positive number")

Output

Following is the output of the above code −

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

if keyword in False condition

If the given expression is not satisfied or False than the if block will not be executed. In such conditions the statements outside the if block will be excecuted.

Example

Lets understand with an example if the condition is 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.")

Output

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

Nested if

If we use one or more if blocks inside another if block, it is called a nested if. When there are more conditions to check, we use nested if statements −

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

Output

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