Python tutorials > Core Python Fundamentals > Control Flow > How to use `if`/`elif`/`else`?

How to use `if`/`elif`/`else`?

Understanding Conditional Statements in Python: if/elif/else

Conditional statements are fundamental building blocks in programming. They allow your program to make decisions based on different conditions. In Python, the if, elif (short for 'else if'), and else statements provide a way to control the flow of execution based on these conditions.

This tutorial will guide you through the syntax, usage, and best practices of using if, elif, and else in Python.

The Basic `if` Statement

The if statement checks if a condition is true. If the condition is true, the code block indented below the if statement is executed. If the condition is false, the code block is skipped.

In the example above, the condition age >= 18 is true (since age is 20), so the message "You are an adult." is printed.

age = 20

if age >= 18:
    print("You are an adult.")

The `if`/`else` Statement

The if/else statement provides an alternative code block to execute when the condition in the if statement is false. If the condition is true, the code block under the if statement is executed. Otherwise, the code block under the else statement is executed.

In the example above, the condition age >= 18 is false (since age is 15), so the message "You are a minor." is printed.

age = 15

if age >= 18:
    print("You are an adult.")
else:
    print("You are a minor.")

The `if`/`elif`/`else` Statement

The if/elif/else statement allows you to check multiple conditions in sequence. The elif (short for 'else if') statement checks another condition only if the previous if or elif conditions were false. The else statement provides a default code block to execute if none of the previous conditions were true.

In the example above, the condition score >= 90 is false, so the next condition score >= 70 is checked. Since this is true (score is 75), the message "Good job!" is printed. Note that even though `score >= 50` is also true, the code block under it is not executed because a previous `elif` condition was already met.

score = 75

if score >= 90:
    print("Excellent!")
elif score >= 70:
    print("Good job!")
elif score >= 50:
    print("You passed.")
else:
    print("You failed.")

Concepts Behind the Snippet

The core concept is conditional execution. The `if`, `elif`, and `else` keywords enable your program to follow different paths of execution depending on the state of your data. This allows programs to respond intelligently to varying inputs and situations.

Boolean Logic: Conditional statements rely on boolean logic. The conditions you evaluate must ultimately resolve to either True or False. Python uses comparison operators (==, !=, >, <, >=, <=) and logical operators (and, or, not) to create these boolean expressions.

Real-Life Use Case Section

User Authentication: Imagine a website where users log in. The if statement checks if the entered username and password match the records in the database. If they match, the user is granted access; otherwise, an error message is displayed using the else statement.

Game Development: In a game, the if/elif/else statements can control character movement based on user input (e.g., pressing the 'W' key moves the character forward). They can also determine the outcome of a game event (e.g., checking if a player's health is zero, in which case the game is over).

Data Validation: When processing user input or data from a file, conditional statements are used to validate the data. For example, you might check if a user has entered a valid email address format or if a number falls within an acceptable range.

Best Practices

  • Keep conditions simple and readable: Complex conditions can be difficult to understand and debug. Break down complex conditions into smaller, more manageable parts.
  • Use meaningful variable names: Choose variable names that clearly indicate the purpose of the variable.
  • Avoid deeply nested `if` statements: Deeply nested if statements can make your code difficult to read and maintain. Consider refactoring your code to use functions or other techniques to reduce nesting.
  • Consider using `elif` for multiple mutually exclusive conditions: If you have a series of mutually exclusive conditions, using elif can improve readability and efficiency.
  • Include an `else` statement for default behavior: Including an else statement can help you handle unexpected cases and prevent errors.

Interview Tip

When asked about if/elif/else statements in an interview, be prepared to explain the syntax, usage, and purpose of each keyword. Also, be ready to discuss best practices and common pitfalls.

A common interview question might be: "Describe a scenario where you would use an if/elif/else statement." Prepare a few examples beforehand.

You should also be prepared to discuss the time complexity of different conditional structures. While the fundamental conditional checks are generally O(1), the overall complexity of a function or program can be affected by the number of conditional branches and the code executed within each branch.

When to use them

Use if statements whenever you need to execute code conditionally based on whether a condition is true or false.

Use if/else statements when you need to execute one block of code if a condition is true and another block of code if the condition is false.

Use if/elif/else statements when you need to check multiple conditions in sequence and execute a different block of code for each condition. This is particularly useful when you have mutually exclusive conditions.

Memory Footprint

The memory footprint of if/elif/else statements themselves is generally negligible. They don't allocate significant amounts of memory directly. The memory usage primarily depends on the variables used in the conditions and the code executed within each branch of the conditional statement.

However, complex conditions involving large data structures can indirectly increase memory usage. Optimizing the data structures and the logic within the conditional blocks can help reduce memory consumption.

Alternatives

While if/elif/else are fundamental, there are situations where alternatives might be more concise or readable:

Ternary Operator: For simple if/else assignments, the ternary operator (value_if_true if condition else value_if_false) can be used.

Dictionaries for dispatch: If you're checking for specific values and performing different actions based on them, a dictionary can act as a 'dispatch table'.

Match statement (Python 3.10+): The match statement provides a more structured way to handle multiple conditions, similar to a switch statement in other languages.

Pros

  • Flexibility: Conditional statements provide a great deal of flexibility in controlling program flow.
  • Readability (when used well): Well-structured conditional statements can make code easier to understand.
  • Ubiquity: They are a fundamental part of virtually every programming language.

Cons

  • Complexity: Overuse or poorly structured conditional statements can lead to complex and difficult-to-maintain code.
  • Potential for errors: Missing an else case or having incorrect conditions can lead to unexpected behavior.
  • Can become verbose: For complex scenarios, the nested structure can make code very long and difficult to read.

FAQ

  • What happens if none of the `if` or `elif` conditions are true?

    If none of the if or elif conditions are true, the code block under the else statement (if present) is executed. If there is no else statement, no code block is executed.
  • Can I nest `if` statements inside other `if` statements?

    Yes, you can nest if statements inside other if statements. However, deep nesting can make your code difficult to read and maintain. It's often better to refactor your code to avoid deep nesting.
  • Are parentheses required around the conditions in `if` statements?

    No, parentheses are not required around the conditions in if statements in Python, but can be added for readability or precedence control when combining several conditions with and and or.