python tutorial

Python If Statement

Learn more about Python, one of the world’s most versatile and popular programming languages.

To get started with Python programming, you will have to learn about syntax to use conditional statements in our code. Let’s take a closer look.


What Are Conditional Statements in Python?

Let’s deep dive further into programming with Python by learning about conditional statements. Usually, code is read by a Python interpreter line-by-line in the order it is written. But, what if we want to execute a certain part of code only when it meets certain criteria?

Conditional statements are very useful in programming as they allow us to switch the execution of code based on logical decisions and criteria. They allow you to run a block of code only when certain conditions are met.

Let’s look into how to use conditional statements in your code. We will also use the reserved keywords andnot, & or that we learned about in the previous lesson.


Introduction to Python If Else Statements

if...elif...else statements are a very useful way to introduce conditional statements in your code. It allows you to execute a block of code only when certain conditions are met, or else skip to the next section of the code. Let’s take a quick look at the basic syntax of if...elif...else statements in Python.

There are two ways in which you can use if....elif...else statements. The first is when you only have one condition to check to execute a block of code, you can use the if...else statement. In this scenario, the syntax looks as follows:

Code Example
if condition:
    Block of code to execute when this condition is True. The condition can be any expression that results in a boolean value - True or False.

else:
    Block of code to execute when this condition is False. Here, the else statement does not need a condition and will be executed if the condition in the if statement is False.

In the above example, anything that follows “if:” and “else:” is indented one level by hitting tab once. This is a very important concept to keep in mind while writing your code in the notebook.

When there are multiple blocks of code that should be executed only when a relevant condition becomes True, we use the if...elif...else syntax. The else statement is optional if there is no need to execute any block of code when all conditions are False. See the hypothetical code explanation below:

Code Example
if condition: 
    Block of code to execute when this condition is True. Condition can be any expression that results in a boolean value - True or False.
elif another_condition:
    Block of code to execute when this condition is False. Here the else statement does not need a condition and will be executed if the condition in the if statement is False.
elif yet_another_condition:
    Block of code to execute when this condition is False. Here the else statement does not need a condition and will be executed if the condition in the if statement is False.
else:
    Block of code to execute when this condition is False. Here the else statement does not need a condition and will be executed if the condition in the if statement is False.

Let’s look at an example to understand both of these syntaxes. Please type the following code in your notebook and execute it line-by-line.

Code Example
grades = 75
if grades > 70:
    print("Graduated!")
else:
    print("Failed.")
#Graduated!

Here because the grades variable is assigned to a value of 75, the condition of grades > 70 will be True under the if statement, and the code will print Graduated!

Let’s look at another example of if..elif..else statement. Please type the following code line-by-line and then execute each cell.

Code Example
temp_celcius = 18
if temp_celcius > 40:
    print("Heat wave! Stay at home")
elif temp_celcius > 20 and temp_celcius <= 40:
    print("Very hot weather. Stay hydrated")
elif temp_celcius > 10 and temp_celcius <= 20:
# this is performed
    print("Great weather with cool breeze")
elif temp_celcius > 0 and temp_celcius <= 10:
    print("Weather is a bit chilly. Wear warm clothes")
else:
    print("Winter time. Grab your winter jacket")
#Great weather with cool breeze

Here, the temp_celcius variable is assigned a value of 18. The elif statement that evaluates the condition to be True is elif temp_celcius > 10 and temp_celcius <= 20. The symbol <= refers to “less than or equal to”. Also, you can see that a condition can either be a simple statement or it can be a more complex statement combined using andor, & not keywords.


Python Exercise: Control Flow

Python Exercise Overview

Let’s put the skills of using control flow statements into practice by doing a small exercise.

Create a new notebook and name it python-control-flow-exercise. Follow the steps below to implement the exercise. By end, you will learn how to write conditional logic using if...elif...else statements.

Python Exercise Instructions

  • As part of this exercise, your job is to find whether a number is even or odd. A number that is perfectly divisible by 2 (the remainder being 0), is even, else it is an odd number.
  • Create a variable called input_num and assign it a value of 3 to start with.
  • Write an if...elif...else statement as follows to determine whether the number is even or odd.
    • Check if the number is of type int and is perfectly divisible by 2 by using modulo operator %. Print the number is even.
    • Else if (elif) the number is of type int and not perfectly divisible by 2, print the number is odd.
    • Else print not a valid number.
  • Change the value stored in input_num one at a time to be 60‘a’‘hello’7.
    • Run all the cells again to check which part of the if…elif…else statement was executed and what was printed.

Python Exercise Solution

Please see the solution below to verify if your code was set up correctly.

Code Example
input_num = 3 # change this to 6, 0, 'a', 'hello', 7 one at a time and run all cells again
if type(input_num) == int and input_num % 2 == 0:
    print('the number is even')
elif type(input_num) == int and input_num % 2 != 0:
    print('the number is odd')
else:
    print('invalid number')
#the number is odd

Learn Python Today

Get hands-on experience writing code with interactive tutorials in our free online learning platform.

  • Free and fun
  • Designed for beginners
  • No downloads or setup required