How to use conditional statements(if, elif, and else) in python.

Kelvin UgwuKelvin Ugwu
8 min read

Table of Contents:

  1. Introduction

Overview of Python's versatility and simplicity in programming.

  1. Basic Conditional Statements
  • Explanation of if statements and their usage.

  • Introduction to executing code based on conditions (if).

  1. The else Statement
  • Using else to provide an alternative when if condition is False.
  1. The elif, Statement
  • Handling multiple conditions sequentially after an ifstatement.

5. Nested if Statements

  • Explanation and usage of nested conditional statements.
  1. Logical Operators (and, or, not)
  • Combining conditions and negating expressions for complex logic.
  1. Ternary Conditional Operator
  • Writing concise if-else statements in a single line.
  1. Best Practices
  • Guidelines for maintaining clean and readable code:

  • Proper indentation

  • Variable declaration

  • Syntax adherence (using colons after conditions)

  • Type-safe comparisons

  • Emphasis on code readability.

9. Conclusion

  • Summary of the key points discussed

Introduction

Python is a high-level programming language known for its simplicity, readability, and versatility. It is used to build robust web applications, software, machine learning solutions, and more.

Python is a good choice for beginners and experienced developers alike, offering simplicity while still being powerful enough to build complex solutions.

In this tutorial, you will learn all about conditional statements in Python. It is assumed that you have Python installed on your machine and understand Python data types.

Why is Learning Conditional Statements Important?

The key lies in control flow. Control flow is the sequence in which a program executes its instructions, deciding how a program makes decisions and responds to different conditions.

Imagine giving a child instructions on what to do. Control flow represents the order in which the child performs those tasks. The sequence of instructions—what to do first or last—affects their decision-making process.

Now that you understand why control flow is important, let’s dive deeper into conditional statements and how they work in Python.

What Are Conditional Statements?

Conditional statements, also known as decision-making statements, are constructs that allow an instruction to be executed only if a certain condition is met.

Let’s use the analogy of giving a child instructions:

"If you get to the road, take a taxi. But if there’s no taxi, take the bus."

In this case, the child will only take the bus if there’s no taxi available.

This is how conditional statements influence control flow: they determine the actions that follow based on whether certain conditions are true or false.

One of Python’s powerful features is its ability to handle conditional statements effectively. Things are about to get even more interesting—let’s explore them further.

The Basics of the if Statement

The simplest form of a conditional statement in Python is the if statement. The syntax looks like this:

if condition:
    # execute this block

The condition is a Boolean expression, meaning it will evaluate to either True or False.

  • If the condition is True, the block of code under the if statement is executed.

  • If the condition is False, the code block is skipped.

For example:

age = 18
if age >= 18:
    print("You are eligible to vote.")

In this case, since age, is 18, the condition age >= 18 is True, so the message "You are eligible to vote” will be printed.

The else Statement

What if there’s another action we want our program to take if the if condition evaluates to False? This is where the else statement comes in.

The syntax looks like this:

if condition:
    # execute this block
else:
    # if the if block is skipped, execute this

In this case, if the if condition evaluates to False and the block is skipped, the else block will be executed.

Example:

age = 17
if age >= 18:
    print('You are allowed to open an account.')
else:
    print('The site requires that you be over 18. Check the minors section.')

Since age is less than 18, the if block will be skipped, and the else block will be executed.

The elif Statement

One of the powerful features of conditional statements is that they can evaluate more than one condition. This is possible using the elif statement, which stands for "else if.”

Here’s the syntax:

if condition_1:
    # Execute this block
elif condition_2:
    # Execute this block
elif condition_3:
    # Execute this block
else:
    # If all conditions are skipped, execute this

You might be wondering, Is it an error to have multiple elif statements? Absolutely not. With elif, you can add as many conditions as needed between the if and else.

Python will check each condition in order, and if none are True, the else block will be executed.

Example:

age = 18
if age >= 18:
    print('Welcome to the hood.')
elif age < 15:
    print('Why not learn Python instead?')
else:
    print('Where do you belong?')

In this example, since age is 18, the first condition age >= 18 is True, so "Welcome to the hood." will be printed. The other conditions will not be evaluated.

Nested if Statements

An if-else statement can exist inside another `if-else` statement. This is called a nested if statement.

