Conditional statements (if, elif, else).

In Python, conditional statements allow your program to make decisions based on certain conditions. They control the flow of your code, ensuring that specific blocks run only if a condition is true.

The three main keywords used are:

  • if: The first condition to check.
  • elif (short for “else if”): Subsequent conditions to check if the previous ones were false.
  • else: The catch-all block that runs if none of the above conditions were true.

Here are 10 examples showing how to use if, elif, and else in Python:

1. A Basic if Statement

The simplest form. The code inside the if block runs only if the condition evaluates to True.

Python

is_raining = True

if is_raining:
    print("Don't forget your umbrella!")  # Output: Don't forget your umbrella!

2. The if and else Combo

Use else to define what should happen if the if condition is False.

Python

age = 16

if age >= 18:
    print("You are eligible to vote.")
else:
    print("You are not old enough to vote yet.")  
    # Output: You are not old enough to vote yet.

3. Adding elif for Multiple Conditions

Use elif to check additional specific conditions. Python checks them in order and stops at the first True condition it finds.

Python

score = 85

if score >= 90:
    print("Grade: A")
elif score >= 80:
    print("Grade: B")  # Output: Grade: B
else:
    print("Grade: C or lower")

4. Multiple elif Blocks

You can chain as many elif statements as you need to handle various scenarios.

Python

traffic_light = "yellow"

if traffic_light == "green":
    print("Go")
elif traffic_light == "yellow":
    print("Slow down")  # Output: Slow down
elif traffic_light == "red":
    print("Stop")
else:
    print("Signal broken")

5. Nested if Statements

You can place conditional statements inside other conditional statements to create complex decision trees.

Python

has_ticket = True
is_vip = False

if has_ticket:
    if is_vip:
        print("Enter through the fast-track VIP line.")
    else:
        print("Enter through the regular line.")  # Output: Enter through the regular line.
else:
    print("You cannot enter without a ticket.")

6. Using and in Conditions

You can combine multiple requirements in a single if statement using the and operator. Both must be true.

Python

username = "admin"
password = "123"

if username == "admin" and password == "123":
    print("Access Granted.")  # Output: Access Granted.
else:
    print("Access Denied.")

7. Using or in Conditions

Use the or operator when the block should run if at least one of the conditions is true.

Python

day = "Saturday"

if day == "Saturday" or day == "Sunday":
    print("It's the weekend!")  # Output: It's the weekend!
else:
    print("It's a weekday.")

8. Using the in Operator

Conditionals are great for checking if an item exists within a list or string.

Python

shopping_cart = ["apples", "bread", "milk"]

if "milk" in shopping_cart:
    print("You already have milk in your cart.")  
    # Output: You already have milk in your cart.

9. Checking “Truthiness” (Implicit Booleans)

Python can evaluate variables directly in an if statement without needing == True. Empty strings, 0, and empty lists are evaluated as False; everything else is True.

Python

user_input = ""

if user_input:
    print(f"User searched for: {user_input}")
else:
    print("Search query cannot be empty.")  
    # Output: Search query cannot be empty.

10. The Ternary Operator (Inline if-else)

For simple assignments, you can write an if-else statement on a single line. This is known as a conditional expression or ternary operator.

Python

is_sunny = True

# Assigns "Go swimming" if True, otherwise assigns "Stay inside"
activity = "Go swimming" if is_sunny else "Stay inside"

print(activity)  # Output: Go swimming

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *