๐ฏ Learning Objectives
By the end of this lesson, learners will be able to:
-
Use
if
,elif
, andelse
statements in Python -
Create programs that make decisions based on user input or conditions
-
Understand Boolean expressions and nesting conditions
-
Apply logical operators within conditionals
๐ Lesson Content
๐น Why Use If-Else?
Programs often need to make decisions. For example:
-
If the user is 18 or older, allow login
-
If a number is even, do one thing; if odd, do another
In Python, we use if-elif-else
statements to handle these decisions.
๐ธ Basic Syntax of If-Else:
๐ Note: Indentation is required โ typically 4 spaces.
๐ธ Example 1: Simple If-Else
๐ธ Example 2: If-Elif-Else
๐น Using Logical Operators in Conditions
You can combine multiple conditions using and
, or
, and not
.
๐ธ Nested If-Else Statements
One if
block inside another:
โ ๏ธ Common Mistakes to Avoid
Mistake | Why it’s Wrong |
---|---|
Missing : after if or else |
SyntaxError |
Incorrect indentation | IndentationError |
Using assignment = instead of comparison == |
Logical bug |
๐ Assignment / Practice
Write a program that:
-
Asks for the user’s age
-
If age < 13: print “Child”
-
If age between 13 and 19: print “Teenager”
-
If age between 20 and 60: print “Adult”
-
Else: print “Senior Citizen”