Python if Statement

Python provides conditional branching with if statement. The Python if statement is a statement which is used to test specified condition. You can use this statements when you want the program to take some decisions and do different things depending on different situations.

Note that, there is no switch statement in python. you can use if..elif...else statement to do the same thing.

The if statement executes only when specified condition is true. We can pass any valid expression into the if parentheses.

There are various types of flow statements available in Python such as,

if..else

if..elif..else

nested if etc.

However in this guide, we will only cover the if statements, other control statements are covered in separate tutorials.

Syntax of if statement

This is the simplest example of a conditional statement. The syntax is:

1

2

if(condition):

Block_of_code

Here, the program evaluates the condition and will execute statement only if the condition is True.

If the condition is False, the statement is not executed.

In Python, the body of the 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.

The block of lines indented the same amount after the colon (:) will be executed whenever the condition is TRUE.

The colon (:) is important because it separates the condition from the statements to be executed after the evaluation of the condition.

Flow Diagram of if statement

Let’s understand this flow diagram: if the expression is TRUE, code inside the if body will run. Otherwise it returns FALSE and will run another block of statement (if there is else block).

Python – if statement Example

1

2

3

num=10

ifnum==10:

print("Welcome to beginnersbook.in")

When you run above program, the output will be following:

1

Welcome to beginnersbook.in

In above example, code would run fine because here the condition is satisfied, hence it returns TRUE value.

In the above example, num = 10 is the condition.

The body of if is executed only if this evaluates to True.

When variable num is equal to 10, then the condition is true and body inside body of if is executed.