Conditional Statements: if, else, elif

Summary: Use if-else conditions to control script logic.


Conditional statements are fundamental building blocks in programming. They enable your script to make decisions and execute code selectively, depending on whether specific conditions are met. This post explores how to use Python's if, elif, and else statements to control the flow of your programs with clarity and precision.

What Are Conditional Statements?

Conditional statements let your scripts perform different actions based on logical conditions. They check for Boolean values—expressions that are either True or False—and execute code accordingly.

  • if statement: Runs a block of code if a condition is True.
  • elif statement: Checks another condition if the previous if (and any elif) were False.
  • else statement: Runs a block of code if none of the preceding conditions are True.

These constructs form the essential "decision points" in your scripts.

The if Statement

The simplest form:

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

Explanation:

  • Python checks if age is greater than or equal to 18.
  • Since age is 18, the condition is True, so print("You are an adult.") runs.

Adding else: Making a Binary Decision

What if the condition is False? The else block provides an alternative:

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

How it works:

  • If age >= 18 is True, the first print runs.
  • Otherwise, the else block executes.

Multiple Conditions Using elif

Often, you need to check more than two potential cases. Here’s where elif comes in:

score = 85
if score >= 90:
    print("Grade: A")
elif score >= 80:
    print("Grade: B")
elif score >= 70:
    print("Grade: C")
else:
    print("Grade: D or lower")

How it flows:

  1. Checks if score is 90 or above. If so, prints "Grade: A".
  2. If not, checks if score is at least 80. If yes, prints "Grade: B".
  3. Continues checking each elif in order.
  4. If none match, the else block runs.

Indentation Matters

Python uses indentation to define code blocks. Each statement inside an if, elif, or else must be indented.

temperature = 32

if temperature > 30:
    print("It's hot!")
    print("Drink plenty of water.")
else:
    print("The weather is pleasant.")

Combining Conditions

Use logical operators (and, or, not) to make more complex decisions:

username = "admin"
password = "1234"

if username == "admin" and password == "1234":
    print("Access granted.")
else:
    print("Access denied.")
  • Both conditions must be True for "Access granted" to print.

Common Mistakes With Conditional Statements

  • Missing Indentation: Each block after : must be indented.
  • Forgetting the elif or else: You don't need them, but ensure your logic doesn't expect them accidentally.
  • Chained Equality: Remember, if x == y == z is valid but not always what you intend.

Real-world Use Case Example

Suppose you're building a temperature converter that also gives weather advice:

celsius = float(input("Enter temperature in Celsius: "))

if celsius > 35:
    print("It's extremely hot!")
elif celsius > 25:
    print("The weather is warm.")
elif celsius > 15:
    print("It's mild.")
else:
    print("It's cold, wear a jacket!")

Result: The script gives users tailored messages based on the temperature they input.

Conclusion

Mastering if, elif, and else is crucial for building scripts that respond dynamically to different inputs and scenarios. These conditional statements are the core of decision-making in code, allowing your programs to adapt and act intelligently.

Tip: Always keep your conditions clear and your blocks properly indented to avoid common pitfalls. With practice, using if-else to control script logic will become second nature.