Python if else statement

Python if…else Statement

Decision making is required when we want to execute code only if a certain condition is satisfied.

1.

Python if Statement

Syntax
if (test expression):
    statement(s)

Here, the program evaluates the test expression and will execute statement(s) only if the test expression is True.

If the test expression is False, the statement(s) is not executed.

In Python, the body of if statement is indicated by the indentation. Body starts with an indentation and the first unindented line marks the end.

Python interprets non-zero values as True

None and 0 are interpreted as False.

2.
Python if…else Statement

Syntax of if…else
if (test expression):
    Body of if
else:
    Body of else

The if..else statement evaluates test expression and will execute body of if only when test condition is True.

If the condition is False, body of else is executed. Indentation is used to separate the blocks.

3.
Python if…else…if … else

Syntax of if…else … if ….else
if (test expression):
    Body of if
else:
    if (test expression):
       Body of if
    else:
     Body of else

 

4.
Python if…elif…else

Syntax of if…elif…else
 if (test expression):
    Body of if
elif (test expression):
    Body of elif
else:
    Body of else

 

Python Basic Programming Tutorial

Python Introduction     Getting started in Python Programming      Python propgramming fundamentals     Python Operators    Python If Condition     Python for loop    Python range construct      Python While loop    break and continue statements     Different looping techniques     Python List     Python String     Python Functions    Python Inbuilt Functions     Python Recursion     Using Python Library     Python Tuples     Python Dictionary     Python Sets     Python Strings     Python Exception Handling     Python Data File Handling