Click to share! ⬇️

python if statement

The Python if statement allows you to investigate the current state of a program and respond accordingly to that state. You can write a basic if statement that checks one condition, or you can create a series of if statements that identify the exact conditions you’re looking for. Some other languages offer a switch, or case, statement for these. Python keeps it simple and sticks with the if statement only. If statements are used for conditional tests, checking user input, numerical comparison, multi-condition checks, boolean values, and so on. In this tutorial, we’ll take a look at conditional tests, if, if-else, if-elif-else, and how to use conditional checks in loops.


Conditional Tests

An expression that can be tested as True or False is a conditional check. Python uses the True and False values to evaluate whether the code should be executed in an if statement.

Checking for equality

A double equal sign (==) checks whether two values are equal. This is not to be confused with the assignment operator which is a single equal sign, and assigns a value to a variable.

language = 'python'
language == 'python'
True
language = 'javascript'
language == 'python'
False

Ignoring case when making a comparison

sandwich = 'Ham'
sandwich.lower() == 'ham'
True

Checking for inequality

vegetable = 'potato'
vegetable != 'potahto'
True

If statements

There are a few kinds of if statements to be aware of. Your choice of which to use depends on how many conditions you need to test. So you may use if, if-else, if-elif, or if-elif-else chains. The else block is optional.

Basic if statement

color = 'Green'
if color == 'Green':
    print('Go!')

if-else statement

color = 'Orange'
if color == 'Green':
    print('Go!')
