100% found this document useful (1 vote)
69 views55 pages

Python Coding by Solving African Problem Regis Nguessan

This document discusses Python programming for solving problems in Africa. It covers installing Python, Python basics like variables, data types, operators and control structures. It also discusses functions, lists, dictionaries and more advanced topics like recursion and lambda functions. Examples provided include managing food stocks, calculating GDP per capita and drug inventory management. The document aims to equip readers with Python skills to address challenges across the African continent.

Uploaded by

sergecard6
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
100% found this document useful (1 vote)
69 views55 pages

Python Coding by Solving African Problem Regis Nguessan

This document discusses Python programming for solving problems in Africa. It covers installing Python, Python basics like variables, data types, operators and control structures. It also discusses functions, lists, dictionaries and more advanced topics like recursion and lambda functions. Examples provided include managing food stocks, calculating GDP per capita and drug inventory management. The document aims to equip readers with Python skills to address challenges across the African continent.

Uploaded by

sergecard6
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 55

Subscribe to DeepL Pro to translate larger documents.

Visit www.DeepL.com/pro for more information.

Python programming
by solving African problems

Regis N'guessan

Publication date : September 30, 2023

@Regis
LinkedIn
YouTube
2
Python Programming for African Problem Solving

Regis N'guessan

September 30, 2023


ii
Contents

Preamble 1

1 Installing Python 3
1.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2 Installing Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2.1 Downloading Python ... ... ... ... ... ... ... ... ... ... ... ... ... . 3
1.2.2 Installing Python on Windows ... ... ... ... ... ... ... ... ... ... ... ... . 3
1.2.3 Installing Python on macOS ... ... ... ... ... ... ... ... ... ... ... ... . 3
1.2.4 Installing Python on Linux ... ... ... ... ... ... ... ... ... ... ... ... . 4
1.2.5 Installation check . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

2 Python basics 5
2.1
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.2 Variables and Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.2.1 Variables and assignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.2.2 Basic data types ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... . 5
2.2.3 Type conversion ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... . 5
2.2.4 Comments ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... . 5
2.3 Operations and operators ........................................................................... 6
2.3.1 Mathematical operations ... ... ... ... ... ... ... ... ... ... ... ... ... . 6
2.3.2 Comparison operators . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.3.3 Logic operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.4 Control structures ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... . 6
2.4.1 Conditional (if, elif, else) ... ... ... ... ... ... ... ... ... ... ... ... ... ... . 6
2.4.2 Loops (for, while) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.4.3 Break and continuous ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... . 6
2.5 Application example: Managing food stocks in a village in Africa 6
2.5.1 Python code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.5.2 Code explanation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

3 Functions 9
3.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
3.2 Defining functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
3.2.1 Creating functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
3.2.2 Parameters and arguments ... ... ... ... ... ... ... ... ... ... ... ... ... ... . 9
3.2.3 Integrated functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
3.3 Using functions ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... . 9
3.3.1 Calling up functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
3.3.2 Return values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
3.4 Function documentation ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... . 10
3.5 Application example: Calculation of GDP per capita in Benin . . . . . . . . . . . . 10
3.5.1 Python code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
3.5.2 Code explanations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

iii
iv CONTENTS

4 Lists and Dictionaries 13


4.1 Introduction ......................................................................................................................................13
4.2 Listings.............................................................................................................................................13
4.2.1 List creation.........................................................................................................................13
4.2.2 Element access ....................................................................................................................13
4.2.3 List editing ..........................................................................................................................13
4.2.4 List operations .....................................................................................................................13
4.2.5 For loops with lists ..............................................................................................................14
4.3 Dictionaries ......................................................................................................................................14
4.3.1 Dictionary creation ..............................................................................................................14
4.3.2 Values access.......................................................................................................................14
4.3.3 Editing dictionaries..............................................................................................................14
4.3.4 Operations on dictionaries...................................................................................................14
4.4 Application example: Drug inventory management in Senegal ......................................................14
4.4.1 Python code .........................................................................................................................14
4.4.2 Code explanation .................................................................................................................15

5 Advanced Functions 17
5.1 Introduction ......................................................................................................................................17
5.2 Recursive functions..........................................................................................................................17
5.2.1 What i s a recursive function? ...........................................................................................17
5.2.2 Structure of a recursive function .........................................................................................17
5.2.3 Example: Factorial calculation ............................................................................................17
5.3 Lambda functions.............................................................................................................................17
5.3.1 What i s a lambda function?..............................................................................................17
5.3.2 Syntax of a lambda function................................................................................................18
5.3.3 Using lambda functions.......................................................................................................18
5.4 Scope of Variables ...........................................................................................................................18
5.4.1 Local and global variables...................................................................................................18
5.4.2 Global instruction..............................................................................................................18
5.5 Application example: Solving an educational problem in Burkina Faso with
Python.............................................................................................................................................18
5.6 Problem: Calculating the number of registered students.........................................................18
5.6.1 Background .........................................................................................................................18
5.6.2 Objective .............................................................................................................................18
5.6.3 Python solution....................................................................................................................18

6 Modules and Packages 21


6.1 Introduction ......................................................................................................................................21
6.2 Modules............................................................................................................................................21
6.2.1 Importing modules ..............................................................................................................21
6.2.2 Using module functions and variables ................................................................................21
6.2.3 Creating modules.................................................................................................................21
6.3 Packages...........................................................................................................................................21
6.3.1 Package creation..................................................................................................................21
6.3.2 Importing modules from a package...............................................................................22
6.3.3 Using functions and module variables in a package ...........................................................22
6.4 Importing with aliases..................................................................................................................22
6.5 Application example: Agricultural Production Management in Côte d'Ivoire ................................22
6.5.1 Python code .........................................................................................................................22
6.5.2 Using the Package ...............................................................................................................23
6.5.3 Explanation..........................................................................................................................23
Regis N'guessan v

7 File and Data Manipulation 25


7.1 Introduction ......................................................................................................................................25
7.2 Reading Files ...................................................................................................................................25
7.2.1 Opening files .......................................................................................................................25
7.2.2 Reading content...................................................................................................................25
7.2.3 Closing files ........................................................................................................................25
7.3 Writing to Files ................................................................................................................................25
7.3.1 File writing ..........................................................................................................................25
7.4 Working with CSV files...................................................................................................................26
7.4.1 The CSV module .................................................................................................................26
7.4.2 Reading CSV files ...............................................................................................................26
7.4.3 Writing to CSV files............................................................................................................26

8 Graphics and Data Visualization 29


8.1 Introduction ......................................................................................................................................29
8.2 Introduction to Matplotlib ...........................................................................................................29
8.2.1 Installing Matplotlib ........................................................................................................29
8.2.2 Importing Matplotlib .......................................................................................................29
8.3 Graphics creation .............................................................................................................................29
8.3.1 Line graph ...........................................................................................................................29
8.3.2 Bar graph .............................................................................................................................30
8.4 Customize graphics ..........................................................................................................................30
8.4.1 Colors, styles and captions ..................................................................................................30
8.4.2 Sub-graphics ........................................................................................................................30
8.4.3 Exporting graphics ..............................................................................................................30
8.5 Data Visualization with Seaborn......................................................................................................30
8.6 Application example: Visualizing unemployment trends in Cameroon ..........................................30
8.6.1 Step 1: Data collection ........................................................................................................30
8.6.2 Step 2: Data preparation......................................................................................................31
8.6.3 Step 3: Graph creation.........................................................................................................31
8.6.4 Code explanation .................................................................................................................31

