Python Coding by Solving African Problem Regis Nguessan
Python Coding by Solving African Problem Regis Nguessan
Python programming
by solving African problems
Regis N'guessan
@Regis
LinkedIn
YouTube
2
Python Programming for African Problem Solving
Regis N'guessan
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
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
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
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.
• 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.
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
• 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.
Installation
Follow the on-screen instructions to complete the installation.
3
4 CHAPTER 1. INSTALLING PYTHON
Installation
Follow the on-screen instructions to complete the installation.
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.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
age = 18
if age < 18:
print("You are a minor.")
else:
print("You are over 18.")
numbers = [1, 2, 3, 4, 5]
for number in numbers:
print(number)
# 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
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.
def greet():
print("Hello, how are you?")
9
10 CHAPTER 3. FUNCTIONS
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
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.
13
14 CHAPTER 4. LISTS AND DICTIONARIES
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"}
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.
17
18 CHAPTER 5. ADVANCED FUNCTIONS
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.
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)
if n == 0:
return 0
8
# Basic case: none cole secondary
else :
9
10
11 return 300 + number_of_secondary_students ( n - 1)
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)
)
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
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.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
import my_package.module1
import my_module as mm
{
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
# Package import
2
collect_data ()
7
8
# Calculation of total production
9
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
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.
25
26 CHAPTER 7. FILE AND DATA MANIPULATION
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
20 "production_cacao_ci . csv".
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.
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.
matplotlib.pyplot as plt
\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.4.2 Sub-graphics
Matplotlib lets you create sub-graphs to display multiple graphics in a single figure.
']
3
4
5 taux_chomage = data [' Taux ␣de␣ Chomage ']
# C r a t i o n du graphique
6
plt. plot( years , unemployment_rate , m a r k e r = 'o ', linestyle = ' - ') #Cre
8
15 grid ( True )
# Display graph plt. show ()
16
17
18
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.
import sqlite3
connection = sqlite3.connect('my_database.db')
33
34 CHAPTER 9. DATABASES
cursor = connection.cursor()
cursor.execute("SELECT * FROM my_table WHERE column = 'value'") results =
cursor.fetchall()
connection.close()
sqlalchemy
()
32
33
34
35
36
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.
class Car:
def init (self, marque, modele):
self.marque = marque self.modele
= modele
class Car:
def init (self, marque, modele):
self.marque = marque self.modele
= modele
37
38 CHAPTER 10. OBJECT-ORIENTED PROGRAMMING
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.")
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
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
1 class Customer:
def init ( self , name , first name , address , phone_number ):
self. name = name
2
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
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
41
42 CHAPTER 11. 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.
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.
# 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
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!