Sign In
Sign In

Conditional Statements in Python

Conditional Statements in Python
Hostman Team
Technical writer
Python
21.10.2024
Reading time: 12 min

In this article, we will discuss perhaps the most essential part of any program, as conditional constructs shape its structure and determine which parts of the code are executed. These constructs are often referred to as the "heart" of a program in any programming language, and even artificial intelligence is largely built on conditional branching. Therefore, let's take a closer look at them in the following order:

  • The if statement

  • The if-else construct

  • The if-elif-else construct

  • Examples of programs

What Does the Conditional Statement Do in Python?

The simplest way to understand this is through an example. Enter the following in the Python interpreter and press Enter to see the output:

>>> if 5 > 4:
print('True, 5 is greater than 4.')

Output:

True, 5 is greater than 4.

Here we have a basic example of how the program works with a condition. 

Thus, if is used to execute a block of code based on a condition: if the condition is true, the block of code will be executed; if it is false, it will not. Let’s provide an example of False; enter and press Enter:

if 5 < 4:
print('True, 4 is greater than 5')

The interpreter remains silent—which is correct because the condition is false, and thus the statement "True, 4 is greater than 5" (which is itself also incorrect) will never be output.

However, in most cases, more than one condition will be required, and we will need to use more complex constructs: if-else and if-elif-else.

The if-else Conditional Statement

The if-else construct is used when you need to give the program a choice: in the first case, do one thing, and in the second case, do something else. Here’s an example:

money = int(input('How much would you like to spend on shopping? Enter a number: '))
if money >= 10:
    print('Welcome! We have sent the catalog to your email.')
else:
    print('Unfortunately, we do not have any products cheaper than 10 dollars. Please visit us again.')
input('Press Enter to exit.')

The first line is needed for input, handled by the input statement. In brief, the input function accepts user input and, if necessary, assigns the entered value to a variable (in this case, money).

Next comes the condition: if the entered amount equals or exceeds $10, the program gives a positive response. If the entered amount is $9 or less, a different response is given.

In the last line, we also added the input operator, which, in this case, does not pass any value to a variable but serves to move to the next line of code. Since we have no additional lines, pressing Enter will exit the program; this is another feature of input.

The if-elif-else Conditional Statement

Let’s complicate the previous example and make the program choose from three options. We can do this by adding an additional condition that will be set by the elif operator:

money = int(input('How much would you like to spend on shopping? Enter a number: '))
if money >= 10000:
    print('Welcome, wholesale buyer! We have special discounts for you.')
elif money >= 10:
    print('Welcome! We have sent the catalog to your email.')
else:
    print('Unfortunately, we do not have any products cheaper than 10 dollars. Please visit us again.')
input('Press Enter to exit.')

Now, if the user enters an amount equal to or greater than the specified value (10000), the program will output the text from the first if block. If the amount is less than this value but equal to or greater than 10, the condition of the elif operator will be executed, and the user will see the second message.

It’s worth noting that there can be as many elif statements as needed, but the main rule is that the first condition must always specify the if operator. Here’s an example of code with several elif statements. Let’s imagine we want to generate a starting star system for our civilization in a space strategy game:

import random
star = random.randint(1, 5)
planets = random.randint(1, 10)

if star == 1:
    print('Your civilization lives in a blue giant system with', planets, 'planets orbiting.')
elif star == 2:
    print('Your civilization lives in a white dwarf system with', planets, 'planets orbiting.')
elif star == 3:
    print('Your civilization lives in a sun-like yellow dwarf system with', planets, 'planets orbiting.')
elif star == 4:
    print('Your civilization lives in an orange giant system with', planets, 'planets orbiting.')
else:
    print('Your civilization lives in a red supergiant system with', planets, 'planets orbiting.')

input('Press Enter to exit')

Here’s the system that random has gifted us:

Your civilization lives in a sun-like yellow dwarf system with 6 planets orbiting.
Press Enter to exit.

It’s almost solar, just with fewer planets. Note that we created two variables (star and planets), and we entrusted the generation of values to the random module, which needs to be called first:

