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,
- 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:
Here, the program evaluates the
condition and will execute statement only if the condition is
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
0 are interpreted as
The block of lines indented the same amount after the colon
(:) will be executed whenever the condition is TRUE.
(:) 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
num = 10
if num == 10:
print("Welcome to beginnersbook.in")
Welcome to beginnersbook.in
In the above example,
num = 10 is the condition.
The body of
if is executed only if this evaluates to
When variable num is equal to 10, then the condition is true and body inside body of
if is executed.