if elif else Statement in Python

The if, if-else or if-elif-else statement are most-used statement in Python world. Since these provides to implement conditions in a program. And based on those conditions, automatically or dynamically, the decisions can be taken by the program. Therefore, without complete understanding about these statements, don't move forward. This is like the basic building block of Python programming.

Therefore, I've provided all these three conditional statements in one single tutorial, with its description, syntax, and well-understandable examples. This article deals with:

  • if Statement
  • if...else Statement
  • if...elif...else Statement
  • Nested if, if...else, if...elif...else Statement

if Statement

The if statement is used, where we've to work with only one condition. That is, the program takes the decision using only one condition, provided using if

if Statement Syntax

The syntax to use if statement in a Python program is:

if expression:
    statement(s)

The expression indicates to the conditional_expression code. The statement(s) of if gets executed, only if the conditional_expression code evaluates to be True. Otherwise, program flow does not goes to if's body.

if Statement Example

Since the theory part of if gets completed. Therefore, let's take some examples, to get clear understanding about the statement. Here is a very basic example, uses if statement:

num = 10
print("Welcome to codescracker.com")
if num>0:
    print("\"num\" holds a positive number.")
print("Exiting the program...")

The output produced by above program is:

if statement in python

Now let's modify the above program. That is, let's initialize the variable num with a value, that is a negative number like shown in the program given below, and re-run the program again to see its new output:

num = -10
print("Welcome to codescracker.com")
if num>0:
    print("\"num\" holds a positive number.")
print("Exiting the program...")

Now this program produces following output:

if statement example python

As you can see from both example programs given above. In first program, the condition, num>0 or 10>0 evaluates to be True, therefore program flow goes inside the if's body and execute all the statements present inside its block of body. Since, I've written only one statement, therefore only that one statement gets executed, that prints "num" holds a positive number. on output.

Rest of the two print statements, that is one written above the if and the second written below the if's body, doesn't cares about if. That two statements always gets printed.

Now in the second program, since the value of num is -10 this time, therefore the condition num>0 or -10>0 evaluates to be False. Therefore program flow doesn't goes inside the if's body. So the message "num" holds a positive number. doesn't gets printed in second program.

Let's take one more example of Python if statement, to provide you the clue about, how an if statement can also be used in a password protected program:

print("Welcome to codescracker.com")
print("Enter Your Password: ", end="")
pwd = input()
if pwd == "123@codescracker":
    print("\nAccess Granted!")

The snapshot given below shows the sample output produced by above program, after providing 123@codescracker as user input:

if statement password protection

That is, the user only gets accessed to some special section or feature, if he/she enters the correct password. In above program, I've only given you the hint about how an if statement can be used to protect some section. Since, this is just a demo program, therefore I've directly compared the entered password with any random like 123@codescracker. But in working application, generally we fetched the user's password from database and then checked with his/her entered password.

if Statement without Conditional Expression

Note - The conditional_expression used in if statement is basically a boolean expression. Boolean expression means an expression that returns either True or False. The is, after evaluating the boolean expression, we can get either True or False.

We can also replace the conditional_expression of if statement using direct variable or object. In that case, what the variable or object's value is, decides whether to enter in the if's body or not.

These are the list of values, are all considered as False:

  • 0
  • 0.0, or anything equivalent to 0
  • None
  • False
  • '' (this is a single empty quotation, that is ' ')
  • ""
  • ()
  • []
  • {}

Except above list of values, all other values are considered as True like 1, 24, True, "codescracker" etc.

As told above, if the variable's value is 0 or False, then it gets treated as False, and the program flow never goes to that if's body. Otherwise all the variable's value (like 1, 2, -2, -4 etc.) including True gets treated as True, therefore program flow goes inside the if's body. Let's take an example to get complete understanding on it.

num_one = 10
num_two = 0
num_three = True
num_four = False
num_five = -10

if num_one:
    print("The value of \"num_one\" is", num_one)
if num_two:
    print("The value of \"num_two\" is", num_two)
if num_three:
    print("The value of \"num_three\" is", num_three)
