🎯 If Statements

If statements are the foundation of decision making in Python. They allow your programs to execute different code based on whether conditions are true or false. Think of if statements as asking questions in your code - "if this condition is true, then do this action."

Every if statement evaluates a condition and executes a block of code only when that condition is true. This simple concept enables your programs to respond intelligently to different situations and data.

# Basic if statement
age = 18

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

print("This line always runs")

📝 Basic If Statement Syntax

The if statement follows a simple pattern: the keyword if, followed by a condition, then a colon, and finally an indented block of code. Python uses indentation to determine which code belongs to the if statement.

The condition must be an expression that evaluates to True or False using comparison operators or truthiness rules. When the condition is true, Python executes all the indented code under the if statement. When false, Python skips that code entirely.

# If statement with different conditions
temperature = 75
is_sunny = True
has_umbrella = False

if temperature > 70:
    print("It's warm outside!")

if is_sunny:
    print("The sun is shining!")

if not has_umbrella:
    print("Don't forget your umbrella if it rains!")

⚖️ If-Else Statements

The if-else statement provides an alternative path when the condition is false. This creates a clear choice between two different actions, ensuring your program always does something meaningful.

The else clause executes only when the if condition is false. This pattern is perfect for binary decisions where you need to handle both possibilities.

# If-else statement
score = 75

if score >= 70:
    print("Congratulations! You passed!")
    result = "Pass"
else:
    print("Sorry, you need to study more.")
    result = "Fail"

print(f"Your result: {result}")

# Another example
weather = "rainy"
if weather == "sunny":
    print("Let's go to the beach!")
else:
    print("Let's stay inside and read.")

🎯 Quick If Statement Practice

Let's practice writing simple if-else statements to make decisions!

Hands-on Exercise

Practice using if and else statements to check conditions and make decisions.

python
# If Statement Practice - Simple decisions!

# Check test score
score = 85
# TODO: Your code here: if score >= 70, print "You passed!", else print "You failed."

Solution and Explanation 💡

Click to see the complete solution
# If Statement Practice - Simple solution

# Check test score
score = 85
if score >= 70:
    print("You passed!")
else:
    print("You failed.")

Key Learning Points:

  • 📌 if statement: Checks if a condition is True
  • 📌 else statement: Runs when the if condition is False
  • 📌 Comparison operators: Use >= and == to make conditions
  • 📌 Indentation: Code inside if/else must be indented

🪆 Nested If Statements

You can place if statements inside other if statements to create more complex decision logic. This is called nesting and allows you to check multiple conditions in sequence.

Nested if statements are useful when you need to check additional conditions only after the first condition is true. Each level of nesting adds another layer of decision making.

# Nested if statements
weather = "sunny"
temperature = 80

if weather == "sunny":
    print("It's a sunny day!")
    
    if temperature > 75:
        print("Perfect weather for the beach!")
    else:
        print("Nice weather for a walk!")
else:
    print("Not sunny today.")
    
    if temperature < 60:
        print("It's quite cold too!")

🎲 Working with Different Data Types

If statements work with any expression that can be evaluated as true or false. Numbers, strings, lists, and other data types all have truthiness values that you can use in conditions.

Understanding how different data types behave in conditions helps you write more flexible and powerful conditional logic using type conversion.

# If statements with different data types
name = "Alice"
numbers = [1, 2, 3]
empty_list = []
zero = 0

if name:  # Non-empty strings are truthy
    print(f"Hello, {name}!")

if numbers:  # Non-empty lists are truthy
    print(f"List has {len(numbers)} items")

if empty_list:  # Empty lists are falsy
    print("This won't print")
else:
    print("The list is empty")

if zero:  # Zero is falsy
    print("This won't print")
else:
    print("Zero is falsy")

# Using truthiness for validation
user_input = ""
if user_input:
    print(f"You entered: {user_input}")
else:
    print("No input provided")

🎯 Common If Statement Patterns

There are several common patterns you'll use frequently when working with if statements. Learning these patterns helps you write more effective conditional code.

PatternExampleUse Case
Validationif user_input:Check if input exists
Range Checkif 0 <= score <= 100:Validate ranges
Type Checkif isinstance(x, int):Verify data types
Membershipif "a" in word:Check if item exists
Multiple Conditionsif age >= 18 and has_id:Complex validation
# Common if statement patterns
print("=== COMMON PATTERNS ===")

# Input validation
user_name = input("Enter your name: ") if False else "Alice"  # Simulated input
if user_name:
    print(f"Welcome, {user_name}!")
else:
    print("Name is required")

# Range checking
age = 25
if 18 <= age <= 65:
    print("Working age")

# Membership testing
vowels = "aeiou"
letter = "a"
if letter in vowels:
    print(f"'{letter}' is a vowel")

# Multiple conditions with logical operators
temperature = 72
humidity = 40
if temperature >= 70 and humidity <= 50:
    print("Perfect weather conditions!")

✅ If Statement Best Practices

Following best practices helps you write clear, maintainable, and efficient conditional code.

📚 Key Takeaways

If statements are the foundation of all decision making in Python. Once you master the basic syntax and understand how conditions work, you'll be ready to handle more complex scenarios with multiple conditions and advanced logic.

Test Your Knowledge

Test what you've learned about if statements in Python:

🚀 What's Next?

Now that you understand if statements, you're ready to handle more complex decision-making scenarios. The next lesson covers Multiple Conditions, where you'll learn about elif statements and how to handle many different possibilities.

If statements work hand-in-hand with comparison operators and logical operations. They're also essential for working with loops and function development.

Understanding if statements prepares you for input validation, error handling, and building interactive programs.

Was this helpful?

😔Poor
🙁Fair
😊Good
😄Great
🤩Excellent