9 Databases 33
9.1 Introduction ......................................................................................................................................33
9.2 Relational Databases ........................................................................................................................33
9.2.1 What i s a relational database? ..........................................................................................33
9.2.2 SQL (Structured Query Language) .....................................................................................33
9.3 Using SQLite in Python ...................................................................................................................33
9.3.1 SQLite installation...............................................................................................................33
9.3.2 Creating a database..............................................................................................................33
9.3.3 Table creation......................................................................................................................34
9.3.4 Inserting, updating and deleting data ..................................................................................34
9.3.5 Data query ...........................................................................................................................34
9.3.6 Closing the database............................................................................................................34
9.4 Using SQLAlchemy .........................................................................................................................34
9.4.1 Installing SQLAlchemy.......................................................................................................34
9.4.2 Using SQLAlchemy ............................................................................................................34
9.5 Example: Agricultural Data Management in Ghana with a Database .............................................34
9.5.1 Python code .........................................................................................................................35
9.5.2 Code explanation .................................................................................................................35
vi CONTENTS

10 Object-oriented programming 37
10.1 Introduction ......................................................................................................................................37
10.2 Classes and Objects..........................................................................................................................37
10.2.1 What i s a class? .................................................................................................................37
10.2.2 Object creation ....................................................................................................................37
10.3 Attributes and Methods................................................................................................................37
10.3.1 Attributes ...........................................................................................................................37
10.3.2 Methods ...............................................................................................................................38
10.4 Heritage ............................................................................................................................................38
10.5 Encapsulation ...................................................................................................................................38
10.6 Example: OOP modeling of a banking system in Congo ................................................................39
10.6.1 Python code .........................................................................................................................39
10.6.2 Explanation of the Code ......................................................................................................39

11 Python projects for Africa 41


11.1 Project 1: Calculating Economic Growth in Nigeria .......................................................................41
11.2 Project 2: Population monitoring in Ethiopia...................................................................................41
11.3 Project 3: Currency converter for Kenya .........................................................................................41
11.4 Project 4: Prediction of the Peanut H a r v e s t in Senegal.............................................................41
11.5 Project 5: Exchange Rate Calculator in South Africa .............................................................41

12 From Solution Approaches to Python Projects for Africa 43


12.1 Solution to Project 1: Calculating Economic Growth in Nigeria.....................................................43
12.2 Solution to Project 2: Population monitoring in Ethiopia................................................................43
12.3 Solution to Project 3: Currency converter for Kenya.......................................................................44
12.4 Solution to Project 4: Predicting the Peanut H a r v e s t in Senegal ..............................................44
12.5 Solution to Project 5: South African Exchange Rate Calculator......................................................45
12.6 Epilogue: Python, the Endless Adventure ........................................................................................46
12.6.1 Python, a Faithful Friend.....................................................................................................46
12.6.2 Les Joies des Boucles ..........................................................................................................46
12.6.3 Riddles of the Reach............................................................................................................46
12.6.4 Limitless Creativity .............................................................................................................46
12.6.5 The Bright Future.............................................................................................................46
12.6.6 This Book is Free and Open Source!...................................................................................46
12.6.7 Your Contributions Are Welcome!.....................................................................................46
12.6.8 Staying Connected...............................................................................................................47
Preamble

Welcome to this Python programming book dedicated to Africa. This book is designed for anyone
wishing to acquire programming skills while addressing the real problems of the African environment.
Whether you're a student, a professional or simply someone who wants to learn how to code, this book
is designed to help you develop your programming expertise while addressing the challenges facing
Africa.

Why this book?


Africa is a dynamic and growing continent, facing a multitude of challenges and opportunities. In
this context, computer programming offers a powerful tool for solving concrete problems and
contributing to Africa's sustainable development. This book aims to :

• Empower learners: Programming gives African learners the opportunity to create innova-
tive solutions to local problems, fostering empowerment and individual initiative.

• Developing Essential Skills: Mastering programming has become a key skill in the global
economy. It offers career opportunities in a variety of fields, from technology to finance to
healthcare.

• Solving local problems : By addressing problems specific to Africa, this book shows how
programming can be used to solve challenges such as natural resource management, public
health monitoring and economic development.

• Promoting Creativity: Programming encourages creativity by enabling people to design


applications, websites, automated systems and much more.

Who's it for?
This book is aimed at a diverse audience, from complete beginners to intermediate programmers. You
don't need any previous programming experience to get started. The resources and projects presented
are designed to suit different skill levels. Whether you're a student at an African school, a professional
looking for new skills, or simply curious to understand the world of programming, this book is
designed for you.

Book structure
This book is structured in a series of chapters, each focusing on a specific aspect of Python
programming. We start with the basics and progress to more advanced concepts, while tackling real
problems encountered in Africa. Each chapter includes code examples, practical exercises and real-life
projects to reinforce your learning.

1
2 CONTENTS

How to use this book


This book is designed to be interactive and practical. To get the most out of your learning, I encourage
you to follow these recommendations:

• Practice: Programming i s learned by doing. Try out the code examples, solve the exercises
and complete the projects to reinforce your understanding.
• Experiment: Don't be afraid to try out new ideas. Creativity is essential in programming. Try to
tailor projects to specific problems in your area.
• Collaborate: Programming is often a collaborative effort. Share your ideas, work with
other learners and be open to comments and suggestions.
• Stay curious: Technology evolves rapidly. Stay on top of the latest trends and technologies to
continue developing your skills.

Ultimately, this book is a starting point for your journey into the exciting world of programming.
We hope it will inspire you to tackle the challenges of Africa using the power of programming.
Happy reading and learning!

Regis N'guessan
Chapter 1

Installing Python

1.1 Introduction
In this first chapter, we'll guide you through the process o f installing Python on your computer.
Python is a powerful and versatile programming language, widely used to solve a variety of problems,
including those facing Africa. We'll also explore some examples of African problems that can be
tackled with Python.

1.2 Installing Python


Python is an open-source language, which means you can download and install it free of charge.
Here's how to install it on different platforms.

1.2.1 Download Python


Visit the official Python website at https://www.python.org/downloads/ to download the latest
version of Python.

1.2.2 Installing Python on Windows


Download installer
Download the Python installer for Windows from the official website.

Launching the installer


Double-click on the downloaded installation file. Check the "Add Python to PATH" box during
installation to make Python accessible from any directory.

Installation
Follow the on-screen instructions to complete the installation.

1.2.3 Installing Python on macOS


Download installer
Download the Python installer for macOS from the official website.

3
4 CHAPTER 1. INSTALLING PYTHON

Launching the installer


Open the downloaded installation file.

Installation
Follow the on-screen instructions to complete the installation.

1.2.4 Installing Python on Linux


Python is generally preinstalled on most Linux distributions. To check whether Python is already
installed, open a terminal and run the following command:
python3 --v e rs i o n
If you don't have Python installed, you can install it from the package manager of your Linux
distribution. For example, on Ubuntu, you can use the following command:
sudo apt-get i n s t a l l python3

1.2.5 Installation check


After installing Python, you can check that everything is working correctly by opening a terminal
(or command prompt under Windows) and typing the following command:
python --v e rs i o n
You should see the version of Python you have just installed displayed on the screen.
Congratulations! You've now installed Python on your computer. You're ready to start
programming in Python and solving African problems with this powerful language.
Chapter 2

Python basics

2.1 Introduction
In this chapter, we'll explore the basics of Python programming. You'll learn the fundamental
concepts, including variables, operators, control structures and functions. These concepts are essential
for solving the African problems we'll cover l a t e r i n t h e book.

2.2 Variables and Data Types


2.2.1 Variables and assignment
In Python, variables are memory spaces that you can use to store data. To assign a value to a variable,
use the equal sign (=). For example:
name =
"John" age =
30

2.2.2 Basic data types


