How to use if statement in Python

All programming language has if statements that allow controlling the flow of the program.

With this, you can execute your code only when the condition is true or false.

In the tutorial, I show how you can use if statements in your program with an example in Python.

How to use if statement in Python


Contents

  1. if statement
  2. if else statement
  3. elif statement
  4. Nesting

1. if statement

if statement, first checks the condition if it is true then executes the block of code otherwise skip it and execute the next statement.

Syntax –

if condition :
   # true statement

# next statement

Example –

num = 4
if num%2 == 0 :
   print("Even number")

print("num : ",num)

Output

Even number
num : 4

2. if else statement

If statement only executes when condition return true if the condition is false for handling that use else statement with if. It executes when the condition is false.

Syntax –

if condition :
   # true statement
else:
   # false statement

# next statement

Example –

num = 5
if num%2 == 0 :
   print("Even number")
else:
   print("Odd number")
print("num : ",num)

Output

Odd number
num : 5

3. elif statement

elif statement allows us to define multiple if statement. If the condition is not true then again check with other conditions using elif. You can define multiple elif statements but only one else statement.

Syntax –

if condition:
   # true statement1
elif condition:
   # true statement2
elif condition:
   # true statement3
.
.
.
else:
   # false statement

# next statement

Example –

num = 30
if num == 10:
   print("If statement1")
elif num == 20:
   print("If statement2")
elif num == 30:
   print("if statement3")
else:
   print("Else statement")

print("num : ",num)

Output

if statement3
num : 30

In the above program, I defined multiple if statements using elif statement. Only one if statement will execute when you run the above program. It checks to if statement until true condition not found. If found valid condition then execute the block of code and then go to the next block of code.


4. Nesting

In a program in some cases, require to check another condition if one is true. For this purpose, generally use nested if statement using this you can define if statement within another if statement. Same you can do with else.

Syntax –

if condition:
   # true statement
   if condition:
      # true statement
   else:
      # false statement
else:
   if condition:
      # true statement
   else:
      # false statement

# next statement

Example –

num = 30
if num == 10:
   print("If statement1")
elif num == 20:
   print("If statement2")
elif num == 30:
   print("if statement3")
else:
   print("Else statement")

print("num : ",num)

Output

if statement3
num : 30

Leave a Comment