popolo - code simple..

popolo - code simple..

Python Basics - Conditional Statements

Python Basics - Conditional Statements

Theodoros Kafantaris's photo
Theodoros Kafantaris
·Apr 27, 2022·

5 min read

Table of contents

Programming often involves examining a set of conditions and deciding which action to take based on those conditions. Python’s if statement allows you to examine the current state of a program and respond appropriately to that state.

Introduction to the if Statement

The most basic type of if statement looks like this:

if <expr>:
  • is an expression evaluated in a Boolean context.
  • is a valid Python statement, which must be indented.

Simple example

fruits = ['apple', 'banana', 'orange', 'kiwi']

   for fruit in fruits:
       if fruit == 'orange':

The loop in this example first checks if the current value of fruit is orange. If it is, the value is printed in uppercase. If the value of fruit is anything other than orange, it’s printed in title case:


Conditional Tests

Every if statement is an expression that can be evaluated as True or False and is called a conditional test. Python uses the values True and False to decide whether the code in an if statement should be executed. If a conditional test evaluates to True, Python executes the code following the if statement. If the test evaluates to False, Python ignores the code following the if statement.

Checking for Equality

Most conditional tests compare the current value of a variable to a specific value of interest. The simplest conditional test checks whether the value of a variable is equal to the value of interest:

#Sets the value of fruit to 'orange'
fruit = 'orange'
#Checks whether the value of fruit is 'orange'
fruit == 'orange'

Ignoring Case When Checking for Equality

Testing for equality is case sensitive in Python. For example, two values with different capitalization are not considered equal:

fruit = 'orange'
fruit == 'Orange'

Checking for Inequality

When we need to determine whether two values are not equal, we can combine an exclamation point and an equal sign (!=). The exclamation point represents not, as it does in many programming languages.

available_fruit = 'apple'

if available_fruit != 'orange':
     print("Sorry but we have only orange")

# Sorry but we have only orange

Numerical Comparisons

Testing numerical values is pretty straightforward. For example, the following code checks whether a person is 18 years old:

age = 18
age == 18

You can also test to see if two numbers are not equal. For example, the following snippet prints a message if the given answer is not correct:

 answer = 18

if answer != 40:
     print("That is not the correct answer. Please try again!")

# That is not the correct answer. Please try again!

Checking Multiple Conditions

We may want to check multiple conditions at the same time. For example, sometimes we might need two conditions to be True to take an action. Other times we might be satisfied with just one condition being True. The keywords and and or can help you in these situations.

Using and to Check Multiple Conditions

result1 = 22
result2 = 18
result1 >= 21 and result2 >= 21
result2 = 22
result1 >= 21 and result2 >= 21

Using or to Check Multiple Conditions

result_1 = 22
result_2 = 18
result_1 >= 21 or result_2 >= 21
result_1 = 18
result_1 >= 21 or result_2 >= 21

Checking Whether a Value Is in a List

Sometimes it’s important to check whether a list contains a certain value before taking an action. For example, you might want to check whether a new username already exists in a list of current usernames before completing someone’s registration on a website.

requested_fruits = ['orange', 'apple', 'banana']
'orange' in requested_fruits
'peach' in requested_fruits

Checking Whether a Value Is Not in a List

Other times, it’s important to know if a value does not appear in a list. You can use the keyword not in this situation. For example, consider a list of users who are banned from commenting in a forum.

banned_users = ['joe', 'david', 'mary']
   user = 'jeffrey'

if user not in banned_users:
   print(f"{user.title()}, you can post a response if you wish.")

# Jeffrey, you can post a response if you wish.

if-else Statements

Often, we’ll want to take one action when a conditional test passes and a different action in all other cases. Python’s if-else syntax makes this possible. An if-else block is similar to a simple if statement, but the else statement allows us to define an action or set of actions that are executed when the conditional test fails.

if <expr>:


>>> x = 20

if x < 50:
   print('(first suite)')
   print(f"{x} is small")
   print('(second suite)')
   print(f"{x} is large")

#(first suite)
#20 is small

The if-elif-else Chain

Often, we’ll need to test more than two possible situations, and to evaluate these we can use Python’s if-elif-else syntax. Python executes only one block in an if-elif-else chain. It runs each conditional test in order until one passes. When a test passes, the code following that test is executed and Python skips the rest of the tests.


name = 'Susan'
if name == 'Joe':
     print('Hello Joe')
elif name == 'Susan':
     print('Hello Susan')
elif name == 'Mike':
    print('Hello Mike')
elif name == 'Stefan':
    print('Hello Stefan')
    print("I don't know who you are!")

# Hello Susan

This is it for now. I believe that you have a good understanding of conditional statements in Python!

Share this