Python supports several b a s i c data types, including :
• Integers: for example, 5, -2, 100
• Floats: for example, 3.14, -0.5, 2.0
• Strings: for example, "Hello", 'Python'.
• Booleans: True or False

2.2.3 Type conversion


You can convert values from one type to another. For example :
number = 42
text = str(number) % Converts the number into a string

2.2.4 Comments
Comments are annotations in Python code that are not executed. They begin with the "#" symbol
and are useful for explaining the code. For example:
# This is a comment

5
6 CHAPTER 2. PYTHON BASICS

2.3 Operations and Operators


2.3.1 Mathematical operations
Python supports basic mathematical operations, such as addition (+), subtraction (-),
multiplication (*), division (/), and other more advanced operations.

2.3.2 Comparison operators


Comparison operators allow you to compare values. Common com- parison operations include
"==", "!=", "<", ">", "<=", ">=".

2.3.3 Logic operators


Logical operators ("and", "or", "not") are used to combine Boolean expressions.

2.4 Control structures


2.4.1 Conditionals (if, elif, else)
Conditional structures allow you t o execute blocks of code according to conditions. For example :

age = 18
if age < 18:
print("You are a minor.")
else:
print("You are over 18.")

2.4.2 Loops (for, while)


Loops allow you to repeat blocks of code. For example, a "for" loop lets you cycle through the
elements of a list.

numbers = [1, 2, 3, 4, 5]
for number in numbers:
print(number)

2.4.3 Break and continue


The "break" and "continue" instructions are used to control the flow of a loop. "break" stops a
loop completely, while "continue" moves on to the next iteration.

2.5 Application example: Managing food stocks in a village in


Africa
In this example, we'll use Python to solve a problem linked to food stock management in an African
village.

2.5.1 Python code


Here is the Python code to solve this problem:
Regis N'guessan 7

# Application example: Food inventory management in Africa

# Variable definitions
stock_alimentaire = 1000 # Initial quantity of food in kilograms
consumption_per_day = 20# Daily consumption in kilograms days_to_feed = 30#
Number of days to feed the community

# Calculation of the amount of food required food_necessary =


consumption_per_day * days_to_feed

# Check food availability if stock_alimentaire >=


food_necessary :
print("La␣ quantite ␣de␣ nourriture ␣ est␣ suffisante .")
print( f" Stock ␣ restant␣: ␣{ stock_alimentaire ␣-␣ nourriture_necessaire } ␣kg")
else :
print("La␣ quantite ␣de␣ nourriture ␣ est␣ insuffisante .")
print( f" Il␣ manque ␣{ nourriture_necessaire ␣-␣ stock_alimentaire } ␣kg␣de␣
nourriture .")

2.5.2 Code explanation


• We initially define the quantity of food available in the stock (stock_alimentaire), the average daily
consumption per person (consumption_per_day), and the number of food items in the stock
(stock_alimentaire).
days for which we must feed the community (days_to_feed).
• We calculate the total quantity of food required by multiplying daily consumption by the
number of days (food_necessary).
• Next, we check whether the quantity of food in stock is sufficient to feed the community for the
specified period. If the stock is sufficient, we display a message indicating that there is enough
food and show the remaining stock. If not, we indicate how many additional kilograms of food
are required.
8 CHAPTER 2. PYTHON BASICS
Chapter 3

Functions

3.1 Introduction
Functions are essential elements of Python programming. They enable you to group blocks of code
into a logical, reusable unit. In this chapter, we'll explore in detail the creation and use of functions, as
well as their role in solving African problems.

3.2 Defining functions


3.2.1 Creating functions
In Python, you can define a function using the def keyword. For example :

def greet():
print("Hello, how are you?")

3.2.2 Parameters and arguments


Functions can accept parameters, which are values you supply w h e n calling the function.
Parameters allow a function to take variable data into account. For example:

def dire_bonjour(name): print("Hello,


" + name + " " !")

3.2.3 Integrated functions


Python has many built-in functions, such as print(), len(), range() and so on. You can use them
directly without having to define them.

3.3 Using functions


3.3.1 Calling up functions
To call a function you've defined, use its name followed by parentheses containing the arguments.
For example:

greet() # Calls the greeting function


dire_bonjour("Alice") # Call the dire_bonjour function with an argument

9
10 CHAPTER 3. FUNCTIONS

3.3.2 Return values


Functions can return values using the return keyword. For example :

def addition(a, b): resultat


= a + b return resultat

3.4 Function documentation


It's a good idea to document your functions by providing explanatory comments (doc- strings) to
explain what the function does, what its parameters are, and what it returns. For example:

def calculate_surface(length, width): """


This function calculates the area of a rectangle.
:param length: The length of the rectangle.
:param width: The width of the rectangle.
:return: The area of the rectangle.
"""
return length * width

3.5 Application example: Calculating GDP per capita in Benin


In this example, we'll use Python to calculate GDP per capita in Benin using dummy data.

3.5.1 Python code


Here is the Python code that performs the calculation:

# Function to calculate GDP per capita


def calculer_pib_par_habitant(pib_total, population):
pib_par_habitant = pib_total / population
return gdp_per_capita
# Benin data
pib_benin =12209 In millions of dollars
population_benin =12209 In millions of inhabitants

# Call function to calculate GDP per capita


gdp_per_capita_benin = calculate_gdp_per_capita(gdp_benin, population_benin)
# Display result
print("GDP per capita in Benin i s ", gdp_per_inhabitant_benin, "dollars per capita.")

3.5.2 Code explanations


We have created a Python function named calculatep ibp arh abitantwhich takes the totalGDPand thepopulationenting that′
argument Then, we have used this function to calculate the GDP per capita of Benin
Benin's total GDP is 12,209 million euros.
Regis N'guessan 11

dollars, and its population is also 12,209 million (these are dummy figures for
i l l u s t r a t i v e purposes).
Finally, we displayed the result using the print() function.
This Python code can be run in a Python environment to obtain the result of the GDP per
capita calculation.
12 CHAPTER 3. FUNCTIONS
Chapter 4

Lists and Dictionaries

4.1 Introduction
Lists and dictionaries are essential data structures in Python. In this chapter, we'll explore
them in depth and learn how to use them to solve African problems.

4.2 The Lists


4.2.1 List creation
In Python, a list is an ordered collection of elements. You can create a list
by using square brackets [] and separating elements with commas. For
example:

fruits = ["apple", "banana", "orange"]

4.2.2 Element access


You can access the elements of a list using their index inside the square brackets.
Indices start at 0. For example:

first_fruit = fruits[0] % Accesses the first item in the list

4.2.3 List editing


Lists are mutable, which means you can modify their elements. For
example:

fruits[1] = "kiwi" % Replace "banana" with "kiwi

4.2.4 List operations


You can perform various operations on the lists, including :

• Add elements with append() or insert().


• Delete elements with remove() or pop().
• Concatenate lists with +.
• Find the length of a list with len().

13
14 CHAPTER 4. LISTS AND DICTIONARIES

4.2.5 For loops with lists


For loops are commonly used to cycle through the elements of a list. For
example :

for fruit in fruits:


print(fruit)

4.3 Dictionaries
4.3.1 Dictionary creation
A dictionary is a collection ofkey-valuepairs. Youcan create a dictionary by
using {} braces and specifying key-value pairs. For example:
capitals = {"France": "Paris", "United States": "Washington, D.C.", "Nigeria": "Abuja"}

4.3.2 Values access


You can access dictionary values using the corresponding key. For example:
capitale_france = capitales["France"]] % Accesses the value associated with the "France" key

4.3.3 Editing dictionaries


Dictionaries are mutable, which means you can add, update or delete key-value pairs.

capitales["Germany"] = "Berlin" % Adds a new key-value pair capitales["France"] =


