Practical use of conditionals in Python with examples

Last updated : Jul 30, 2023 12:00 AM

Conditionals provide the ability to execute specific code blocks based on whether a given condition is true or false. In this article, I will explain the various types of conditionals in Python and how to use them effectively to write clean, efficient, and flexible code.

In Python conditionals, indentation defines the blocks of code that belong to the if, elif, else, or any nested conditionals. Each indentation level typically consists of four spaces or a single tab. The Python style guide, PEP 8, recommends using four spaces instead of a tab. When you have nested conditionals, the indentation increases with each new level.

1. The if statement

The if statement is the simplest form of conditional in Python. It tests a condition and executes a code block if the condition is true.
The syntax for an if statement is as follows:

if conditionDescription
if condition: 
   # code to execute if the condition is true

For example, to check if a number is positive:

Simple if conditionDescription
number = 5 
if number > 0: 
   print("The number is positive")

2. The if-else statement

The if-else statement allows you to execute one block of code if the condition is true and another block if the condition is false. The syntax is as follows:

if else statementDescription
if condition: 
   # code to execute if the condition is true 
else: 
   # code to execute if the condition is false

For example, to check if a number is even or odd:

Simple if else statementDescription
number = 6 
if number % 2 == 0: 
   print("The number is even") 
else: 
   print("The number is odd")

3. The elif statement

The elif (short for else if) statement allows you to test multiple conditions in a single conditional structure. It is used with if and else statements to create a multi-branch conditional.
The syntax is as follows:

elif syntaxDescription
if condition1: 
   # code to execute if condition1 is true 
elif condition2: 
   # code to execute if condition2 is true 
else: 
   # code to execute if none of the conditions are true

For example, to categorize a numeric grade:

Simple elif usageDescription
grade = 85 
if grade >= 90: 
   print("A") 
elif grade >= 80: 
   print("B") 
elif grade >= 70: 
   print("C") 
else: 
   print("F")

4. Nested conditionals

You can also create nested conditionals by placing one if statement inside another. That can be useful when testing multiple conditions in a specific order. However, nested conditionals can quickly become difficult to read and maintain.
For example, to determine the quadrant of a point in a Cartesian coordinate system:

Nested conditionsDescription
x, y = 5, -2 
if x > 0: 
   if y > 0: 
      print("Quadrant I") 
   else: 
      print("Quadrant IV") 
else: 
   if y > 0: 
      print("Quadrant II") 
   else: 
      print("Quadrant III")

5. Conditional expressions

A conditional expression, also known as a ternary operator, is a concise way of writing a simple if-else statement. It allows you to return one value if the condition is true and another if it is false.
The syntax is as follows:

Conditional expressionsDescription
value_if_true if condition else value_if_false

For example, to assign the absolute value of a number:

Conditional expressions exampleDescription
number = -3 
absolute_value = number if number >= 0 else -number

Here are some sample problems solved with Python conditionals.

Find the largest number without using Python's built-in functions.

Find the largest numberDescription
a = 15 
b = 8 
c = 12
if a > b:
   if a > c:
      largest = a
   else:
      largest = c
else:
   if b > c:
      largest = b
   else:
      largest = c
print(f"The largest number is : {largest}")

FizzBuzz with Python conditionals

FizzBuzzDescription
numbers = [1, 3, 5, 10, 12, 15, 19, 22, 20, 24]
for number in numbers:
   result = ""
   if number % 3 == 0:
      result = "fizz"
   if number % 5 == 0:
      result += "buzz"
   if result == "":
      result = number
   print(result)

Leap year detection

Determine if a given year is a leap year or not. A leap year is divisible by 4, but if it is divisible by 100, it must also be divisible by 400.

Leap year detectionDescription
year = 2000
if year % 4 == 0:
   if year % 100 == 0:
      if year % 400 == 0:
         print(f"The year {year} is a leap year")
      else:
         print(f"The year {year} is not a leap year")
   else:
      print(f"The year {year} is a leap year")
else:
   print(f"The year {year} is not a leap year")

Rock, Paper, Scissors game

Determine the winner of a game of Rock, Paper, Scissors, given the choices of two players.

Rock, Paper, ScissorsDescription
player1 = "scissors"
player2 = "paper"

if player1 == player2:
   print("Its a tie")
else:
   if player1 == "rock":
      if player2 == "scissors":
         print("Player 1 wins")
      else:
         print("Plater 2 wins")
   elif player1 == "paper":
      if player2 == "rock":
         print("Player 1 wins")
      else:
         print("Player 2 wins")
   elif player1 == "scissors":
      if player2 == "paper":
         print("Player 1 wins")
      else:
         print("Player 2 wins")

Triangle type classification

Classify a triangle as equilateral, isosceles, or scalene, given the lengths of its sides.

Triangle type classificationDescription
side_a = 5 
side_b = 5 
side_c = 5 
if side_a == side_b == side_c: 
   print("Equilateral triangle") 
elif side_a == side_b or side_b == side_c or side_c == side_a: 
   print("Isosceles triangle") 
else: 
   print("Scalene triangle")
Lance

By: Lance

Hi, I'm Lance Raney, a dedicated Fullstack Developer based in Oklahoma with over 15 years of exp

Read more...