if num_four:
    print("The value of \"num_four\" is", num_four)
if num_five:
    print("The value of \"num_five\" is", num_five)

This program produces the output like shown in the snapshot given below:

python if statement

if Statement in One Line

If inside the body of if, there is only one statement, then we can create if in one line. Here is its syntax to use if in one line:

if expression: statement

The example given below shows if statement program with whole if block created in one line:

num = 10
if num>0: print("Positive")

Prints Positive on output. But single line if block can not be used if there are multiple statements available in if's body.

if...else Statement

The if...else statement is basically the improved version of if statement. That is, in if statement of Python, we can only execute some set of statements only when the condition provided is True, otherwise when condition evaluates to be False, then nothing to execute. But for a change, if...else is created to also execute some set of statements even when the condition evaluates to be False.

That is, using if...else we'll have two bodies. One of if and second of else. The if's body statement(s) gets executed, if the condition evaluates to be True, otherwise if the condition evaluates to be False, then the else's body statement(s) gets executed.

if...else Syntax

Let's have a look at the syntax of if...else statement:

if expression:
    statement(s)
else:
    statement(s)

As you can see, using else, we are able to execute statement(s) when the condition of if evaluates to be False.

if...else Example

In programming world, without implementing the things into practical way, we can not understand the thing in clear and complete way. Therefore, I've provided you all the necessary programs that gives more concentration and complete understanding on the topic. Now in this if...else example section, I've taken the same example as provided for if, that is:

num = 10
print("Welcome to codescracker.com")
if num>0:
    print("\"num\" holds a positive number.")
else:
    print("\"num\" holds zero or a negative number.")
print("Exiting the program...")

The output produced by above program is shown in the snapshot given below:

if else statement in python

Now let's change the above program as done in if's example:

num = -10
print("Welcome to codescracker.com")
if num>0:
    print("\"num\" holds a positive number.")
else:
    print("\"num\" holds zero or a negative number.")
print("Exiting the program...")

Now this time, since we've an else block, that is the counterpart of if, we're able to execute some set of statements when the condition evaluates to be False. Here is its sample run:

if else example python

As you can see, when the condition num>0 or -10>0 evaluates to be False, then the program flow goes to else's body and execute all the statements available in its body. Since in above program, I've created only one statement inside else's body, therefore that one statement gets executed, that prints "num" holds zero or a negative number. on output like shown in the snapshot given above.

Now let's re-create that password protection program using if-else, that was created in if section. Since, I'm going to create the same program using if-else, therefore it provides a good user experience (UX). Because using else, we are able to provide the message to user that shows what if they enters a wrong password like shown in the program given below:

print("Welcome to codescracker.com")
print("Enter Your Password: ", end="")
pwd = input()
if pwd == "123@codescracker":
    print("\nAccess Granted!")
else:
    print("\nAccess Denied!")

Here is its sample run with user input codescracker as password. Since the password is 123@codescracker, not codescracker, therefore you'll see the following output:

python if-else program

if...else without Conditional Expression

Let's take one last example of if-else statement. I hope this will clear all remaining doubt (if any) about if...else:

num_one = 10
num_two = 0
num_three = True
num_four = False
num_five = -10

if num_one:
    print("The value of \"num_one\" is", num_one)
else:
    print("The value of \"num_on\" is", num_one)
if num_two:
    print("The value of \"num_two\" is", num_two)
else:
    print("The value of \"num_two\" is", num_two)
if num_three:
    print("The value of \"num_three\" is", num_three)
else:
    print("The value of \"num_three\" is", num_three)
if num_four:
    print("The value of \"num_four\" is", num_four)
else:
    print("The value of \"num_four\" is", num_four)
if num_five:
    print("The value of \"num_five\" is", num_five)
else:
    print("The value of \"num_five\" is", num_five)

This program produces:

python if else

As you can see, either the statement of if or of its else gets executed, but not both in all five cases of if...else block.

if...else in One Line

This can be done with the help of ternary operator. I've created a separate tutorial on ternary operator or single line if...else statement of Python. Feel free to refer, that tutorial provides you in-depth learning on the topic.