"Lyon" % Updates the value associated with the "France" key
del capitales["Nigeria"] % Deletes the key-value pair associated with the "Nigeria" key

4.3.4 Operations on dictionaries


You can check whether a key exists in a dictionary with the in operator, and obtain the
list of keys or values with the keys() and values() methods.

4.4 Application example: Drug inventory management in


Senegal
Suppose you work in a rural medical clinic inSenegal. Theclinic needs
a computerized system to manage its stock of medicines.
a simple Python program to keep track of drugs in stock and order new ones when stocks are low.

4.4.1 Python code


# Initialization of the list of drugs in stock stock_medicaments = {
"Paracetamol: 100,
"Amoxicillin: 50,
"Aspirin: 75,
"Ibuprofen": 30,
}
Regis N'guessan 15

# Function to check the stock quantity of a drug def


verifier_stock(drug):
if drug in stock_medicaments:
quantity = stock_medicaments[medicament]
return f "There is {quantity} {drug} left in stock." else:
return "This drug is not in stock."
# Drug ordering function
def commander_medicaments(medicament, quantite): if
medicament in stock_medicaments:
stock_medicaments[medicament] += quantity
else:
stock_medicaments[medicament] = quantity
# Function to sell a drug
def sell_medicine(medicine, quantity):
if drug in stock_drugs and stock_drugs[drug] >= quantity: stock_drugs[drug] -= quantity
return f"{quantity} {drug}(s) sold." else:
return "Insufficient stock for this sale."
# Using the program
print(verifier_stock("Paracétamol")) # Check quantity of Paracétamol in stock
commander_medicaments("Vitamine C", 20) # Order 20 Vitamin C tablets
print(verifier_stock("Vitamin")) Check quantity of Vitamin C in stock
print(vendre_medicament("Paracétamol",10)) Sell 10 Paracétamol tablets
print(verifier_stock("Paracétamol")) # Check quantity of Paracétamol in stock

4.4.2 Code explanation


In this Python :
• We initialize a list called stock_medicaments, which stores available drugs and their
stock quantities in dictionary form.
• We define three functions: verifier_stock, commander_medicaments, and
vendre_medicam which are used to check the stock o f a drug, order drugs
and selling drugs, respectively.
• We use these functions to carry out stock management operations, such as checking
Paracetamol stock or ordering Vitamin C,
checking Vitamin C stock, selling Paracetamol and checking Paracetamol stock.
This code simulates the management of drug stocks in a medical clinic in Senegal.
It shows how lists (used in dictionary form) can be used to store and update
information on drugs in stock, and how functions can be used to perform management
operations onstock. Thistype o f approach can be useful for solving stock management
problems in many situations in Africa.
16 CHAPTER 4. LISTS AND DICTIONARIES
Chapter 5

Advanced Functions

5.1 Introduction
In this chapter, we'll explore advanced concepts related to functions in Python. You'll discover
how to create recursive functions, use lambda functions and understand the scope of variables.

5.2 Recursive functions


5.2.1 What i s a recursive function?
A recursive function is one that calls itself in its own definition.
This technique is useful for solving problems that can be broken down into similar sub-
problems.

5.2.2 Structure of a recursive function


A recursive function generally consists of two parts: the base case and the recursion. The
base case is the condition that determines when recursion should stop, thus avoiding an
infinite loop.

5.2.3 Example: Factorial calculation


A classic example of a recursive function is the calculation of the factorial o f a number.
The basic
case is when the number is equal to 0, then the result is 1. Otherwise,
the factorial is calculated by multiplying the number by the factorial of the previous
number.
def factoriel( n):
if n == 0:
return 1
else :
return n * factorial(n -1)

5.3 Lambda functions


5.3.1 What i s a lambda function?
A lambda function, also known as an anonymous function , is a small, unnamed
function often used to create simple, one-off functions.

17
18 CHAPTER 5. ADVANCED FUNCTIONS

5.3.2 Syntax of a lambda function


A lambda function is defined using the lambda keyword, followed by the parameters
and the expression to beevaluated. Forexample:

carre = lambda x: x **2

5.3.3 Using lambda functions


Lambda functions are often used in combination with functions such as map(), filter(),
and reduce(), to apply operations to collections of data.

5.4 Scope of Variables


5.4.1 Local and global variables
In Python, there are two types of variables: local variables, defined i n s i d e a
function and restricted to that function, and global variables, defined outside a function and
restricted to that function.
outside all functions and accessible anywhere in the code.

5.4.2 Global instruction


If you need to modify a global variable within a function, you can use the global statement to
indicate that you are referring to a global variable.

5.5 Application example: Solving an educational problem in


Burkina Faso with Python

5.6 Problem: Calculating the number of registered students


5.6.1 Context
In Burkina F a s o , tracking the number o f students enrolled i n schools is essential to
guarantee access t o quality education, but calculating the
total number o f students across the country can be complex due to the diversity of
educational levels.

5.6.2 Objective
Create a Python program that calculates the total number o f students enrolled
throughout Burkina Faso, based on data from each region and its primary, secondary and
higher education schools.

5.6.3 Python solution


Recursive functions for calculation
Recursive functions are used to calculate the number o f students at each teachinglevel.
Eachfunction takes into account the lower levels and stops when the
base case is reached.
Regis N'guessan 19

1 def nombre_etudiants_primaire (
n): if n == 0:
return 0
2
# Basic case: none cole primary
else :
3
4
5 return 500 + number_of_primary_students ( n - 1)

7 def nombre_etudiants_secondaire ( n):


6

if n == 0:
return 0
8
# Basic case: none cole secondary
else :
9
10
11 return 300 + number_of_secondary_students ( n - 1)

13 def nombre_etudiants_superieur ( n):


12

if n == 0:
return 0
14
# Basic case: none coles u p r i e
else :
15
16 ure
17 return 100 + upper_student_number ( n - 1)

Using Lambda functions


We define a list of regions with the number o f primary, secondary and higher education
schools in eachregion. Next,we use lambda functions to apply our recursive
functions to the data for each region.
1 regions = [
{"name": "Ouagadougou", "primary": 20 , "secondary": 15 ,
"higher": 8},
2

{"name": "Bobo - Dioulasso", "primary": 15 , "secondary": 10 ,


"higher": 5},
3

% Add other ␣ r g i o n s ␣ with ␣ their ␣ d o n n e s


]
4
5

calculate_total_region ␣=␣ lambda ␣ region : ␣(


6

␣␣␣␣ primary_student_number ( region ["primary"]) ␣+


7

␣␣␣␣ number_of_secondary_students ( region ["secondary"]) ␣+


8

␣␣␣␣ superior_student_number ( region ["superior"])


9

)
10
11

Results aggregation
We use the map() function to apply our lambda function to each region and aggregate the
results to obtain the total number o f students in Burkina Faso.
1 total_national = sum ( map ( calculer_total_region , regions ))
2 print("Number ␣ t o t a l ␣ d ' tudiants ␣au␣ Burkina ␣ Faso ␣:", total_national )
20 CHAPTER 5. ADVANCED FUNCTIONS
Chapter 6

Modules and Packages

6.1 Introduction
In this chapter, we'll discover how to organize our code u s i n g modules and packages in.
Modules are Python files c o n t a i n i n g functions and
variables that you can reuse, while packages are directories containing several modules.

6.2 Modules
6.2.1 Importing modules
To use a module in your code, you need to import it using t h e import instruction.
For example:
import math % Imports the math module

6.2.2 Using module functions and variables


Once a module has been imported, you can use its functions and variables by preceding
them with the name of themodule. Forexample:
result = math.sqrt(25) % Uses the sqrt() function in the math module

6.2.3 Creating modules


You can also create your own modules by creating Python files with functions and variables that
you want to reuse in other parts of your code.

