Imagine you are writing a school examination. Your teacher checks your score to determine whether you passed or failed.
If your score is 50 or above, you pass. If your score is below 50, you fail.
This is an example of decision-making. A decision depends on whether a particular condition is true or false.
Python can make decisions using conditional statements.
Conditional statements allow a program to perform different actions depending on whether a condition is True or False.
For example:
score = 75
if score >= 50:
print("Congratulations! You passed.")
Output:
Congratulations! You passed.
Python checks whether the score is greater than or equal to 50. Because the condition is True, it displays the congratulatory message.
By the end of this module, you should be able to:
if statement.if...else statements.if...elif...else statements.A condition is an expression that Python evaluates to determine whether something is True or False.
For example:
age = 18
print(age >= 18)
Output:
True
The condition is True because 18 is equal to 18.
Another example:
score = 40
print(score >= 50)
Output:
False
The condition is False because 40 is less than 50.
The if statement tells Python to perform an action only when a condition is True.
Basic structure:
if condition:
statement
The condition is checked first. If it is True, Python executes the indented statement. If it is False, Python skips that statement.
score = 80
if score >= 50:
print("You passed the examination.")
Output:
You passed the examination.
age = 20
if age >= 18:
print("You are an adult.")
Output:
You are an adult.
If the age were 15, Python would not display the message because the condition would be False.
Sometimes, you want your program to choose between two possible actions.
The if...else statement allows Python to perform one action when a condition is True and another action when it is False.
Basic structure:
if condition:
statement_if_true
else:
statement_if_false
score = 45
if score >= 50:
print("Congratulations! You passed.")
else:
print("Sorry, you failed.")
Output:
Sorry, you failed.
Because the score is 45, the condition is False. Python executes the code inside the else section.
number = 7
if number % 2 == 0:
print("This is an even number.")
else:
print("This is an odd number.")
Output:
This is an odd number.
The modulus operator checks the remainder after dividing the number by 2. If the remainder is 0, the number is even. Otherwise, it is odd.
What happens when a program needs to choose from more than two possibilities?
For example, a school may use the following grading system:
| Score | Grade |
|---|---|
| 70 - 100 | A |
| 60 - 69 | B |
| 50 - 59 | C |
| 45 - 49 | D |
| 0 - 44 | F |
You can use if, elif and else to build a program that checks these conditions.
Basic structure:
if condition1:
statement1
elif condition2:
statement2
elif condition3:
statement3
else:
default_statement
The word elif means "else if". It allows Python to check another condition when the previous condition is False.
score = 75
if score >= 70:
print("Grade A")
elif score >= 60:
print("Grade B")
elif score >= 50:
print("Grade C")
elif score >= 45:
print("Grade D")
else:
print("Grade F")
Output:
Grade A
Python checks the conditions from top to bottom. Once it finds a True condition, it executes the matching block and skips the remaining branches.
Comparison operators help Python compare values when making decisions.
| Operator | Meaning | Example |
|---|---|---|
| == | Equal to | age == 18 |
| != | Not equal to | age != 18 |
| > | Greater than | score > 50 |
| < | Less than | score < 50 |
| >= | Greater than or equal to | score >= 50 |
| <= | Less than or equal to | score <= 50 |
balance = 5000
if balance > 1000:
print("You have enough money.")
else:
print("Your balance is low.")
Output:
You have enough money.
Logical operators allow you to combine multiple conditions in a single decision.
Python has three main logical operators:
andornotThe and operator requires all combined conditions to be True.
Example: A student must score at least 50 and complete all required assignments to qualify for a certificate.
score = 75
assignment_completed = True
if score >= 50 and assignment_completed:
print("You qualify for a certificate.")
else:
print("You do not qualify yet.")
Output:
You qualify for a certificate.
The or operator returns True if at least one of the conditions is True.
Example: A student can access a school library using a student ID or a valid library card.
has_student_id = False
has_library_card = True
if has_student_id or has_library_card:
print("Library access granted.")
else:
print("Library access denied.")
Output:
Library access granted.
The not operator reverses a condition.
is_absent = False
if not is_absent:
print("The student is present.")
else:
print("The student is absent.")
Output:
The student is present.
A nested if statement is an if statement placed inside another if statement.
It allows a program to make a second decision after the first condition has been met.
Imagine that a student must be registered and must have paid the examination fee before taking an examination.
is_registered = True
has_paid = True
if is_registered:
print("Registration confirmed.")
if has_paid:
print("You can take the examination.")
else:
print("Please pay your examination fee.")
else:
print("Please register first.")
Output:
Registration confirmed.
You can take the examination.
The first condition checks registration. If registration is confirmed, Python checks the second condition to determine whether the student has paid.
Python allows you to check whether a value falls between two numbers.
For example:
age = 15
if 13 <= age <= 19:
print("You are a teenager.")
else:
print("You are outside the teenage age range.")
Output:
You are a teenager.
This condition checks whether the age is at least 13 and no more than 19.
Indentation means adding spaces at the beginning of a line of code.
Python uses indentation to identify which statements belong to an if, elif or else block.
Example of correct indentation:
score = 80
if score >= 50:
print("You passed.")
print("Well done!")
Both print statements belong to the if block.
Example of incorrect indentation:
score = 80
if score >= 50:
print("You passed.")
This code produces an indentation error because the statement inside the if block is not indented.
You are creating a student result checker for a school. The program should collect a student's name and examination score, then display the appropriate grade and result.
Project Requirements:
name = input("Enter student's name: ")
score = float(input("Enter examination score: "))
print("\n--- STUDENT RESULT ---")
print("Student Name:", name)
if score < 0 or score > 100:
print("Invalid score. Enter a score between 0 and 100.")
elif score >= 70:
print("Grade: A")
print("Result: Excellent")
elif score >= 60:
print("Grade: B")
print("Result: Very Good")
elif score >= 50:
print("Grade: C")
print("Result: Good")
elif score >= 45:
print("Grade: D")
print("Result: Pass")
else:
print("Grade: F")
print("Result: Fail")
Example Interaction:
Enter student's name: Amina Yusuf
Enter examination score: 85
--- STUDENT RESULT ---
Student Name: Amina Yusuf
Grade: A
Result: Excellent
Write a program that asks a user to enter their age. If the age is 18 or above, display "You are eligible to vote". Otherwise, display "You are not yet eligible to vote".
Ask a user to enter a number. Use conditional statements to determine whether the number is positive, negative or zero.
Create a program that asks for the total shopping amount. If the amount is โฆ10,000 or more, display "You qualify for a discount". Otherwise, display "No discount available".
Ask a user to enter a password. Compare it with a predefined sample password. Display "Access granted" if they match and "Access denied" if they do not.
Ask a user to enter two numbers. Use conditional statements to display the larger number. Also handle the situation where both numbers are equal.
if, elif and else statement must end with a colon.== when comparing two values.else block must come after all if and elif branches.int() or float() before comparing it with numbers.| Term | Meaning |
|---|---|
| Conditional Statement | A statement that allows a program to make decisions. |
| Condition | An expression that evaluates to True or False. |
| if | Checks a condition and executes code when it is True. |
| else | Executes code when the preceding if condition is False. |
| elif | Checks another condition when previous conditions are False. |
| Nested if | An if statement placed inside another if statement. |
| Indentation | Spaces used at the beginning of a line to organise code blocks. |
| Boolean | A data type that has two values: True and False. |
| Logical Operator | An operator used to combine or reverse conditions. |
In this module, you learned how Python makes decisions using conditional statements.
You explored the if, if...else and if...elif...else statements. You also learned how to combine conditions using logical operators, create nested conditions and use comparison operators to check information.
Conditional statements are important because they allow programs to respond differently depending on the information they receive.
You can use these skills to build grading systems, password checkers, shopping discount calculators, eligibility checkers and many other useful applications.
Test your understanding of Module 7 by answering the following questions.
1. What is the main purpose of conditional statements in Python?
2. Which keyword is used to check a condition in Python?
3. Which keyword is used when the if condition is False?
4. What does elif mean?
5. Which operator checks whether two values are equal?
6. Which logical operator requires all combined conditions to be True?
7. What is a nested if statement?
8. What does the not operator do?
9. What must appear at the end of an if statement line?
10. What is indentation used for in conditional statements?
Module 8: Python Loops and Functions
In the final module, you will learn how to make Python repeat instructions and organise reusable blocks of code.
You will explore for loops, while loops and functions. You will also learn how to create simple programs that perform repeated tasks without writing the same instructions many times.