else:
    print('Don't Go!')

if-elif-else statement

color = 'Green'
if color == 'Red':
    takeaction = 'Stop'
elif color == 'Yellow':
    takeaction = 'Slow Down'
elif color == 'Green':
    takeaction = 'Go'
else:
    takeaction = 'Maintain current state'
print(f'You need to {takeaction}.')

Using If Statements With Lists

The if statement is quite useful in combination with lists.

Check if a value is not included in a list

foods = ['Snickers', 'Kit Kat', 'Butterfinger']
vegetable = 'Broccoli'
if vegetable not in foods:
    print("Eat some vegetables!")
Eat some vegetables!

Test whether a list is empty

cats = []
if cats:
    for cat in cats:
        print(f"Cat: {cat.title()}")
else:
    print("Thank God we have no cats!")
Thank God we have no cats!

Conditional tests with lists

To test whether a certain value is in a list, you can use the in keyword.

programs = ['Photoshop', 'Illustrator', 'InDesign', 'Animate', 'Acrobat']
using = input('What program are you using? ')

if using in programs:
    print('That program is made by Adobe')
else:
    print('That is not an Adobe product')

python in keyword


Checking User Input

You can use the input statement to allow your users to enter the data which we can check using the if statement. All input is initially stored as a string data type. You will need to convert the value of the input string to a numerical form if you want to accept numerical data.

A basic input example

fruit = input("What is your favorite fruit? ")
print(f"{fruit} is a great fruit!")

python accept input

Getting numerical input using int()

favnum = input("What is your favorite number? ")
favnum = int(favnum)
if favnum == 7:
    print(f"{favnum} is also my favorite!")
else:
    print(f"{favnum} is a good choice!")

python numerical input with int

Accepting numerical input via float()

pi = input("What is the value of pi? ")
pi = float(pi)
print(type(pi))

python num input as float


Numerical comparisons

Numeric values testing is similar to string values testing.

Testing equality and inequality

num = 17
num == 17
# True

num != 17
# False

Comparison operators

num = 250
num < 777
# True

num <= 777
# True

num > 777
# False

num >= 777
# False

Testing multiple conditions

You can simultaneously check multiple conditions. The and operator returns True if all the conditions listed are True. The or operator returns True if any condition is True.

Using and to check multiple conditions

num_0 = 12
num_1 = 8
res = num_0 >= 11 and num_1 >= 11
print(res)
# False

num_1 = 23
res = num_0 >= 11 and num_1 >= 11
print(res)
# True

Using or to check multiple conditions

num_0 = 12
num_1 = 8
res = num_0 >= 11 or num_1 >= 11
print(res)
# True

num_1 = 7
res = num_0 >= 15 or num_1 >= 14
print(res)
# False

Boolean values

A boolean value is either True or False. Variables with boolean values are often used within a program to keep track of certain conditions.

Basic Boolean values

subscription_active = True
is_cancelled = False

Using if statements in loops

An if statement within a loop is a great way to evaluate a list of numbers in a range and take actions on them depending on some condition. This first example is the classic fizzbuzz problem. We want to loop over the numbers 1 to 15, and on each iteration print fizz for every number that’s divisible by 3, print buzz for every number divisible by 5, and print fizzbuzz for every number divisible by 3 and by 5. If the number is not divisible by either 3 or 5, print a message that there was no matching condition for the given iteration.

for i in range(1, 16):
    if i % 3 == 0 and i % 5 == 0:
        print(f'iteration {i} fizzbuzz!')
    elif i % 3 == 0:
        print(f'iteration {i} fizz!')
    elif i % 5 == 0:
        print(f'iteration {i} buzz!')
    else:
        print(f'--none on iteration {i}--')
--none on iteration 1--
--none on iteration 2--
iteration 3 fizz!
--none on iteration 4--
iteration 5 buzz!
iteration 6 fizz!
--none on iteration 7--
--none on iteration 8--
iteration 9 fizz!
iteration 10 buzz!
--none on iteration 11--
iteration 12 fizz!
--none on iteration 13--
--none on iteration 14--
iteration 15 fizzbuzz!

The example above is using the if statement inside of a for loop. We can also use the if statement inside of a while loop.

i = 1
while i < 16:
    if i % 3 == 0 and i % 5 == 0:
        print(f'iteration {i} fizzbuzz!')
    elif i % 3 == 0:
        print(f'iteration {i} fizz!')
    elif i % 5 == 0:
        print(f'iteration {i} buzz!')
    else:
        print(f'--none on iteration {i}--')
    i = i + 1

Guessing A Secret Word

prompt = "Guess the secret word "
secret = ""
while secret != 'swordfish':
    secret = input(prompt)
    if secret != 'swordfish':
        print(f'{secret} is not the secret word')
    else:
        print('swordfish is the secret word!')

python if statement inside while loop

Using A Flag

We can rewrite the word guessing game using a flag like so.

prompt = "Guess the secret word "
active = True
while active:
    secret = input(prompt)
    if secret != 'swordfish':
        print(f'{secret} is not the secret word')
    else:
        print('swordfish is the secret word!')
        active = False

python if flag in while loop


break and continue with loops

You can use the break keyword and the continue keyword with any of Python’s loops. For example, you can use break to quit a for loop that’s iterating over a list or a dictionary. You can use the continue keyword to skip over various items when looping over a list or dictionary as well.

Exit a loop with break

prompt = "What are your favorite colors? "
prompt += "Enter 'q' to quit. "
while True:
    color = input(prompt)
    if color == 'q':
        print("Thanks for sharing your colors!")
        break
    else:
        print(f"{color} is a great color!")

python break out of loop

Using continue in a loop

already_watched = ['Top Gun', 'Star Wars', 'Lord Of The Rings']
prompt = "Choose a movie to watch. "
prompt += "Enter 'q' to quit. "
movies = []
while True:
    movie = input(prompt)
    if movie == 'q':
        break
    elif movie in already_watched:
        print(f"I already saw {movie}")
        continue
    else:
        movies.append(movie)
    print("Movies to watch:")
    for movie in movies:
        print(movie)

python continue in loop

Prevent infinite loops

Every while loop needs a way to stop running, so it won’t run forever. If there’s no way for the condition to become false, the loop will run infinitely. This is bad since your program may crash or your computer may run out of memory.


Removing all occurrences of an item from a list

In Python, you can use the remove() method to delete an item from a list. When used in combination with a while loop, it makes it easy to remove all instances of a given value from the list.

Removing all duplicates from a list of programs

programs = ['Photoshop', 'Illustrator', 'InDesign', 'Animate', 'Illustrator', 'Acrobat', 'Illustrator']
print(programs)
while 'Illustrator' in programs:
    programs.remove('Illustrator')
print(programs)
['Photoshop', 'Illustrator', 'InDesign', 'Animate', 'Illustrator', 'Acrobat', 'Illustrator']
['Photoshop', 'InDesign', 'Animate', 'Acrobat']

Learn more about if in Python


Python If Statement Summary

The if statement in Python is a form of flow control. It allows a program to decide if it needs to skip some instructions, repeat them several times, or choose a single instruction from a list of many. It is the flow control statements that tell Python what instructions to run and under what conditions to run them. In this tutorial, we saw the if statement, if-else statement, if-elif-else chain, and many examples of conditional tests.

Click to share! ⬇️