6.3 Packages
6.3.1 Package creation
A package is a directory containing several Python modules, as well a s a special file called
init.py. Thepresence of this file tells Python that the directory is apackage.
Forexample:
my_package/
init .py module1.py
module2.py

21
22 CHAPTER 6. MODULES AND PACKAGES

6.3.2 Importing modules from a package


To import modules f r o m a package, you use the import statement with the package
structure and module name, e.g. :

import my_package.module1

6.3.3 Using module functions and variables in a package


Once you've imported a module from a package, you can use its functions and variables in the
same way as for simple modules.

6.4 Importing with aliases


You can also import modules or functions with aliases to simplify their use. For example :

import my_module as mm

6.5 Application example: Agricultural Production


Management in Côte d'Ivoire
In this document, we'll explore an example of a Python application for managing agricultural
production in Côte d'Ivoire, using modules and packages.

6.5.1 Python code


Here is the Python code that manages t h e collection and analysis of agricultural production
data in Côte d'Ivoire :
1 # cotedivoire_agriculture / production . py

def collect_data ():


2

""" Simulates the collection of data on agricultural production .""" data =


3

{
4

cocoa': 50000 ,
5

'coffee': 30000
6

,
7
Oil ␣de␣ palm ': 75000 ,
8
}
9

return data
10
11
# cotedivoire_agriculture / analysis . py
12
13
14 def calculate_total_production ( data ):
""" Calculates total agricultural production in the Ivory Coast ."""
15
production_totale = sum ( data . values ())
16
return production_total
17
18
19 def product_the_most_product ( data ):
20 """ Finds the most produced agricultural product."""
21 product = max ( data , key = data . get)
return product
22
Regis N'guessan 23

6.5.2 Using the Package


We use the package and modules in our main code to p e r f o r m operations on
production data:
1 # main . py

# Package import
2

import cotedivoire_agriculture . production as production import


3

cotedivoire_agriculture . analyse as analyse


4
5

# Collect production data farm_data = production .


6

collect_data ()
7
8
# Calculation of total production
9

total_production = analysis . calculate_total_production ( farm_data )


10
11
# Find the best product
12

product_plus_product = analysis . product_plus_product ( farm_data )


13
14
# Results display
15

print("Donnees ␣de␣ production ␣ agricole ␣en␣ Cote ␣ d'Ivoire ␣:")


16
print( donnees_agricoles )
17
print(" Production ␣ agricole ␣ totale ␣en␣ Cote ␣ d'Ivoire ␣:", production_totale )
18
print(" Produit␣le␣ plus␣ produit␣en␣ Cote ␣ d'Ivoire ␣:", produit_plus_produit )
19
20

6.5.3 Explanation
In this example, we've created a simple system for managing agricultural production in Côte
d'Ivoire using Python. Here's how it works:

Code organization
We've structured our code using modules and a Python package called
cotedivoire_agriculture. Here's how the files are organized:
• cotedivoire_agriculture/ :The package directory containing our modules.
– init . py : A special file indicating that this directory is a package.
– production.py : The data collection module.
– analyse.py : The data analysis m o d u l e .

Production.py module
In this module, we simulate the collection of data on agricultural production in Côte d'Ivoire,
and store this data in a dictionary with fictitious values.
for three agricultural products: cocoa, coffee and palm oil. The collect_data() function
returns this dictionary.

Module analyse.py
This module contains two functions for analyzing production data:
• calculate_total_production(data) : This function takes t h e production data
dictionary and calculates total production by summing the values.
• product_the_most_produced(data) : This function finds t h e most produced
agricultural product in Côte d'Ivoire by searching for the key associated with the
maximum value in the dictionary.
24 CHAPTER 6. MODULES AND PACKAGES

Using the Package and Modules


In our main main.py file, we use the package and modules to perform operations on
production data:

• We import the cotedivoire_agriculture package and its corresponding modules.


• We collect production data using the collect_donnees() function.
• We calculate total production using the calculate_total_production() function.
• We find the most produced product using the product_the_most_produced() function.
• Finally, we display the results o n screen.
This model of code organization using modules and packages facilitates code
management and reuse, which is essential for solving complex programming problems.
Chapter 7

File and Data Handling

7.1 Introduction
In this chapter, we will explore file and data manipulation in
You will learn how to read, write and manipulate files, as well as work with structured
data, such as CSV files, to solve problems.
linked to th e African economy.

7.2 Reading files


7.2.1 Opening files
You can open a file in Python using the open() function. It's important
to specify t h e opening mode, such as "read" ('r'), "write" ('w'), or "add" ('a').

file = open('my_file.txt', 'r') # Opens file in read mode

7.2.2 Content playback


You can read the contents o f a file line by line or in its entirety. line =

file.readline() # Reads a line


content = file.read() # Reads all content

7.2.3 Closing files


It's important to close a file after reading or writing it, using the close() method.

7.3 Writing to Files


7.3.1 Writing files
To write to a file, open it in write ('w') or add ('a') mode and use the write() method to
write data to the file.

25
26 CHAPTER 7. FILE AND DATA MANIPULATION

file = open('new_file.txt', 'w') # Opens file in write mode


file.write("Hello, world!")
file.close() # Closes the file

7.4 Working with CSV files


7.4.1 The CSV module
Python offers a csv module for working with CSV files. You can import it with import csv.

7.4.2 Reading CSV files


You can read CSV files using the csv.reader() function. import csv

with open('données.csv', 'r') as fichier_csv: reader


= csv.reader(fichier_csv)
for ligne in lecteur:
print(ligne)

7.4.3 Writing to CSV files


To write data to a CSV file, you can use the csv.writer() function. import csv

data = [['name', 'age'], ['Alice', 25], ['Bob', 30]]

with open('nouvelles_donnees.csv', 'w', newline='') as fichier_csv:


writer = csv.writer(fichier_csv)
writer.writerows(data)

Application example: Analysis of cocoa production in Côte


d'Ivoire
Python code

1 import csv

3 # Step 0: Creation of the CSV file (optional, if the file does not yet exist)
2

data = [
4
5 ["Annee", "Production ␣( en␣ tonnes )"],
6 [2010 , 1500000] ,
7 [2011 , 1550000] ,
8 [2012 , 1600000] ,
9 [2013 , 1620000] ,
10 [2014 , 1650000 ]
11 ]
12
13 no m_file = " production_cacao_ci . csv " th
14
15 wi open ( file_name , 'w', newline ='') as fichier_csv :
Regis N'guessan 27

writer = csv . writer( fichier_csv ) writer .


writerows ( data )
16
17

19 # Step 1: Open the CSV file in read mode file_name =


18

20 "production_cacao_ci . csv".

22 with open ( filename , 'r') as fichier_csv :


21

23 reader = csv . reader( fichier_csv )

# Step 2: Reading headers ( first line ) headers = next(


24
reader)
25

print("Les␣en - tetes ␣du␣ fichier ␣ sont␣:", en_tetes )


26
27
28 # Step 3: Initialize lists to store data years = []
productions = []
29
30
31 # Step 4: Read data from file for ligne in
32 lecteur:
33 year = int( line [0]) production
34 = int( line [1])
35
36 years . append ( year )
productions . append ( production
)
37
38

# Step 5: Calculate total production


39

production_totale = sum ( productions )


40

print("La␣ production ␣ totale ␣de␣ cacao ␣en␣ Cote ␣ d Ivoire ␣ est␣de",


41

production_totale , " tonnes .")


