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
| Operator | Meaning | Example |
|---|---|---|
== | Equal | x == 5 |
!= | Not equal | x != 5 |
> | Greater | x > 5 |
< | Less | x < 5 |
>= | Greater or equal | x >= 5 |
<= | Less or equal | x <= 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.
Comments
Comments
Post a Comment