if...elif...else Statement

To use multiple conditions, we need if...elif...else statement. In if...elif...else, the elif is considered as else if

if...elif...else Syntax

Here is the syntax used for if...elif...else statement. We can create as many boolean expression as we want.

if expression_1:
    statement(s)
elif expression_2:
    statement(s)
elif expression_3:
    statement(s)
.
.
.
elif expression_n:
    statement(s)
else:
    statement(s)

The if...elif...else's syntax (as provided above) works in a way that:

  • First the expression_1 gets evaluated
  • If expression_1 evaluates to be True, then program flow goes inside this if's body and evaluates all of its statement(s)
  • And if expression_1 evaluates to be False, then program flow goes to the first elif and evaluates the expression_2
  • If expression_2 evaluates to be True, then program flow goes inside this elif's body and evaluates all of its statement(s)
  • And if expression_2 evaluates to be False, then program flow goes to the second elif and evaluates the expression_3
  • If expression_3 evaluates to be True, then program flow goes inside this elif's body and evaluates all of its statement(s)
  • This process continues, until the last expression or expression_n
  • The statement(s) of else gets executed, only when the last expression (expression_n) evaluates to be False
  • While executing the expressions of if...elif...else statement, any expression evaluates to be True, then program flow goes to that body and executes all its statement(s). And rest part of the whole if...elif...else block gets skipped
  • That is, the process of evaluating all the expression continues, until we get True. Otherwise, if all condition evaluates to be False, then else body's statement(s) gets executed.

if...elif...else Example

Let's take first example of this tutorial again and get better understanding about where and why we use if...elif...else statement:

num = 10
print("Welcome to codescracker.com")
if num>0:
    print("\"num\" holds a positive number.")
elif num==0:
    print("\"num\" holds 0.")
else:
    print("\"num\" holds a negative number.")
print("Exiting the program...")

The output produced by above program is exactly same as of first program's output like shown in the snapshot given below:

if statement in python

Now let's modify the program, with variable num with its value as 1, 0, and -1 in one program like shown in the program given below:

num = 1
print("\n--------When \"num = 1\"----------")
if num>0:
    print("\"num\" holds a positive number.")
elif num==0:
    print("\"num\" holds 0.")
else:
    print("\"num\" holds a negative number.")

num = 0
print("\n--------When \"num = 0\"----------")
if num>0:
    print("\"num\" holds a positive number.")
elif num==0:
    print("\"num\" holds 0.")
else:
    print("\"num\" holds a negative number.")

num = -1
print("\n--------When \"num = -1\"----------")
if num>0:
    print("\"num\" holds a positive number.")
elif num==0:
    print("\"num\" holds 0.")
else:
    print("\"num\" holds a negative number.")

The output produced by above program is:

python if elif else

Nested if, if...else, if...elif...else Statement

We can also nest one conditional statement inside another like shown in the program given below:

print("Enter any Number: ", end="")
num = int(input())

if num>0:
    if num>10:
        print("It is greater than 10.")
    elif num>100:
        if num>50:
            print("It is greater than 50.")
        else:
            print("It is greater than 100.")
    elif num>500:
        print("It is greater than 500.")
    elif num>1000000:
        print("It is greater than 1000000.")
    else:
        print("It is less than 10.")
elif num==0:
    print("It is 0.")
else:
    if num>-10:
        print("It is between -1 to -9.")
    else:
        print("It is less than -9.")

Here is its sample run with user input 600:

if-elif-else example python

Note - As you can see from above program, since the first if's expression inside first if, that is num>10 or 600>10 evaluates to be True. Therefore rest of all the expression (of elifs) does not gets evaluated, rather program flow goes inside this if's body and prints the message saying It is greater than 10.. And rest of all conditional statements available in same indentation gets skipped.

To get more programs on nested conditional statements, refer to Find Largest of Three Numbers. There, I've created a program with nested if...elif...else that contains 18 conditional statements in a single program.

More Examples

These are the list of example programs, that you may like to practice. All these programs contains if, if-else, or if-elif-else statements:

Python Online Test


« Previous Tutorial Next Tutorial »