Welcome to Module 4! In the previous module, you learned how to organise information using Python lists, tuples, dictionaries, and sets.
In this module, you will learn how to make Python decisions, repeat instructions automatically, and create reusable blocks of code called functions.
These skills are important because data analysts often need to check information, repeat calculations, and perform tasks on large datasets.
Conditional statements allow Python to make decisions based on certain conditions.
Think about what happens when you are writing an examination. If you score 50 or above, you pass. If you score below 50, you fail.
Python can make this decision automatically using conditional statements.
Example:
score = 75
if score >= 50:
print("You passed the examination")
Output:
You passed the examination
In this example:
Python provides three important keywords for making decisions: if, elif, and else.
The if statement tells Python to perform an action when a condition is true.
age = 13
if age >= 13:
print("You are a teenager")
Output:
You are a teenager
The else statement tells Python what to do when the if condition is false.
score = 35
if score >= 50:
print("You passed")
else:
print("You failed")
Output:
You failed
Python checks the score. Since 35 is less than 50, it displays "You failed".
The elif keyword means "else if". It allows Python to check another condition when the previous condition is false.
Imagine a school uses the following grading system:
You can use Python to check the grade automatically.
score = 75
if score >= 80:
print("Excellent")
elif score >= 60:
print("Good")
elif score >= 50:
print("Average")
else:
print("Fail")
Output:
Good
Python checks each condition from top to bottom. When it finds a true condition, it executes that instruction and skips the remaining branches.
Comparison operators are symbols used to compare two values. They help Python decide whether a condition is true or false.
| Operator | Meaning | Example | Result |
|---|---|---|---|
| == | Equal to | 10 == 10 | True |
| != | Not equal to | 10 != 5 | True |
| > | Greater than | 10 > 5 | True |
| < | Less than | 5 < 10 | True |
| >= | Greater than or equal to | 10 >= 10 | True |
| <= | Less than or equal to | 5 <= 10 | True |
Example:
price = 5000
if price > 3000:
print("The product is expensive")
Output:
The product is expensive
Logical operators allow Python to combine two or more conditions.
There are three important logical operators:
The and operator returns True only when both conditions are true.
age = 15
has_card = True
if age >= 13 and has_card == True:
print("You can enter")
Output:
You can enter
The or operator returns True when at least one of the conditions is true.
day = "Saturday"
if day == "Saturday" or day == "Sunday":
print("It is the weekend")
Output:
It is the weekend
The not operator reverses a Boolean value. True becomes False, and False becomes True.
is_raining = False
if not is_raining:
print("You can play outside")
Output:
You can play outside
A loop is a programming instruction that allows Python to repeat a task several times.
Imagine you want to display the names of 100 students. Writing 100 separate print() instructions would take a lot of time.
Instead, you can use a loop to repeat the instruction automatically.
Python has two commonly used loops:
A for loop repeats an instruction for each item in a collection or over a sequence of values.
Example:
fruits = ["Mango", "Orange", "Banana"]
for fruit in fruits:
print(fruit)
Output:
Mango
Orange
Banana
Python displays each fruit one after another.
The range() function generates a sequence of numbers that a loop can use.
for number in range(1, 6):
print(number)
Output:
1
2
3
4
5
The range(1, 6) instruction generates numbers from 1 to 5. The ending number, 6, is not included.
A while loop repeats an instruction as long as a condition remains true.
Example:
number = 1
while number <= 5:
print(number)
number = number + 1
Output:
1
2
3
4
5
Python continues printing the numbers while the condition number <= 5 remains true.
Important: Always make sure a while loop can eventually become false. Otherwise, you may create an infinite loop that keeps running without stopping.
Data analysts often use loops to work through lists of numbers and calculate useful results.
Imagine a teacher has recorded the scores of five students:
scores = [70, 85, 60, 90, 75]
for score in scores:
print(score)
Output:
70
85
60
90
75
You can also calculate the total score using a loop.
scores = [70, 85, 60, 90, 75]
total = 0
for score in scores:
total = total + score
print(total)
Output:
380
The loop adds all five scores together. The total is 380.
You can calculate the average by dividing the total by the number of scores.
scores = [70, 85, 60, 90, 75]
total = 0
for score in scores:
total = total + score
average = total / len(scores)
print(average)
Output:
76.0
The len() function counts the number of items in a collection. In this example, there are five scores.
A function is a reusable block of code designed to perform a particular task.
Think about a calculator. When you press the addition button, it performs an addition task. A Python function works in a similar way.
Functions help programmers avoid writing the same instructions repeatedly.
Python provides built-in functions such as:
Example:
scores = [70, 85, 60, 90, 75]
print(sum(scores))
print(max(scores))
print(min(scores))
print(len(scores))
Output:
380
90
60
5
You can also create your own functions using the def keyword.
Example:
def greet():
print("Welcome to Python!")
greet()
Output:
Welcome to Python!
In this example:
A parameter is information that a function receives so it can perform a task.
Example:
def greet(name):
print("Hello", name)
greet("David")
greet("Grace")
Output:
Hello David
Hello Grace
The name parameter allows the function to greet different people.
Imagine a shop owner wants to calculate the total amount made from selling three products.
def calculate_sales(rice, beans, garri):
total = rice + beans + garri
return total
result = calculate_sales(5000, 3000, 2000)
print(result)
Output:
10000
The function receives three values, adds them together, and returns the total.
These Python features help data analysts work with information more efficiently.
For example, a school can use Python conditions to identify students who scored above 70, loops to check every student's score, and functions to calculate the average examination result.
In this module, you have learned:
Open Google Colab or another Python environment and complete these activities:
A teacher records the following examination scores:
Your Task:
Remember: Conditions help Python make decisions, loops help it repeat tasks, and functions help you reuse code. These three skills will become very useful when you start analysing real datasets.