Here’s an analogy to break it down:

"Go to the second street. If the mall is open, check in and get me a Coke. If there's no Coke, get a Pepsi instead. And if the mall is closed, go to the market."

The person can only get a Coke or Pepsi if the mall is open.

Example:

mall_is_open = True
coke_is_available = False
if mall_is_open:
    if coke_is_available:
        print('I got a Coke.')
    else:
        print('Got a Pepsi.')
else:
    print('Go to the market.')

In this example, since the mall is open but Coke isn't available, the program prints "Got a Pepsi."

Logical Operators in Python

In Python, logical operators are used to combine conditions. The main logical operators are:

  • and
  • or
  • not
  1. The and Operator

When using and, both conditions must evaluate to True for the block to be executed. If the first condition is False, the second condition isn’t checked, and the block is skipped. This behavior is called short-circuiting.

Example:

x = 12
y = 14
if x > 5 and y > 10:
print('Both conditions are True.')

Since both x > 5 and y > 10 are True, the block will be executed.

  1. The or Operator

With or, the block is executed if at least one condition is True. If the first condition evaluates to True, the second condition is not checked (another example of short-circuiting).

Example:

x = 12
y = 14
if x < 5 or y > 10:
print('At least one condition is True.')

Here, x < 5 is False, but y > 10 is True, so the block will be executed.

  1. The not Operator

The not operator is used to negate a condition. If a condition evaluates to False, not changes it to True, and vice versa.

Example:

x = 4
if not (x > 5):
print('Hello world.')

Since x > 5 is False, the not operator negates it, turning it into True. So, the block will be executed, and "Hello world." will be printed.

Now that we’ve covered logical operators, let’s explore ternary conditional operators.

Ternary Conditional Statements

Ternary conditional statements provide a concise way of writing an if-else statement in a single line. This is useful when you need a simple condition that can be expressed briefly.

The basic syntax is:

value_if_true if condition else value_if_false

This means:

  • If the condition is True, it evaluates to value_if_true.
  • If the condition is False, it evaluates to value_if_false.

Here’s an example:

worker_status = 'pensioner' if worker_is_retired else 'salary earner'

If worker_is_retired is True, worker_status will be 'pensioner'. Otherwise, it will be 'salary earner'.

Another Example:

age = 20
category = 'Adult' if age >= 18 else 'Minor'
print(category) # Outputs: Adult

Here, since age is greater than or equal to 18, category is assigned the value 'Adult'.

Ternary operators are great for simplifying short conditional logic, but they should be used carefully, as they can reduce readability when overused in complex conditions.

Best Practices for Conditional Statements

Now that you’ve learned about conditional statements, it’s important to follow best practices to ensure your code is readable and bug-free.

  1. Indentation:
  • Ensure correct indentation for nested statements. IDEs with automatic indentation features can make this process smoother.
  1. Undeclared Variables:
  • Using an undeclared variable in a conditional statement will result in a NameError.
  • Always declare variables before using them to prevent errors.
  1. Omitting Colon:
  • Omitting the colon after a condition will lead to a syntax error.
  • Form the habit of adding a colon (:) immediately after writing the condition.
  1. Comparing Different Data Types:
  • Comparing variables of different data types will raise a TypeError.
  • Be mindful of the data types you are comparing to avoid unexpected errors.
  1. Avoid Complex Conditions:
  • Write code that is as readable as possible.
  • While complex conditions may not always result in errors, prioritizing readability enhances maintainability and debugging.

Following these practices will not only help you avoid common pitfalls but also contribute to writing cleaner and more maintainable code.

Summary of Conditional Statements in Python

Python's conditional statements (if, else, elif, and ternary operators) are powerful tools for controlling program flow based on conditions.

They allow developers to execute specific blocks of code based on whether certain conditions are met.

Understanding and correctly using these statements is crucial for writing clean, efficient code.

Key considerations

Include proper indentation, variable declaration, syntax adherence (using colons after conditions), avoiding type mismatches in comparisons, and prioritizing code readability.

By following these principles, developers can create robust Python applications that are easier to maintain and understand.

1
Subscribe to my newsletter

Read articles from Kelvin Ugwu directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Kelvin Ugwu
Kelvin Ugwu