Conditions: if, else, and elif

Welcome back.
In the previous lesson, you learned how to use input().
Your programs learned how to ask questions.
Very polite.
Very interactive.
A little suspicious.
You wrote programs like:
name = input("What is your name? ")
age = int(input("How old are you? "))
print(f"Hello, {name}!")
print(f"Next year you will be {age + 1}.")
Good.
Now your program can ask the user for information.
But it still cannot make decisions.
It always does the same thing.
Real programs need choices.
For example:
If the user is old enough, allow access.
If the password is correct, log in.
If the product is available, show “Buy now”.
If the number is negative, show a warning.
This is where conditions enter the story.
Conditions let your program choose what to do.
Without conditions, a program is like a train with no switches.
It goes forward.
Always forward.
Even when the track ends.
Not ideal.
What You Will Learn
In this lesson, you will learn:
- what conditions are;
- how
ifworks; - how indentation works with conditions;
- how comparison operators work;
- how to use
else; - how to use
elif; - how to compare numbers;
- how to compare strings;
- how booleans work with conditions;
- how to combine conditions with
and; - how to combine conditions with
or; - how to use
not; - common beginner mistakes;
- how to build simple decision-making programs.
By the end of this lesson, your programs will be able to make choices.
Small choices.
But important choices.
Very Python.
Very powerful.
Slightly dangerous.
Perfect.
What Is a Condition?
A condition is a question that Python can answer with:
True
or:
False
Example:
age = 20
print(age >= 18)
Output:
True
Python checks:
Is age greater than or equal to 18?
The answer is:
True
Another example:
age = 15
print(age >= 18)
Output:
False
The condition is not true.
The user is not 18 or older.
Python is not emotional.
It just checks the condition.
No drama.
Just logic.
Mostly.
Your First if Statement
Create a file:
conditions.py
Write:
age = 20
if age >= 18:
print("You are an adult.")
Run it:
python conditions.py
or:
python3 conditions.py
Output:
You are an adult.
This means:
If age is greater than or equal to 18, print the message.
The condition is true.
So Python runs the indented line.
Very simple.
Very important.
The program just made a decision.
Tiny decision.
Big concept.
When the Condition Is False
Now change the code:
age = 15
if age >= 18:
print("You are an adult.")
Run it.
Output:
Nothing happens.
Why?
Because the condition is false.
Python checks:
Is 15 greater than or equal to 18?
Answer:
False
So Python skips the indented line.
This is how if works.
If the condition is true, run the code.
If the condition is false, skip the code.
Very direct.
Very Python.
Very “no ticket, no entry”.
Indentation Matters
In Python, indentation is very important.
This works:
age = 20
if age >= 18:
print("You are an adult.")
The line:
print("You are an adult.")
is indented.
That means it belongs to the if.
Python uses indentation to understand blocks of code.
A block is a group of lines that belong together.
In many languages, programmers use {}.
In Python, we use indentation.
Python saw curly braces and said:
No thanks. I prefer furniture alignment.
Very Python.
Wrong Indentation
This is wrong:
age = 20
if age >= 18:
print("You are an adult.")
Python will show an error:
IndentationError
Why?
Because after if, Python expects an indented block.
Correct:
age = 20
if age >= 18:
print("You are an adult.")
Use consistent indentation.
Most Python code uses 4 spaces.
Do not mix tabs and spaces.
Mixing tabs and spaces is how small programs become haunted houses.
The Colon Is Required
The if line needs a colon:
if age >= 18:
The colon means:
A block of code starts here.
Wrong:
if age >= 18
print("You are an adult.")
Python will complain.
Correct:
if age >= 18:
print("You are an adult.")
Small symbol.
Big responsibility.
The colon is tiny.
But without it, Python stops the party.
Comparison Operators
Comparison operators let Python compare values.
Common operators:
== equal to
!= not equal to
> greater than
< less than
>= greater than or equal to
<= less than or equal to
Examples:
age = 20
print(age == 20)
print(age != 18)
print(age > 18)
print(age < 30)
print(age >= 20)
print(age <= 21)
Output:
True
True
True
True
True
True
These operators are the foundation of conditions.
They ask questions.
Python answers with True or False.
Very useful.
Very strict.
Like a tiny judge with a keyboard.
== Is Not the Same as =
Very important:
=
means assignment.
It stores a value.
Example:
age = 20
This means:
Store 20 in age.
But:
==
means comparison.
Example:
age == 20
This means:
Is age equal to 20?
Do not confuse them.
Wrong idea:
if age = 20:
print("Age is 20.")
Correct:
if age == 20:
print("Age is 20.")
One = gives a value.
Two == ask a question.
Tiny difference.
Huge drama.
Classic programming.
Using else
else runs when the if condition is false.
Example:
age = 15
if age >= 18:
print("You are an adult.")
else:
print("You are not an adult yet.")
Output:
You are not an adult yet.
The condition:
age >= 18
is false.
So Python skips the if block and runs the else block.
This means:
If this is true, do one thing.
Otherwise, do another thing.
Very useful.
Very common.
Very “door A or door B”.
if and else with Input
Create a file:
age_check.py
Write:
age = int(input("How old are you? "))
if age >= 18:
print("You can enter.")
else:
print("You cannot enter yet.")
Run it.
Example 1:
How old are you? 20
Output:
You can enter.
Example 2:
How old are you? 15
Output:
You cannot enter yet.
Now your program reacts differently depending on user input.
This is important.
The same code can produce different results.
Because the data changes.
That is where programming starts to feel alive.
Not too alive.
Still no robot rebellion.
Using elif
Sometimes two choices are not enough.
You may need several possibilities.
Example:
If score is 90 or more, grade A.
If score is 80 or more, grade B.
If score is 70 or more, grade C.
Otherwise, grade D.
For this, use elif.
elif means:
else if
Example:
score = 85
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
else:
print("Grade: D")
Output:
Grade: B
Python checks from top to bottom.
First condition:
score >= 90
False.
Second condition:
score >= 80
True.
So Python prints:
Grade: B
Then it skips the rest.
Very efficient.
Very decisive.
Very “I found the answer, goodbye”.
Order Matters with elif
Order matters.
Look at this:
score = 95
if score >= 70:
print("Grade: C or better")
elif score >= 80:
print("Grade: B or better")
elif score >= 90:
print("Grade: A")
Output:
Grade: C or better
Why?
Because Python checks from top to bottom.
score >= 70 is true.
So Python runs that block and skips the rest.
Even though score >= 90 is also true.
This is why the order must be logical.
Better:
score = 95
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
else:
print("Grade: D")
Output:
Grade: A
Put the most specific or strongest condition first.
Otherwise your program may be technically correct but logically silly.
Python will not stop you.
Python allows nonsense if the syntax is legal.
Very dangerous freedom.
Comparing Strings
You can compare strings too.
Example:
password = input("Password: ")
if password == "secret":
print("Access granted.")
else:
print("Access denied.")
Example 1:
Password: secret
Output:
Access granted.
Example 2:
Password: banana
Output:
Access denied.
Python compares the text exactly.
This means:
secret
is not the same as:
Secret
or:
secret
or:
secret
Spaces and capital letters matter.
Python is strict.
Like a security guard who also loves grammar.
Case Sensitivity with Strings
Try:
word = input("Type yes: ")
if word == "yes":
print("You typed yes.")
else:
print("That was not yes.")
If the user types:
yes
Output:
You typed yes.
If the user types:
Yes
Output:
That was not yes.
Why?
Because "yes" and "Yes" are different strings.
Later, you can make input more flexible.
For now, remember:
Python compares strings exactly.
Exact means exact.
No emotional interpretation.
Using lower()
You can make string comparison easier with .lower().
Example:
answer = input("Do you like Python? ")
answer = answer.lower()
if answer == "yes":
print("Excellent choice.")
else:
print("Python will try not to be offended.")
If the user types:
YES
or:
Yes
or:
yes
.lower() converts it to:
yes
This makes comparison easier.
You can also write it shorter:
answer = input("Do you like Python? ").lower()
This is common.
Very useful.
Python forgives capitalization after you tell it how.
Booleans in Conditions
Booleans work naturally with if.
Example:
is_logged_in = True
if is_logged_in:
print("Welcome back!")
else:
print("Please log in.")
Output:
Welcome back!
Because is_logged_in is already True, you do not need to write:
if is_logged_in == True:
This works, but it is unnecessary.
Better:
if is_logged_in:
Clear.
Simple.
Pythonic.
Very nice.
Checking False with not
You can use not to reverse a boolean.
Example:
is_logged_in = False
if not is_logged_in:
print("Please log in.")
else:
print("Welcome back!")
Output:
Please log in.
This means:
If the user is not logged in, print this message.
not reverses the condition.
not True
becomes:
False
And:
not False
becomes:
True
Small word.
Big power.
Use carefully.
Too many nots can make your brain do gymnastics.
Combining Conditions with and
Use and when both conditions must be true.
Example:
age = 25
has_ticket = True
if age >= 18 and has_ticket:
print("You can enter the event.")
else:
print("You cannot enter the event.")
Output:
You can enter the event.
Both conditions are true:
age >= 18
and:
has_ticket
So access is allowed.
If one of them is false, the whole condition is false.
and is strict.
Like a serious nightclub bouncer.
Age is okay?
Ticket is okay?
Then enter.
No ticket?
Goodbye.
Combining Conditions with or
Use or when at least one condition must be true.
Example:
is_admin = False
is_owner = True
if is_admin or is_owner:
print("You can edit this page.")
else:
print("You cannot edit this page.")
Output:
You can edit this page.
Only one condition is true:
is_owner
But that is enough.
or means:
This one or that one or both.
Very useful.
Very common.
Very “one key is enough to open the door”.
Combining Input and and
Create a file:
event_access.py
Write:
age = int(input("Age: "))
has_ticket_answer = input("Do you have a ticket? yes/no: ").lower()
has_ticket = has_ticket_answer == "yes"
if age >= 18 and has_ticket:
print("You can enter the event.")
else:
print("You cannot enter the event.")
Example 1:
Age: 25
Do you have a ticket? yes/no: yes
Output:
You can enter the event.
Example 2:
Age: 25
Do you have a ticket? yes/no: no
Output:
You cannot enter the event.
This line is important:
has_ticket = has_ticket_answer == "yes"
It creates a boolean.
If the answer is "yes", then has_ticket is True.
Otherwise, it is False.
Very useful.
Very clean.
Very Python.
Nested if Statements
You can put an if inside another if.
This is called nesting.
Example:
age = int(input("Age: "))
if age >= 18:
has_ticket = input("Do you have a ticket? yes/no: ").lower()
if has_ticket == "yes":
print("You can enter.")
else:
print("You need a ticket.")
else:
print("You are too young.")
This works.
But be careful.
Too much nesting can make code hard to read.
Nested code is like boxes inside boxes inside boxes.
At some point you forget where the socks are.
Use nesting when it makes sense.
But do not build a maze unless you enjoy suffering.
Flat Code Is Often Easier
This version is simpler:
age = int(input("Age: "))
has_ticket = input("Do you have a ticket? yes/no: ").lower()
if age >= 18 and has_ticket == "yes":
print("You can enter.")
else:
print("You cannot enter.")
This is shorter.
But it gives less specific feedback.
The nested version can say:
You are too young.
or:
You need a ticket.
So both approaches can be useful.
The best choice depends on the situation.
Programming is often not:
one correct answer
It is more like:
which solution is clearer for this problem?
Annoying.
But true.
Common Mistake: Forgetting the Colon
Wrong:
if age >= 18
print("Adult")
Correct:
if age >= 18:
print("Adult")
The colon starts the block.
No colon, no block.
No block, no happiness.
Common Mistake: Wrong Indentation
Wrong:
age = 20
if age >= 18:
print("Adult")
Correct:
age = 20
if age >= 18:
print("Adult")
The code inside the if must be indented.
Python uses indentation to understand structure.
Your spaces are not decoration.
They are architecture.
Very serious spaces.
Common Mistake: Using = Instead of ==
Wrong:
password = input("Password: ")
if password = "secret":
print("Access granted.")
Correct:
password = input("Password: ")
if password == "secret":
print("Access granted.")
Remember:
= assignment
== comparison
One stores.
Two compare.
A tiny difference that can ruin your afternoon.
Common Mistake: Comparing Number Input as Text
Wrong:
age = input("Age: ")
if age >= 18:
print("Adult")
This will fail because age is a string.
Correct:
age = int(input("Age: "))
if age >= 18:
print("Adult")
If you want numeric comparison, convert input to a number.
Python does not compare "20" and 18 like humans do.
Python says:
Text and number? Absolutely not.
Strict.
But reasonable.
Common Mistake: Bad elif Order
Wrong:
score = 95
if score >= 60:
print("Passed")
elif score >= 90:
print("Excellent")
Output:
Passed
The second condition never runs because score >= 60 is already true.
Better:
score = 95
if score >= 90:
print("Excellent")
elif score >= 60:
print("Passed")
else:
print("Failed")
Output:
Excellent
When using elif, order matters.
Think before ordering conditions.
Your program will not do the thinking for you.
Rude.
But expected.
Mini Program: Number Checker
Create a file:
number_checker.py
Write:
number = int(input("Enter a number: "))
if number > 0:
print("The number is positive.")
elif number < 0:
print("The number is negative.")
else:
print("The number is zero.")
Try:
10
Output:
The number is positive.
Try:
-5
Output:
The number is negative.
Try:
0
Output:
The number is zero.
This is a classic conditions exercise.
Simple.
Clear.
Useful.
Not glamorous.
But neither is a screwdriver.
And screwdrivers are important.
Mini Program: Password Check
Create a file:
password_check.py
Write:
password = input("Enter password: ")
if password == "python123":
print("Access granted.")
else:
print("Access denied.")
Try the correct password.
Then try a wrong one.
This is a simple login idea.
Very basic.
Do not use this for real security.
Real security is much more serious.
This is learning.
Not protecting a bank.
Please do not protect a bank with lesson 4.
Mini Program: Simple Discount
Create a file:
discount.py
Write:
total = float(input("Order total: "))
if total >= 100:
discount = total * 0.10
final_total = total - discount
print(f"Discount: {discount:.2f}")
print(f"Final total: {final_total:.2f}")
else:
print("No discount.")
print(f"Final total: {total:.2f}")
Example 1:
Order total: 150
Output:
Discount: 15.00
Final total: 135.00
Example 2:
Order total: 50
Output:
No discount.
Final total: 50.00
This is close to real business logic.
If the order is big enough, apply discount.
Otherwise, no discount.
Small shop logic.
Very useful.
Very real.
Mini Program: Grade Calculator
Create a file:
grade_calculator.py
Write:
score = int(input("Score: "))
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"
print(f"Grade: {grade}")
Try different scores:
95
85
75
65
50
The program should give different grades.
This uses:
- input;
- type conversion;
if;elif;else;- variables;
- output.
Many concepts together.
The Python soup is getting richer.
Still no USB flavor.
Hopefully.
Practice
Create a file:
practice_conditions.py
Write a program that asks for:
- username;
- age;
- whether the user is a student.
Then:
- if age is under 18, print
"You are young."; - if age is between 18 and 64, print
"You are an adult."; - if age is 65 or more, print
"You are a senior."; - if the user is a student, print
"Student mode activated.".
Example:
username = input("Username: ")
age = int(input("Age: "))
student_answer = input("Are you a student? yes/no: ").lower()
print(f"Hello, {username}!")
if age < 18:
print("You are young.")
elif age < 65:
print("You are an adult.")
else:
print("You are a senior.")
if student_answer == "yes":
print("Student mode activated.")
Notice this line:
elif age < 65:
We do not need to write:
age >= 18 and age < 65
Why?
Because if Python reaches this elif, it already knows that:
age < 18
was false.
So the age is already 18 or more.
Order helps.
Beautiful logic.
Very Python.
Mini Challenge
Create a file:
shipping_calculator.py
Your program should ask for:
- customer name;
- order total;
- country;
- whether the customer is VIP.
Rules:
If order total is 100 or more, shipping is free.
If customer is VIP, shipping is free.
If country is "italy", shipping is 5.
Otherwise, shipping is 15.
Then print:
Customer: Anna
Order total: 80.00
Shipping: 5.00
Final total: 85.00
Example solution:
customer_name = input("Customer name: ")
order_total = float(input("Order total: "))
country = input("Country: ").lower()
vip_answer = input("VIP customer? yes/no: ").lower()
is_vip = vip_answer == "yes"
if order_total >= 100 or is_vip:
shipping = 0
elif country == "italy":
shipping = 5
else:
shipping = 15
final_total = order_total + shipping
print("----- Order Summary -----")
print(f"Customer: {customer_name}")
print(f"Order total: {order_total:.2f}")
print(f"Shipping: {shipping:.2f}")
print(f"Final total: {final_total:.2f}")
Test it with different values.
Try:
Order total: 120
VIP: no
Try:
Order total: 50
VIP: yes
Try:
Country: italy
Order total: 80
VIP: no
Try:
Country: france
Order total: 80
VIP: no
The program should choose different shipping costs.
This is real logic.
Small.
But real.
The program is now making decisions.
Very good.
Very Python.
Beginner Checklist
When your condition program does not work, check:
Did I save the file?
Did I use a colon after if, elif, and else?
Is the code inside the condition indented?
Did I use == for comparison?
Did I use = only for assignment?
Did I convert input to int or float before numeric comparison?
Are my elif conditions in the correct order?
Did I write True and False with capital letters?
Did I compare strings exactly?
Did I use .lower() when I wanted flexible text input?
Most condition bugs are not big.
They are usually small logic mistakes.
The computer does exactly what you wrote.
Not what you meant.
This is annoying.
This is programming.
Welcome.
Summary
Today you learned:
- conditions let programs make decisions;
- conditions return
TrueorFalse; ifruns code when a condition is true;elseruns code when theifcondition is false;elifchecks another condition;- Python checks
ifandeliffrom top to bottom; - indentation defines code blocks;
- the colon
:starts a block; ==compares values;=assigns values;- strings are compared exactly;
.lower()helps with flexible text input;- booleans work naturally in conditions;
andrequires both conditions to be true;orrequires at least one condition to be true;notreverses a condition;- order matters in
elifchains.
This is a huge step.
Your programs can now choose.
They can react.
They can say yes or no.
They can apply discounts.
They can check passwords.
They can calculate shipping.
They can judge numbers.
A little.
Not morally.
Just mathematically.
Good.
Next Lesson
In the next lesson, we will learn loops.
Loops let your program repeat actions.
Instead of writing:
print("Hello")
print("Hello")
print("Hello")
you will write something smarter.
You will learn:
for
while
Loops are powerful.
Loops are useful.
Loops are also dangerous if you accidentally create one that never stops.
But that is a future adventure.
For now, your programs can make decisions.
Very strong progress.
Very Python.