42
43
# Step 6: Calculate average production average_production = sum (
productions ) / len ( productions )
44
print("La␣ moyenne ␣de␣ production ␣de␣ cacao ␣en␣ Cote ␣ d Ivoire ␣ est␣de",
45
46 moyenne_production , " tonnes ␣ par␣an.")
47
# Step 7: Year of maximum production
48 annee_max = annees [ productions . index ( max ( productions ))]
49 print("L' annee ␣de␣ production ␣ maximale ␣ etait␣en", annee_max )
50
51

Code explanation
1. We import the csv module to work with CSV files.
2. We open the CSV file in read mode ('r') using a with clause to ensure that the file is
properly closed after use.

3. We use csv.reader() to read the lines in the CSV file.


4. We read the headers (first line) of the file to understand what data we have.
5. We initialize lists (years and productions) to store data from the file.
6. We go through the file line by line and extract the years and productions, which we
store in the corresponding lists.
7. We calculate total production and average production using data from the production
list.
28 CHAPTER 7. FILE AND DATA MANIPULATION

8. We determine the year of maximum production by finding the index of maximum


production in the productions list and using this index to extract the corresponding year
from the annees list.
Chapter 8

Graphics and Data Visualization

8.1 Introduction
In this chapter, we'll explore how to create graphs and visualize data.
data in. Data visualization is essential to present information in a clear and
convincingway. Wewill mainly use the library
Matplotlib, one of the most popular libraries for data visualization in Python.

8.2 Introduction to Matplotlib


8.2.1 Installing Matplotlib
If you haven't already installed Matplotlib, you can do so using pip, Python's
package manager.

pip install matplotlib

8.2.2 Importing Matplotlib


To use Matplotlib, import it into your Python script. import

matplotlib.pyplot as plt

8.3 Graphics creation


8.3.1 Line graph
A line graph is used to represent linear relationships between two variables: for example,
GDP as a function of time.

\begin{figure}[h]
\centering
\includegraphics[width=0.8\textwidth]{graphique_lineaire.png}
\caption{Changes in GDP over time}
\label{fig:graphic-linear}
\end{figure}

29
30 CHAPTER 8. GRAPHICS AND DATA VISUALIZATION

8.3.2 Bar graph


A bar chart is used to compare different categories, for example,
comparing the GDP of several countries.

8.4 Customize graphics


8.4.1 Colors, styles and captions
You can customize color, line style and add captions to your graphics to make them
more informative.

8.4.2 Sub-graphics
Matplotlib lets you create sub-graphs to display multiple graphics in a single figure.

8.4.3 Exporting graphics


You can export your graphics in image format (PNG, JPG,etc.) toshare them or
integrate them into reports.

8.5 Data visualization with Seaborn


Seaborn is another data visualization library that integrates well with Matplotlib and
simplifies the creation of aesthetic graphs. You can install it with
pip.

8.6 Application example: Visualizing unemployment trends in


Cameroon
We'll be doing data visualization using Python to understand trends i n the unemployment
rate in Cameroon overtime. Well use Matplotlib to create
a line graph showing the evolution of the unemployment rate over t h e last few years.

8.6.1 Step 1: Data collection


The first step is to collect data on the unemployment rate in Cameroon over time .
from reliablesources. Let's assumewe've collected this data and stored it in a CSV file named
"chomagecameroun.csv". The CSV file should contain two
columns: "Annee" and "Taux de Chomage".

8.6.2 Step 2: Data preparation


We're going to use the Pandas library to read and manipulate data from the CSV file.
Make sure you install Pandas with pip install pandas.
1 import pandas as pd

3 # Read data from CSV file data = pd. read_csv ('


2

4 chomage_cameroun . csv ')


5
Regis N'guessan 31

6 # Display the first lines of the Data Frame print( data .


7 head ())

8.6.3 Step 3: Creating the graphic


Now that we have our data, we can create a graph to visualize trends in the unemployment
rate in Cameroon.
1 import matplotlib . pyplot as plt

# Extraction of year and c h m a g e rate d o n n e s annees = data [' Annee


2

']
3
4
5 taux_chomage = data [' Taux ␣de␣ Chomage ']

# C r a t i o n du graphique
6

plt. figure ( figsize =(10 , 6)) # D f i n i t chart size


7

plt. plot( years , unemployment_rate , m a r k e r = 'o ', linestyle = ' - ') #Cre
8

a l l i n a r y graph with points


9

10 plt. xlabel(' Year ')


11 plt. ylabel(' Rate ␣de␣ Unemployment ␣ (% ) ')
12 plt. title (' Rate ␣of␣ Unemployment ␣in␣ Cameroon ␣ (2010 -2020) ')

14 # Add grids plt.


13

15 grid ( True )
# Display graph plt. show ()
16
17
18

8.6.4 Code explanation


• We use Pandas to read the data from the CSV file and store the "Year" and
"Unemployment Rate" columns in separate variables.
• Next, we use Matplotlib to create a graphlinear. Wespecify the
years on the x-axis and the unemployment rates on they-axis. Themarker='o'
parameter adds points to the data values to make them more visible,
and linestyle='-' specifies a continuous line.
• We add axis labels, a title and activate the grids to make the graph easier to read.
• Finally, we use plt.show() to display the graph.

This code will generate a line graph showing the evolution of the unemployment rate in
Cameroon from 2010 to2020. Youcan then analyze trends and variations in the
unemployment rate over time to better understand the country's economic situation.
32 CHAPTER 8. GRAPHICS AND DATA VISUALIZATION
Chapter 9

Databases

9.1 Introduction
In this chapter, we will explore how to interact with databases using. Databases are essential
tools for storing, organizing and retrieving data, making them indispensable for data
management.
in many fields, including the African economy.

9.2 Relational Databases


9.2.1 What i s a relational database?
A relational database is a database management system that uses tables to storedata. Tables are
linked to each other by
relationships.

9.2.2 SQL (Structured Query Language)


SQL is the standard language for interacting with relational databases. You can use Python
to execute SQL queries and manipulate d a t a b a s e data.

9.3 Using SQLite in Python


SQLite is a lightweight, self-contained relational database that can be used to
in Python without the need t o install external database management software.

9.3.1 SQLite installation


SQLite is generally included in Python installations by default, so there's no need to
install it separately.

9.3.2 Creating a database


You can create a new SQLite database using Python's SQLite3 library.

import sqlite3

connection = sqlite3.connect('my_database.db')

33
34 CHAPTER 9. DATABASES

9.3.3 Table creation


Once you've established a d a t a b a s e connection, you can create tables to store data
using SQL.

9.3.4 Inserting, updating and deleting data


You can insert, update and delete data in the d a t a b a s e using SQL.

9.3.5 Data query


Use SQL to query the database and extract data.

cursor = connection.cursor()
cursor.execute("SELECT * FROM my_table WHERE column = 'value'") results =
cursor.fetchall()

9.3.6 Closing the database


Don't forget to close the database connection when you've finished using it.

connection.close()

9.4 Using SQLAlchemy


SQLAlchemy is a popular Python library that f a c i l i t a t e s interaction w i t h relational
databases by providing a high-level interface for creating, querying and managing
databases.

9.4.1 Installing SQLAlchemy


You can install SQLAlchemy using pip. pip install

sqlalchemy

9.4.2 Using SQLAlchemy


Use SQLAlchemy to define data models, interact with the d a t a b a s e and perform operations in a
more abstract way.

9.5 Example: Agricultural Data Management in Ghana with a


Database
In this example, we'll create a SQLite database in Python to track information on the
agricultural sector in Ghana , including data on crops, yields,
farmers and prices of agricultural products.
Regis N'guessan 35

9.5.1 Python code


Here's the Python code used to create the database and perform basic operations.
# Importing the SQLite 3 b i b l i o t h q u e import
sqlite 3
1
2

# Connection = sqlite 3 . connect(' ghana_agriculture . db ')


3
4

