๐ฐ Introduction :

So far, your programs have performed the same steps regardless of what the user enters.
But what if you want your program’s behavior to change based on a specific condition?
That’s where conditional statements come in!
๐ง What is an if statement ?
A conditional statement is used when you want code to execute only if a specific condition is met.
โ General Format :
Python
if Condition:
# Code to execute if the condition is true
๐งช Example :
Python
age = int(input(“How old are you?”))
if age >= 18:
print(“You are an adult and can register.”)
๐ If the age is 18 or older,
the message will be executed.
If it is younger, nothing will be printed.
๐ Using else :
Python
if age >= 18:
print(“You are an adult.”)
else:
print(“You are a minor.”)
๐ else is used to execute alternative code if the condition is not true.
๐ Using elif (else if) :
Python
grade = int(input(“How much did you score on the exam?”))
if grade >= 90:
print(“Excellent!”)
elif grade >= 75:
print(“Very good.”)
elif grade >= 50:
print(“Pass.”)
else:
print(“Failed, try again.”)
๐ข The program here makes multiple decisions based on values.
๐ Comparison Operators :
Symbol Meaning
== Equal
!= Not Equal
> Greater Than
< Less Than
>= Greater or Equal
<= Less or Equal
๐ Real-World Example :
Python
password = input(“Enter password: “)
if password == “12345”:
print(“Login Successful!”)
else:
print(“Incorrect password.”)
๐งช Exercise 1 :
Write a program that asks the user for their age, then:
If under 13 โ “You are a child.”
If between 13 and 17 โ “You are a teenager.”
If 18 or older โ “You are an adult.”
๐งช Exercise 2:
Write a program that asks for the username and compares whether it is “admin” or not:
python
username = input(“Enter username: “)
if username == “admin”:
print(“Hello, Administrator!”)
else:
print(“Hello, ” + username)
โ ๏ธ Beginner’s Tip:
Make sure you spell the condition correctly.
Indentations are very important in Python:
โ Incorrect:
python
if x > 0:
print(“Positive”)
โ Correct:
python
if x > 0:
print(“Positive”)
๐ Conclusion:
You learned how to use if, else, and elif to implement conditions.
You learned how to use comparison operators.
You wrote programs that react to user input and make intelligent decisions.
๐ What will we learn in Lesson 4 ?
In the next lesson, we’ll learn about for and while loops, which help you automatically repeat commands without rewriting your code
โฌ๏ธ Download Delux ุชุญู ูู