If-Else statements allow your program to make decisions and execute different code blocks based on conditions. They are fundamental for creating dynamic and responsive applications.
π Essential for controlling the flow of your program.
πΉ 1. What are Conditional Statements?
They test a condition. If the condition is
True, one block of code runs. If False, another block (or nothing) might run.Example:
temperature = 25
if temperature > 20:
print("It's warm!")
Output:
It's warm!πΉ 2. The
if StatementThe simplest conditional, executing code only when a condition is
True.Syntax:
if condition:
# code to run if condition is True
Example:
age = 18
if age >= 18:
print("You are an adult.")
Output:
You are an adult.πΉ 3. The
else StatementExecutes a block of code when the
if condition is False.Syntax:
if condition:
# code if True
else:
# code if False
Example:
score = 75
if score >= 90:
print("Excellent!")
else:
print("Good effort!")
Output:
Good effort!πΉ 4. The
elif (Else If) StatementAllows you to check multiple conditions sequentially. If the first
if is False, it checks elif, and so on.Syntax:
if condition1:
# code if condition1 is True
elif condition2:
# code if condition2 is True
else:
# code if all conditions are False
Example:
time = 14
if time < 12:
print("Good morning!")
elif time < 18:
print("Good afternoon!")
else:
print("Good evening!")
Output:
Good afternoon!πΉ 5. Short Hand If / Ternary Operator
A concise way to write simple
if-else statements on a single line.Example:
a = 10
b = 5
print("A is greater") if a > b else print("B is greater")
Output:
A is greaterπ― Today's Goal(What you should do)
βοΈ Understand how to use
if, elif, and elseβοΈ Make your programs respond to different inputs
βοΈ Use shorthand for simple conditions
π Conditional statements are the backbone of any interactive and logical Python program. It's crucial you understand them well.