# C r a t i o n de la table " cultures "


5

curseur = connexion . cursor ()


6
curseur. execute (''''
7
CREATE TABLE IF NOT EXISTS cultures (
8
id INTEGER PRIMARY KEY AUTOINCREMENT ,
9
name TEXT , area
10
REAL , yield REAL
11
12 )
''')
13
14
15 # Insertion of d o n n e s in the "cultures" table cursor.
16 execute ('''
17 INSERT INTO crops ( name , area , yield) VALUES
18 (' M a s ', 5000 , 2.5) ,
19 (' Rice ', 3500 , 3.0) ,
20 (' Cacao ', 2000 , 1.8)
''')
21
22
23 # D o n n e s questioning
24 cursor. execute (' SELECT ␣* ␣ FROM ␣ cultures ') data
25 = cursor . fetchall ()
26
27 print("D o n n e s ␣ sur␣ les␣ cultures ␣au␣ Ghana ␣:")
for ligne in données :
print( f" ID␣: ␣{ line [0]}, ␣ Name ␣: ␣{ line [1]}, ␣ Area ␣: ␣{ line [2]} ␣ hectares , ␣
28

Yield␣: ␣{ line [3]} ␣ tons per␣ hectare ")


29
30

# Closing the database connection . close


31

()
32
33

34
35
36

9.5.2 Code explanation


Here is a detailed explanation of the Python code:

• We import the SQLite3 library to work with SQLite in Python.


• We create a database named "ghana_agriculture.db" and establish a connection to
thisdatabase. Ifthe database d o e s not exist, it will be
created.
• We define a "crops" table to store information about crops, including crop name, cultivated
area and yields. We use
SQL to create this table.
• We insert some initial data in the "crops" table to represent crops in Ghana.
36 CHAPTER 9. DATABASES

• We perform an SQL query to extract and display the crop data.


• Finally, we close the database connection when we've finished using it.
Chapter 10

Object-oriented programming

10.1 Introduction
In this chapter, we'll dive into object-oriented programming (OOP) in Python.OOP is a
programming paradigm that relies on the creation o f objects, instances of classes, to organize
and structure your code. OOP is largely
used to solve complex problems and is a fundamental concept in software development.

10.2 Classes and Objects


10.2.1 What i s a class?
A class is a model or blueprint for creatingobjects. Itdefines the attributes
(variables) and methods (functions) that the objects in this class will have.

10.2.2 Object creation


An object is an instance of a specific class. Youcreate objects using the class
name followed by parentheses.

class Car:
def init (self, marque, modele):
self.marque = marque self.modele
= modele

my_car = Car("Toyota", "Camry")

10.3 Attributes and Methods


10.3.1 Attributes
Attributes are variables that define the characteristics of an object.
Att
ributes can be defined in the class constructor ( init ) and can be accessed via the
object.

class Car:
def init (self, marque, modele):
self.marque = marque self.modele
= modele

37
38 CHAPTER 10. OBJECT-ORIENTED PROGRAMMING

ma_voiture = Voiture("Toyota", "Camry")


print(ma_voiture.marque) # Access t o 'marque' attribute

10.3.2 Methods
Methods are functions that define an object' s behavior.
Methods are defined inside the class and can be called via the object.

class Car:
def init (self, marque, modele):
self.marque = marque
self.modele = modele

def start(self):
print("The car starts.")

ma_car = Car("Toyota", "Camry") ma_car.start() # Call 'start'


method

10.4 Heritage
Inheritance is a key OOP concept that allows new classes to be created using existing classes as
a template. New classes inherit the attributes and
methods of the parent class.

class Vehicule:
def init (self, marque, modele):
self.marque = marque
self.modele = modele

def start(self):
print("The vehicle starts.")
class Car(Vehicle):
def init (self, brand, model, color): super(). init
(brand, model) self.color = color

my_car = Car("Toyota", "Camry", "blue") my_car.start()

10.5 Encapsulation
Encapsulation is the principle of hiding the implementation details o f a class and
a l l o w i n g access only to the necessaryparts. InPython, encapsulation is
often achieved by using private attributes and access m e t h o d s (getters and setters).
Regis N'guessan 39

10.6 Example: OOP modeling of a banking system in Congo


We're going to model a simple Congolese banking system using OOP in Python.
This will help us understand how OOP can be used to structure a complex system.

10.6.1 Python code


Here's the Python code for the bank account management example:

1 class Customer:
def init ( self , name , first name , address , phone_number ):
self. name = name
2

self. firstname = firstname


3

self. address = address


4

self. phone_number = phone_number


5
self. accounts = []
6
7
def open_account ( self , initial_balance):
8
if initial_balance >= 0:
9
10 new_account = Account ( initial_balance)
11 self. accounts . append ( new_account )
12 print( f" Account ␣ c r ␣ pour␣{ self. prenom } ␣{ self. nom
13 }") else :
14 print("Le␣ solde ␣ initial␣ doit␣ tre ␣ positif.")
15
16 # ... ( Other m t h o d e s of the Customer class) class
17
18 Account :
19 account_number = 0 # A counter to assign account numbers
20 unique
21 def init ( self , initial_balance):
22 Account . account_number += 1
23 self. numero = Account . numero_compte
24 self. solde = solde_initial
25
26 # ... ( Other m t h o d s of the Account class ) #
27
28 Example of use
29 client1 = Client("Mukendi", "Jean", "Kinshasa", "123456789")
customer1 . open_account
(50000 ) customer1 .
30

open_account (10000 )
31

customer1 .
32

display_accounts ()
33
34
# ... ( S u p p l e m e n t a l a c c o u n t s )
35

10.6.2 Code explanation


Classes and Objects

We have created two main classes: Customer andAccount.


TheCustomer class represents a bank customer
with personal information and a list of accounts. The Account class represents
a bank account with a unique account number and balance.
40 CHAPTER 10. OBJECT-ORIENTED PROGRAMMING

Attributes and Methods


Attributes are variables that define an object' s
characteristics;
m
ethods are functions that define an object's behavior.

Heritage
Inheritance is used to create a derived class (Car) f r o m a parent class (Vehicle).
The derived class inherits the attributes and methods of the parent
class.

Encapsulation
Encapsulation is an OOP principle which involves hiding the implementation details of aclass.
Weve used methods to access private attributes, for example,
client1.ouvrir_compte(50000).
Chapter 11

Python projects for Africa

11.1 Project 1: Calculating Economic Growth in Nigeria


Problem :Nigeria would like to track its economic growth. You have
GDP data for severalyears. Calculatethe average annual economic growth rate over this
period.

11.2 Project 2: Population monitoring in Ethiopia


Problem : Ethiopia wishes to track its population growth. You have
population data for severalyears. Calculatethe average annual population growth rate
over this period.

11.3 Project 3: Currency converter for Kenya


Problem: Create a command line currency converter for Kenya.
Users must be able to enter an amount in local currency (Kenyan shillings).
The program should return the equivalent amount in the chosen currency.

11.4 Project 4: Peanut crop prediction in Senegal


Problem: Senegal wants to predict its peanut h a r v e s t for t h e coming year. Use
historical harvest data and create a simple prediction model using linear regression.

11.5 Project 5: Exchange Rate Calculator in South Africa


Problem: Create an exchange rate calculator for South Africa. Users must be
able to enter an amount in South African rand (ZAR) and choose another currency.
The program must return the equivalent amount in the chosen currency, using current
exchange rates.
These mini-projects are designed to illustrate how Python can be used to solve real-life
problems in Africa, from economic calculations to population tracking and currency
conversion.

41
42 CHAPTER 11. PYTHON PROJECTS FOR AFRICA

by adding extra features or adapting them to specific problems in each country.


Chapter 12

From Solution Approaches to


Python Projects for Africa

In this chapter, we'll look at solutions for five Python projects designed to solve specific
problems inAfrica. Thesolutions provided a r e
examples of Python code that illustrate how to approach eachproblem. Youcan
use them as a starting point for developing these projects further, or for solving similar
problems.

12.1 Solution to Project 1: Calculating Economic Growth in


Nigeria
Solution: To calculate the economic growth rate in Nigeria, you can use the following
formula:
(FinalGDP - InitialGDP)
GrowthRate = × 100
PIBInitial
You can implement this in Python by asking the user to enter the initial and final GDP
values, then calculating the growth rate.

# Solution to Project 1: Calculating Economic Growth in Nigeria # Input of

initial and final GDP


initial_gdp = float(input("Enter initial GDP in billions of dollars: "))
final_gdp = float(input("Enter final GDP in billions of dollars: "))
# Growth rate calculation
growth_rate = ((final_gdp - initial_gdp) / initial_gdp) * 100
# Display result
print(f "The average annual economic growth rate is {growth_rate:.2f}%")

12.2 Solution to Project 2: Population monitoring in Ethiopia


Solution: To track population growth in Ethiopia, you can use the following
formula:
(FinalPopulation - InitialPopulation)
DemographicGrowthRate = × 100
InitialPopulation

43
CHAPTER 12. SOLUTION APPROACHES TO PYTHON PROJECTS FOR
44 AFRICA

You can implement this in Python by asking the user to enter the
initial and final population values, then calculating the population growth rate.

# Solution to Project 2: Population Monitoring in Ethiopia #

Initial and final population data capture


initial_population = float(input("Enter initial population: "))
final_population = float(input("Enter final population: "))
# Calculating the population growth rate
population_growth_rate = ((final_population - initial_population) / initial_population) * 100
# Display result
print(f "The average annual population growth rate is {population_growth_rate:.2f}%")

12.3 Solution to Project 3: Currency converter for Kenya


Solution: You can create a currency converter in Python using predefined exchange
rates. Ask the user to enter an amount in Kenyan shillings, then choose a
destination currency. Use an exchange rate dictionary to perform the
conversion.

# Solution to Project 3: Currency Converter for Kenya

# Definition of exchange rates (in relation to the Kenyan shilling)


exchange_rate = {
"USD":.009, US dollar exchange rate "EUR":.007,
Euro exchange rate
"GBP": 0. 006# Pound sterling exchange rate
}
# Enter amount in Kenyan shillings
amount_in_shillings = float(input("Enter the amount in Kenyan shillings: "))
# Enter destination currency
destination_currency = input("Choose a destination currency (USD, EUR, GBP): ")
# Amount conversion
converted_amount = shilling_amount * exchange_rate [destination_currency]
# Display result
print(f "{amount_in_shillings} KES equals {amount_converted} {currency_destination}")

12.4 Solution to Project 4: Predicting the Peanut Harvest in


Senegal
Solution: You can use the scikit-learn library in Python to create a regression modellinear.
Use historical peanut harvest data as a training dataset and train the model to
predict future harvest as a function of variables such as rainfall, temperature, etc.
Regis N'guessan 45

# Solution to Project 4: Predicting the Peanut Harvest in Senegal #

Importing the necessary libraries


import numpy as np
from sklearn.linear_model import LinearRegression

# Historical peanut harvest data (fictitious examples) years =


np.array([2010, 2011, 2012, 2013, 2014, 2015])
recolte = np.array([5000, 5200, 4900, 5300, 5100, 5400]) # In tons

# Create linear regression model modele =


LinearRegression()

# Model training model.fit(years.reshape(-


1, 1), harvest)

