beginner

If-Else Statements

Learn conditional logic with if, elif, and else statements in Python.

Conditional statements are the foundation of decision-making in programming. They allow your code to respond differently based on conditions, making your programs intelligent and dynamic. From validating user input to controlling game logic, if-else statements are used constantly in real-world applications. This exercise teaches you to write clear, effective conditional logic.

📚 Concepts & Theory

Basic If Statement:

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

If-Else Statement:

temperature = 25
if temperature > 30:
print("It's hot!")
else:
print("It's comfortable")

If-Elif-Else Chain:

score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "F"

Comparison Operators:

  • == Equal to

  • != Not equal to

  • > Greater than

  • < Less than

  • >= Greater than or equal

  • <= Less than or equal
Logical Operators:
  • and - Both conditions must be True

  • or - At least one condition must be True

  • not - Inverts the boolean value
if age >= 18 and has_license:
print("You can drive")

🎯 Your Challenge

Write a program that checks a variable called `number` (set to 15). If the number is positive (greater than 0), set `result` to "positive". If it's negative, set `result` to "negative". If it's exactly zero, set `result` to "zero".

📝 Starter Code

Python
# Check if number is positive, negative, or zero
number = 15

# Your conditional logic here
if number > 0:
    result = 
elif number < 0:
    result = 
else:
    result = 
  • Start with if for the first condition
  • Use elif for additional conditions
  • else handles all remaining cases
  • Make sure each block is properly indented

Solution

Python
number = 15

if number > 0:
    result = "positive"
elif number < 0:
    result = "negative"
else:
    result = "zero"

Explanation

We use an if-elif-else chain to check three mutually exclusive conditions. First, we check if the number is greater than 0 (positive). If not, we check if it's less than 0 (negative). If neither condition is true, the number must be exactly 0, which is handled by the else clause.

⚠️ Common Mistakes to Avoid

  • Using = instead of == for comparison
  • Forgetting the colon after conditions
  • Incorrect indentation
  • Using elif before if

❓ Frequently Asked Questions

Yes, you can chain as many elif statements as needed. Python will check each condition in order and execute the first one that is True.
No, else is optional. If you don't include it and no conditions are True, nothing happens and the program continues.

🔗 Related Concepts