import random

Next, using the random.randint instruction, we set the range of generated values, from which the random number generator (RNG) selects one: for stars from 5 and for planets from 10:

star = random.randint(1, 5)
planets = random.randint(1, 10)

Since we have five types of stars, there should be just as many blocks of code with conditions, which is why we used several elif operators. The number of planets will be arbitrary for any piece of code because the planets variable is included in everything.

One more thing: you may have already noticed that some operations in the code are indicated with a single = sign, while others use a double equality ==. In Python, a single equal sign = is used only for assigning values to variables, while double equality == is used for comparison. Therefore, in the example above, the code:

star = random.randint(1, 5)

means that the variable star takes on a random value generated by the random module, while the expression:

if star == 1:

means that the variable star, which has already been assigned a value, is being compared to the value 1 (and if this condition is true, the code in this block begins to execute).

Game Examples

The best way to learn is by playing, so let’s demonstrate how the if-else conditional operator works in Python through simple games while also getting acquainted with other useful functions.

Coin Tossing

Let’s write a program using the if-elif-else conditional statement and examine how this program is structured step by step. Type the following into your editor, making sure to maintain the indentation:

import random
coin = random.randint(1, 2)
attempts = 0
heads = 0
tails = 0

while attempts < 100:
    if coin == 1:
        heads += 1
        attempts += 1
        coin = random.randint(1, 2)
    elif coin == 2:
        tails += 1
        attempts += 1
        coin = random.randint(1, 2)
    else:
        print('The coin landed on its edge. Does that ever happen? Alright, let’s toss it again.')
        attempts += 1
        coin = random.randint(1, 2)

print('Heads appeared', heads, 'time(s), and tails', tails, 'time(s).')
input('Press Enter to exit')

We will simulate the coin tosses using the RNG we are already familiar with, provided by the random module. This is called in the first line of the code:

import random

Next, we define several variables:

  • coin — for the coin tosses,

  • attempts — to count the number of tosses,

  • heads — to tally the number of heads,

  • tails — to tally the number of tails.

When tossing the coin, we will use the RNG immediately, so we write:

coin = random.randint(1, 2)

This means that a value will be generated randomly in the range from 1 to 2, which means it can either be a 1 or a 2. Now we just need to assign these values to heads and tails accordingly, specify the maximum number of tosses, and ensure that the count of each increases by one with each toss. For this, we use the Python if-elif-else conditional construct inside a while loop:

while attempts < 100:

This part of the code means: as long as the number of tosses is less than 100:

if coin == 1:
    heads += 1
    attempts += 1
    coin = random.randint(1, 2)

If the RNG returns 1:

  • increase the number of heads by one,

  • increase the number of tosses by one,

  • toss the coin again.

elif coin == 2:
    tails += 1
    attempts += 1
    coin = random.randint(1, 2)

The same applies for tails.

else:
    print('The coin landed on its edge. Does that ever happen? Alright, let’s toss it again.')
    attempts += 1
    coin = random.randint(1, 2)

This code is added to handle the impossible case (a coin will never land on its edge since our RNG can only output 1 or 2). However, adding a final else block is a good habit — "impossible" conditions can sometimes still occur because programmers can’t always account for every scenario. Therefore, an else block can make the program more stable in cases of unanticipated conditions.

As soon as the coin has been tossed for the hundredth time, the last block of code will execute:

print('Heads appeared', heads, 'time(s), and tails', tails, 'time(s).')
input('Press Enter to exit')

The program will exit the while loop and display how many times heads and tails appeared; we analyze the statistics and exit. Essentially, the user will only see the result displayed like this:

Heads appeared 53 time(s), and tails 47 time(s).
Press Enter to exit.

Of course, observing the RNG is interesting, but calling either the star and planet generator or the coin toss a game is a stretch, so let’s write a more interesting program.

Playing Dice

In this game, we will take turns rolling dice against the computer, and in the end, we will declare a winner. The following code accomplishes this:

import random

score1 = 0
score2 = 0
games = 0
die1 = 0
die2 = 0
total1 = 0
die3 = 0
die4 = 0
total2 = 0

input('Roll the dice, press Enter!\n')

while score1 < 6 and score2 < 6 and games <= 11:
    die1 = random.randint(1, 6)
    die2 = random.randint(1, 6)
    total1 = die1 + die2
    print(die1, die2)
    print(total1, '\n')
    input('Now it’s my turn, press Enter!\n')

    die3 = random.randint(1, 6)
    die4 = random.randint(1, 6)
    total2 = die3 + die4
    print(die3, die4)
    print(total2, '\n')

    if total1 > total2:
        score1 += 1
        games += 1
    elif total1 < total2:
        score2 += 1
        games += 1
    else:
        games += 1
        print('It’s a tie\n')
    print('Score', score1, ':', score2, '\n')
    input('Press Enter!\n')

if score1 > score2:
    input('You won! Press Enter to exit.')
elif score1 < score2:
    input('I won! Press Enter to exit.')
else:
    input('Friendship wins! Press Enter to exit.')

This code may seem a bit long and complicated at first glance, but, firstly, we've written a real game (even if it doesn’t have graphics yet), and secondly, there’s nothing particularly difficult here — let's explain everything now.

First, we call the familiar random module, then we define the following variables, which will, of course, be initialized to 0 before the game starts:

  • score1 and score2 for counting victories for the player and the computer,

  • games for counting the number of rounds (which we will later limit to prevent a long game in case of frequent ties),

  • die1, die2, die3, die4 for rolling the individual dice,

  • total1 and total2 for calculating the total score in each roll for both players: for the human player, it will be the sum total1 of the dice die1 and die2, and for the computer, it will be total2 and die3, die4 respectively.

Next, we prompt the start of the game (the player will see this first), and then the program enters a loop:

while score1 < 6 and score2 < 6 and games < 11:

As we can see, there are multiple conditions connected by and operators. This means the program will exit the loop if any one of them is no longer true (i.e., either score1 or score2 reaches 6, or games equals 11). We play almost like a tennis set: as soon as one of the players wins six rounds, the game ends in their victory. Meanwhile, the number of rounds cannot exceed 11. Thus, if no player achieves 6 wins due to a series of ties, the game will still end after the 11th round.

Now the player rolls the dice, and the program calculates their total (total1 = die1 + die2) and prints the result. After pressing Enter, the computer does the same (its total will be total2 = die3 + die4). Of course, the entire game runs solely on the RNG, but that’s how most simple games are structured: even for the player, everything is determined by random chance.

Next, we move to the most important part of the program: the two if-elif-else blocks. The first one is part of the while loop:

if total1 > total2:
    score1 += 1
    games += 1
elif total1 < total2:
    score2 += 1
    games += 1
else:
    games += 1
    print('It’s a tie\n')
print('Score', score1, ':', score2, '\n')
input('Press Enter!\n')

This is straightforward: if our total is higher, we score a point; if the computer wins the round, it gets a point; and in the event of a tie, no one scores, but the round is counted as played in any case. The current score is then displayed, and the players are prompted to continue playing. As soon as the while loop condition is met, meaning one of the players has achieved 6 victories or the number of played rounds has reached 11, the program exits the loop and moves to the final block:

if score1 > score2:
    input('You won! Press Enter to exit.')
elif score1 < score2:
    input('I won! Press Enter to exit.')
else:
    input('Friendship wins! Press Enter to exit.')

The first if condition is satisfied when the player has won more rounds than the computer. The elif condition applies if the computer was more fortunate. But what if 11 rounds were played, and both players won an equal number? This is why we added the else block, which will display a conciliatory message.

Lastly, it’s important to note that Python checks conditions sequentially and executes the first true one: it will first check the if condition, then the elif conditions (if there are multiple, they are checked from top to bottom), and finally the else. Thus, if several conditions happen to be true in a complex program, only the first block will execute: keep this in mind when writing code.

Python
21.10.2024
Reading time: 12 min

Do you have questions,
comments, or concerns?

Our professionals are available to assist you at any moment,
whether you need help or are just unsure of where to start
Email us