Keyboard Shortcuts N Next post
P Previous post
S Save / unsave
R Read aloud
T Toggle theme
/ Focus search
Esc Close panels
🔥
Ready to read...
control flow Module 2 - Control Flow Python Python Basics Python Programming: From Zero to Real-World Applications

if, elif, else - Making Decisions in Python

Reviewed & accurate
AI Summary

What You Will Learn

Beginner

  • How to use if, elif, and else
  • Python indentation rules
  • Nested conditionals
Terminalpython
age = 18

if age >= 18:
    print("You are an adult.")
elif age >= 13:
    print("You are a teenager.")
else:
    print("You are a child.")
Indentation matters!
Python uses indentation (4 spaces) to define code blocks. No braces like other languages. Wrong indentation = SyntaxError.

Comparison Operators

OperatorMeaningExample
==Equalx == 5
!=Not equalx != 5
>Greaterx > 5
<Lessx < 5
>=Greater or equalx >= 5
<=Less or equalx <= 5

Logical Operators

Terminalpython
# and: both must be True
if age >= 18 and age < 65:
    print("Working age adult.")

# or: at least one must be True
if day == "Saturday" or day == "Sunday":
    print("It is the weekend!")

# not: inverts the condition
if not is_raining:
    print("No umbrella needed.")

Nested Conditionals

Terminalpython
score = 85

if score >= 60:
    print("You passed!")
    if score >= 90:
        print("Grade: A")
    elif score >= 80:
        print("Grade: B")
    else:
        print("Grade: C")
else:
    print("You failed.")

Practical Exercise

Ask the user for a score (0-100)
If score >= 90: print A
elif score >= 80: print B
elif score >= 70: print C
else: print F

Key Takeaways

  • if/elif/else for decision making.
  • Python uses 4-space indentation for code blocks.
  • == compares values. = assigns values.
  • and, or, not combine conditions.
  • Nested if statements are allowed but avoid deep nesting.
Previously: Module 1 covered fundamentals.
Today: You learned: Make decisions in your code with if/elif/else.
Next: Lesson 10 goes deeper on operators.
Test Your Knowledge
How did you find this?

Comments

Join the discussion! Sign in with your Google or Blogger account, or comment as Anonymous - no account needed. For quick questions, also reach me on Telegram @cytestch.

Comments