Hiring Partners
Segilola Resources Operating LimitedTaviatech TechnologiesFCMBMTN NigeriaAdvans La Fayette Microfinance BankAboki AfricaFirst Bank of NigeriaOPay
โ† Introduction to Python for Data Analysis ยท Lesson 5 of 9

Module Four

๐Ÿ“– Every lesson in this course is free to read right here, no account needed. Create a free account to track your progress, take the exam, and earn your certificate.
5
Module 4: Python Conditions, Loops, and Functions Introduction to Python for Data Analysis | Beginner-friendly lesson for 13-year-olds

Module 4: Python Conditions, Loops, and Functions

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.

4.1 Understanding Conditional Statements

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:

  • if tells Python to check a condition.
  • score >= 50 checks whether the score is greater than or equal to 50.
  • print() displays a message if the condition is true.

4.2 Understanding If, Elif, and Else

Python provides three important keywords for making decisions: if, elif, and else.

1. The If Statement

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

2. The Else Statement

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".

3. The Elif Statement

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:

  • 80 to 100: Excellent
  • 60 to 79: Good
  • 50 to 59: Average
  • Below 50: Fail

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.

4.3 Understanding Comparison Operators

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 to10 == 10True
!=Not equal to10 != 5True
>Greater than10 > 5True
<Less than5 < 10True
>=Greater than or equal to10 >= 10True
<=Less than or equal to5 <= 10True

Example:

price = 5000

if price > 3000:
    print("The product is expensive")

Output:

The product is expensive

4.4 Understanding Logical Operators

Logical operators allow Python to combine two or more conditions.

There are three important logical operators:

1. AND Operator

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

2. OR Operator

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

3. NOT Operator

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

4.5 Understanding Python Loops

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:

  • For loop
  • While loop

1. The For Loop

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.

Using a For Loop with Range()

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.

2. The While Loop

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.

4.6 Using Loops to Analyse Simple Data

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.

4.7 Understanding Python Functions

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:

  • print() - displays information.
  • len() - counts the number of items.
  • sum() - adds numbers together.
  • max() - finds the largest value.
  • min() - finds the smallest value.
  • round() - rounds a number.

Example:

scores = [70, 85, 60, 90, 75]

print(sum(scores))
print(max(scores))
print(min(scores))
print(len(scores))

Output:

380
90
60
5

4.8 Creating Your Own Python Functions

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:

  • def tells Python that you are creating a function.
  • greet is the name of the function.
  • The indented print() instruction is the task performed by the function.
  • greet() calls the function and makes it run.

Creating a Function with Parameters

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.

Creating a Function to Calculate Total Sales

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.

4.9 Why Conditions, Loops, and Functions Matter in Data Analysis

These Python features help data analysts work with information more efficiently.

  • Conditions: Help identify students who passed or failed an examination.
  • Loops: Help process hundreds or thousands of records automatically.
  • Functions: Help perform repeated calculations without rewriting the same code.

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.

4.10 Summary of the Module

In this module, you have learned:

  • Conditional statements allow Python to make decisions.
  • The if, elif, and else keywords are used to check conditions.
  • Comparison operators compare two values.
  • Logical operators combine conditions.
  • Loops allow Python to repeat instructions.
  • For loops work through collections and sequences.
  • While loops repeat instructions while a condition is true.
  • Functions are reusable blocks of code.
  • The def keyword is used to create a function.
  • Functions can receive information through parameters and return results.

4.11 Practical Exercise

Open Google Colab or another Python environment and complete these activities:

  1. Create a variable called score and write an if statement to check whether a student passed or failed. Use 50 as the pass mark.
  2. Write an if, elif, and else statement to classify a student's score as Excellent, Good, Average, or Fail.
  3. Create a for loop that displays numbers from 1 to 10.
  4. Create a while loop that displays numbers from 1 to 5.
  5. Create a list containing five examination scores and use a for loop to display each score.
  6. Use the sum(), max(), min(), and len() functions to analyse a list of numbers.
  7. Create a function called calculate_total() that adds three numbers together.

Practical Challenge: Analyse Students' Examination Results

A teacher records the following examination scores:

  • Ada: 85
  • Tunde: 45
  • Musa: 70
  • Grace: 90
  • John: 35

Your Task:

  1. Create a list containing the five examination scores.
  2. Use a for loop to check each student's score.
  3. Use an if statement to display "Pass" when a score is 50 or above.
  4. Display "Fail" when a score is below 50.
  5. Create a function that calculates the average score.
  6. Display the highest and lowest scores.

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.

๐Ÿ† Get Certified

๐Ÿ”’

Earn this certificate

Every lesson is already free to read. Sign up, finish the lessons, pass the exam (โ‚ฆ2,000 or 20,000 coins), and get a verified certificate with your name on it.

๐ŸŽ“ Sign Up to Get Certified
๐Ÿ› ๏ธ Practice Tools
Hands-on simulators & labs - subscription required.
โ†’
๐ŸŽฏ Internship Tasks
Real-world tasks to build your portfolio - unlock them with a subscription.
โ†’