# Harvest prediction for t h e coming year


annee_future = 2023
recolte_future = modele.predict(np.array([[annee_future]]))
# Display result
print(f "Prediction of peanut harvest in {future_year}: {future_harvest[0]:.2f} tons"

12.5 Solution to Project 5: South African E x c h a n g e Rate


Calculator
Solution: You can create an exchange rate calculator in Python using a rate dictionary
fromexchange. Askthe user to enter an amount in South African
rand (ZAR), then choose another currency. Use the dictionary to
perform the conversion.
# Solution to Project 5: Exchange Rate Calculator in South Africa

# Definition of exchange rates (in relation to the South African rand, ZAR)
exchange_rate = {
"USD":.069, US dollar exchange rate "EUR":.059,
Euro exchange rate
"GBP": 0. 051# Pound sterling exchange rate
}
# Enter amount in South African rand (ZAR)
amount_in_zar = float(input("Enter the amount in South African rand (ZAR): "))
# Enter destination currency
destination_currency = input("Choose a destination currency (USD, EUR, GBP): ")
# Amount conversion
converted_amount = zar_amount * exchange_rate [destination_currency]
# Display result
print(f "{amount_in_zar} ZAR equals {amount_converted} {currency_destination}")
These solutions illustrate how to solve project-specific problems using. Youcan
customize, enhance or extend them by
CHAPTER 12. SOLUTION APPROACHES TO PYTHON PROJECTS FOR
46 AFRICA

depending on your needs or the specific requirements of each problem.

12.6 Epilogue: Python, the Endless Adventure


Congratulations, dear reader, you've now read an entire book on programming in Python, a powerful
and versatilelanguage. Beforeturning the last page, let me take one last
look at what you've accomplished.

12.6.1 Python, a Faithful Friend


Python isn't just a programming language, it's your faithful friend in
solvingproblems. W h e t h e r it's calculating the number o f students in
Burkina Faso or predicting agricultural yields in Africa, Python is always there to help.
give you a hand.

12.6.2 Les Joies des Boucles


Have you ever felt the ultimate satisfaction when your "for" loop has worked perfectly
Orwhen your "while" loop has reached the base case of a recursive function?
Loops in Python are like a rollercoaster of programming, and you are the master
of the track.

12.6.3 Riddles in the Reach


The scope of variables can sometimes seem like a mystery, but you've done it!
Local and global variables no longer hold any surprises for you.

12.6.4 Limitless Creativity


Python is a language that encouragescreativity. Youcan c r e a t e games, web
applications, robots, or even solve global problems. Imagination
is your only limit, and Python is your magic wand.

12.6.5 The Bright Future


So, what does the future hold for an accomplished Pythonist like you Perhapsyou'll contribute
to open s o u r c e projects, teach programming to the next generation, or solve real-world
problems using your Python skills. Quoi
whatever you do, never forget that Python is there to support you.

12.6.6 This Book is Free and Open Source!


I'd like to emphasize that this book is totally free and open source. It's available to
anyone who wants to learn Python, whether for their own pleasure or for the pleasure of
others.
You can share it, modify it and use it
as you see fit.

12.6.7 Your Contributions Are Welcome!


This book is a project in constantevolution. Advice, suggestions and improvements
are welcome and will be included in future editions. Ifyou have
ideas for improving the content, additional examples to share, or corrections to make,
p l e a s e d o n 't hesitate to contribute.
Regis N'guessan 47

12.6.8 Staying Connected

Regis N'guessan,
PhD student in Data Science, AIMS-QLA(African Institute for Mathematical
Sciences-Quantum Leap Africa)

I also invite you to follow me on my various social networks to stay in touch . Youcan
contact me, ask me questions or simply discuss your own experiences in programming.
Your successes and challenges are welcome:
- @Mail
- LinkedIn
- YouTube

I'd love t o hear about your projects, your Python successes, a n d all the adventures
that await you in the world of programming.
So take a deep breath, smile, and keep coding. Python will be with you every step of the
way, guiding you to new heights o f creativity and innovation.
Happy programming, Pythonist, and may your code always be clean and your errors easy to
debug!

You might also like