Python Programming Fundamentals
Python Programming Fundamentals
GENPP501
SOFTWARE
DEVELOPMENT
Python
Programming
Fundamentals
TRAINEE'S
TRAINEE’S
TRAINEE'S MANUAL
MANUAL
MANUAL
October, 2024
PYTHON PROGRAMMING FUNDAMENTALS
2024
AUTHOR’S NOTE PAGE (COPYRIGHT)
The competent development body of this manual is Rwanda TVET Board ©, reproduce with
permission.
● This work has been produced initially with the Rwanda TVET Board with the support
from KOICA through TQUM Project
● This work has copyright, but permission is given to all the Administrative and
Academic Staff of the RTB and TVET Schools to make copies by photocopying or
other duplicating processes for use at their own workplaces.
● This permission does not extend to making of copies for use outside the immediate
environment for which they are made, nor making copies for hire or resale to third
parties.
● The views expressed in this version of the work do not necessarily represent the
views of RTB. The competent body does not give warranty nor accept any liability
● RTB owns the copyright to the trainee and trainer’s manuals. Training providers may
reproduce these training manuals in part or in full for training purposes only.
Acknowledgment of RTB copyright must be included on any reproductions. Any
other use of the manuals must be referred to the RTB.
iii | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
ACKNOWLEDGEMENTS
The publisher would like to thank the following for their assistance in the elaboration of this
training manual:
Rwanda TVET Board (RTB) extends its appreciation to all parties who contributed to the
development of the trainer and trainee’s manuals for the TVET Certificate V in Software
Development, specifically for the module "GENPP501: Python Programming Fundamentals”
We extend our gratitude to KOICA Rwanda for its contribution to the development of these
training manuals and for its ongoing support of the TVET system in Rwanda
We extend our gratitude to the TQUM Project for its financial and technical support in the
development of these training manuals.
We would also like to acknowledge the valuable contributions of all TVET trainers and
industry practitioners in the development of this training manual.
The management of Rwanda TVET Board extends its appreciation to both its staff and the
staff of the TQUM Project for their efforts in coordinating these activities.
iv | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
This training manual was developed:
PRODUCTION TEAM
Authoring and Review
SEKABANZA Jean de la Paix
AKIMANA Gabriel
Validation
HAKIZIMANA Evariste
NYANDWI Ronger
vi | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
TABLE OF CONTENT
vii | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
ACRONYMS
viii | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
INTRODUCTION
This trainee's manual includes all the knowledge and skills required in Software
Development specifically for the module of "Python Programming Fundamentals". Trainees
enrolled in this module will engage in practical activities designed to develop and enhance
their competencies. The development of this training manual followed the Competency-
Based Training and Assessment (CBT/A) approach, offering ample practical opportunities
that mirror real-life situations.
The trainee's manual is organized into Learning Outcomes, which is broken down into
indicative content that includes both theoretical and practical activities. It provides detailed
information on the key competencies required for each learning outcome, along with the
objectives to be achieved.
As a trainee, you will start by addressing questions related to the activities, which are
designed to foster critical thinking and guide you towards practical applications in the labor
market. The manual also provides essential information, including learning hours, required
materials, and key tasks to complete throughout the learning process.
All activities included in this training manual are designed to facilitate both individual and
group work. After completing the activities, you will conduct a formative assessment,
referred to as the end learning outcome assessment. Ensure that you thoroughly review the
key readings and the 'Points to Remember' section.
Resources
Duration:5 hrs
Tasks:
Task:
10 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
use.
N.B: Among the tools you have to select the followings depending on the project to
be developed.
2. Python IDE
An IDE is a software application that provides comprehensive facilities for
programmers to develop software.
Here are some of the most popular Python IDEs:
2.1. Visual Studio Code (VS Code)
Platform
Windows, macOS, Linux
Features
Lightweight, highly customizable, supports various programming languages,
intelligent code completion, debugging, Git integration, and a vast extension
marketplace.
2.2. PyCharm
Platform: Windows, macOS, Linux
Features: Specifically designed for Python development, intelligent code completion,
refactoring, debugging, unit testing, and integration with popular Python
frameworks like Django and Flask.
2.3. Jupiter Notebook
Platform: Web-based, can be used in most browsers
Features: Interactive environment for data analysis, scientific computing, and
machine learning. It's great for exploring data, creating visualizations, and sharing
results.
2.4. Spyder
Platform: Windows, macOS, Linux
Features: Similar to MATLAB, Spyder is a scientific computing environment with a
MATLAB-like interface, suitable for data analysis and scientific programming.
2.5. Sublime Text
Platform: Windows, macOS, Linux
Features: A lightweight, highly customizable text editor with excellent Python
support, including syntax highlighting, code completion, and multiple panes.
2.6. Thonny
Platform: Windows, macOS, Linux
Features: A beginner-friendly IDE designed for teaching programming, with a simple
interface, step-by-step debugging, and a built-in Python interpreter.
3. Python frameworks
Python frameworks provide a pre-built structure and tools to streamline the
development process. They offer reusable code, best practices, and a modular
approach, making it easier to build applications efficiently.
11 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
3.1. Web Development Frameworks
3.1.1. Django:
A full-stack framework known for its rapid development, scalability, and
security features. It's ideal for complex web applications.
3.1.2. Flask
A lightweight, minimalist framework that offers flexibility and control. It's
suitable for smaller projects and APIs.
3.1.3. FastAPI
A modern framework that emphasizes performance, ease of use, and developer
experience. It's built on top of Starlette and Pedantic.
3.2. Data Science and Machine Learning Frameworks
3.2.1. TensorFlow
A popular open-source platform for machine learning, deep learning, and
natural language processing. It's used for building and training neural networks.
3.2.2. PyTorch
Another popular framework for machine learning, known for its flexibility and
ease of use. It's often used for research and prototyping.
3.2.3. Scikit-learn
A machine learning library that provides a simple interface for building and
training models, including classification, regression, clustering, and
dimensionality reduction.
3.3. Scientific Computing and Data Analysis Frameworks
3.3.1. NumPy
A fundamental package for numerical computing, providing multi-dimensional
arrays and matrices, along with mathematical functions.
3.3.2. Pandas
A powerful data analysis library offering data structures like Data Frames and
Series, which make it easy to manipulate and analyse data.
3.3.3. Matplotlib
A plotting library for creating static, animated, and interactive visualizations.
Other Notable Frameworks:
3.3.4. Kivy
A framework for building cross-platform mobile apps, desktop applications, and
web applications using a single codebase.
3.3.5. Twisted
A framework for asynchronous networking, making it suitable for building
network-intensive applications like servers and chat clients.
3.3.6. CherryPy
A minimalistic web framework that emphasizes simplicity and performance.
3.4. Automation libraries in python
12 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
Python has several powerful libraries for automation that can help streamline
tasks across various domains.
Here are some of the most popular ones:
3.4.1. Selenium
Use Case: Automating web browsers.
Description: Selenium allows you to control a web browser programmatically. It
can be used for testing web applications and scraping data from websites.
3.4.2. PyAutoGUI
Use Case: GUI automation.
Description: PyAutoGUI lets you simulate mouse movements, clicks, and
keyboard inputs to automate interactions with desktop applications.
3.4.3. requests
Use Case: HTTP requests.
Description: While primarily used for making HTTP requests, it can be leveraged
for automating interactions with web APIs.
3.4.4. BeautifulSoup
Use Case: Web scraping.
Description: BeautifulSoup is used for parsing HTML and XML documents. It
helps in extracting data from web pages.
3.4.5. Pandas
Use Case: Data manipulation and analysis.
Description: Pandas is excellent for automating data processing tasks, such as
cleaning, transforming, and analyzing data in tabular formats.
3.4.6. Airflow
Use Case: Workflow automation.
Description: Apache Airflow is a platform to programmatically author, schedule,
and monitor workflows, making it ideal for batch data processing.
3.4.7. Celery
Use Case: Distributed task queue.
Description: Celery is used for handling asynchronous tasks and scheduling
them, making it great for background job processing.
3.4.8. Paramiko
Use Case: SSH and SFTP.
Description: Paramiko allows you to automate SSH connections and file
transfers, useful for server management and automation.
3.4.9. Fabric
Use Case: SSH command execution.
Description: Fabric is a high-level Python library for executing shell commands
remotely over SSH, making it easier to deploy applications.
3.4.10. pywinauto
13 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
Use Case: Windows GUI automation.
Description: This library allows you to automate GUI interactions on Windows
applications.
3.4.11. Schedule
Use Case: Job scheduling.
Description: A simple library for scheduling Python functions to run at specific
intervals.
Points to Remember
14 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
● Scientific Computing and Data Analysis Frameworks: NumPy, Pandas and
Matplotlib
● In python we can use the following automation Libraries: Selenium, PyAutoGUI,
requests, BeautifulSoup, Airflow, Celery, Paramiko, Fabric, Pywinauto and
Schedule.
15 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
Indicative content 1.2: Installation of Python Tools
Duration: 5 hrs
Tasks:
1. You are requested to identify the system requirements to install python tools.
2. Write your findings on paper/flipchart
3. Present your findings to the whole class and trainer
4. For more clarification read key reading 1.2.1 and ask questions where necessary.
2. Software Requirements
Operating System: Python tools can run on Windows, macOS, or Linux. However,
certain tools may have better support on Linux and macOS (e.g., TensorFlow on
GPUs). Ensure that the OS version is up-to-date and compatible with Python versions
(e.g., Windows 10 or higher).
Python Interpreter: The latest version of Python (3.x) should be installed. Some tools
may require specific versions of Python (3.6, 3.8, etc.).
16 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
Package Manager: pip (Python’s package installer) is required for installing most
Python tools. Ensure that pip is installed and up-to-date.
Development Tools: A suitable IDE or text editor (such as PyCharm, VS Code, or
Jupyter Notebook) is required for writing and testing Python code.
If working with web development or DevOps, Node.js, Docker, or Git may be
necessary for additional setup.
Task:
17 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
Double-click the installer file (e.g., python-3.12.exe).
Follow the on-screen instructions: Check the "Add Python to PATH" option to
make Python accessible from the command line.
Choose the installation location (default is usually fine).
18 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
If Python is installed correctly, you should see the installed version number
displayed.
2. Install PyCharm
a. Download PyCharm or use offline from external storage
Visit the Jet Brains website: https://www.jetbrains.com/pycharm/download/
Click on the "Download PyCharm" button.
19 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
Follow the on-screen instructions
Accept the license agreement.
Choose the installation location (default is usually fine).
20 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
Click "Install" and wait for the installation to complete.
21 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
c. Launch PyCharm
Once the installation is finished, click "Finish" to launch PyCharm.
22 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
Practical Activity 1.2.3: Configuring python virtual environment
Task:
23 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
On macOS and Linux
Run the following command source myenv/bin/activate
Once activated, your terminal prompt will change to indicate that you are now
working within the virtual environment.
3. Installing Packages
With the virtual environment activated, you can install packages using pip
“pip install package name”
6. Freeze packages
The "freeze" command in the context of Python virtual environments is used to
create a list of all installed packages and their versions. This is particularly useful
for replicating your environment or sharing your project setup with others.
Activate your virtual environment if it's not already activated.
Run the freeze command
24 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
This command will create a file named requirements.txt in your current
directory, containing a list of all installed packages and their versions.
7. To install packages from a requirements.txt file in another environment
This is helpful for setting up identical environments across different machines or
for other developers working on the same project
Points to Remember
● To install Python tools, your system should meet certain hardware requirements:
at least a dual-core processor, 4 GB RAM (preferably 8-16 GB for heavier tasks), 1
GB of free disk space, and optionally, a GPU for machine learning.
● On the software side, ensure you have the latest version of Python 3.x, an
appropriate IDE (e.g., VS Code, PyCharm), pip for package management, and
necessary dependencies like C++ build tools or Java for specific libraries
● While installing python we follow these steps:
Step 1: download the Python Installer or use offline from external storage
Step 2: run the installer
Step 3: verify the installation
● while installing PyCharm we follow these steps:
Step 1: Download PyCharm or use offline from external storage
Step 2: Run the installer
Step 3: Launch PyCharm
● Python virtual environments create isolated environments for projects,
preventing dependency conflicts.
● To create a virtual environment, use python -m venv myenv.
● Activate it using myenv\Scripts\activate.
● Install packages with pip install package_name.
● Deactivate using deactivate.
● Freeze dependencies with pip freeze > requirements.txt.
● Install from requirements.txt using pip install -r requirements.txt.
25 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
Application of learning 1.2.
HHT LTD Company located in Kicukiro district, wants to develop a web app that will help in
selling their products online and the system will have capabilities to perform automatic
deployment on the side of system administrator. You have been hired as full stack developer
responsible for installing and configuring all python tools that will be needed to develop that
project.
The company will provide all tools, materials and equipment.
26 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
Indicative content 1.3: Testing Python Installation
Duration: 5 hrs
Task:
27 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
Exit the Interpreter
To exit, type “exit()” or press Ctrl + D (macOS/Linux) or Ctrl + Z followed by
Enter (Windows).
28 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
Points to Remember
29 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
Learning outcome 1 end assessment
Written assessment
30 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
8. The command to install a Python package using pip is:
a) python install package_name
b) pip install package_name
c) install package_name
d) pip setup package_name
9. Which of the following is NOT a Python web framework?
a) Django
b) Flask
c) NumPy
d) FastAPI
10. In Python, indentation is used to:
a) Declare variables
b) Define the scope of loops and functions
c) Import libraries
d) Comment on the code
11. Which Python library is primarily used for numerical computing?
a) Pandas
b) NumPy
c) Matplotlib
d) Scikit-learn
12. Python’s memory management is handled by:
a) The developer
b) The Python interpreter automatically
c) An external tool
d) Manual memory allocation
13. Which of the following is an example of a Python text editor?
a) PyCharm
b) Jupyter Notebook
c) Sublime Text
d) All of the above
14. Python was first released in:
a) 1989
b) 1991
c) 1995
d) 2000
15. What is the primary use of the TensorFlow library?
a) Web development
b) Machine learning
c) Data visualization
d) Game development
16. Which of the following is NOT a characteristic of Python?
31 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
a) Dynamic typing
b) Complex syntax
c) Object-oriented programming
d) Readability
17. What does the command python --version do?
a) Runs a Python script
b) Displays the current Python version installed
c) Updates Python to the latest version
d) Installs Python on your system
18. Which Python library is widely used for data visualization?
a) Matplotlib
b) TensorFlow
c) Flask
d) Pandas
19. What does IDE stand for in the context of Python?
a) Integrated Development Environment
b) Interactive Development Editor
c) Integrated Debugging Environment
d) Interactive Design Editor
20. Which Python command is used to create a virtual environment?
a) python create venv
b) python -m venv
c) venv create
d) create venv python
21. Which Python framework is designed for asynchronous networking?
a) Kivy
b) Twisted
c) CherryPy
d) Flask
22. In Python, a function is defined using the keyword:
a) func
b) function
c) def
d) define
23. Which IDE is web-based and primarily used for data analysis?
a) PyCharm
b) Jupyter Notebook
c) Visual Studio Code
d) Thonny
24. The command to deactivate a Python virtual environment is:
a) end venv
32 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
b) stop venv
c) deactivate
d) exit venv
25. What type of language is Python?
a) Low-level
b) High-level
c) Mid-level
d) Machine-level
II. Complete the following statements by using one of the keyword listed below;
You can use one keyword once or more.
Display installed packages, Kivy, Large, Data type, IDEs, Delete, Functional,
TensorFlow, Include libraries, Interpreted, pip, Indentation, FastAPI, Pandas,
Beginners
1. Python is an ____________ language, meaning it executes code line by line.
2. The Python package manager is called ____________.
3. Python relies on ____________ to define the scope of loops, functions, and classes.
4. ____________ is a popular Python framework for building APIs, known for its
performance and ease of use.
5. The Python library ____________ is used for data manipulation and analysis.
6. Python’s simple and readable syntax makes it especially beneficial for
____________.
7. The command pip list is used to ____________.
8. ____________ is a Python framework used for developing cross-platform mobile and
desktop applications.
9. Python’s ____________ community provides extensive support, documentation, and
resources.
10. In Python, variables do not require an explicit ____________ declaration.
11. PyCharm and VS Code are examples of ____________ used for Python development.
12. The command rmdir /s myenv is used to ____________ a Python virtual
environment.
13. Python supports both object-oriented and ____________ programming paradigms.
14. The Python library ____________ is widely used for machine learning and deep
learning.
15. In Python, the import statement is used to ____________.
33 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
III. Matching questions
1. Match the IDE in column A with their corresponding primary features in column B
34 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
6. Match the Python tool of column A with its corresponding description in column B
Answers Column A Column B
…….. a) PyTorch (i) Computer vision library
…….. b) TensorFlow (ii) Flexible machine learning framework
…….. c) SciPy (iii) Platform for deep learning
…….. d) OpenCV (iv) Scientific computing and statistics
7. Match the Python task in Column A with corresponding the suitable
library/framework in Column B:
…….. Column A Column B
…….. a) Web Development (i) Scikit learn
…….. b) Data Visualization (ii) Matplotlib
…….. c) Machine Learning (iii) Django
…….. d) Task Automation (iv) Python’s standard library
8. Match the Python version command in Column A with its corresponding
corresponding output in Column B:
Answers Column A Column B
…….. a) python -- (i) Displays the Python version number
version
…….. b) pip show (ii) Shows details of the installed NumPy
numpy package
…….. c) python -m (iii) Creates a new virtual environment
venv env
…….. d) pip freeze (iv) Lists installed packages in the virtual
environment
9. Match the Python command in Column A with the corresponding action it
performs in Column B:
Answers Column A Column B
…….. a) import (i) Defines a function
…….. b) def (ii) Imports a module or library
…….. c) print (iv) Outputs data to the console
…….. d) class (iii) Defines a new class
10. Match the following Python versions in Column A with their corresponding key
characteristics in Column B:
Answers Column A Column B
…….. a) Python 2.x (i) Legacy version with different print syntax
…….. b) Python 3.x (ii) Current version with updated syntax
…….. c) Python 3.6+ (iv) Introduced f string formatting
…….. d) Python 3.8+ (iii) Introduced assignment expressions
35 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
Practical assessment
HHT LTD Company located in Kicukiro district, wants to develop a web application that will
help in selling their products online and the system will have capabilities to perform
automatic deployment on the side of system administrator and automatic updates once
new feature is added. You have been hired as full stack developer responsible for installing,
configuring all python tools that will be needed to develop that project, testing the python
installation and installing required packages that will be used.
The company will provide all tools, materials and equipment.
36 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
References
Books
Alpaydin, E. (2020). Introduction to Machine Learning (Adaptive Computation
and Machine Learning series). MIT Press.
Bishop, C. Ms. (2006). Pa ern Recognition and Machine Learning. Springer.
Chollet, F. (2017). Deep Learning with Python. Manning Publications.
Goodfellow, I., Bengio, Y., Courville, A., & Bengio, Y. (2016). Deep Learning
(Adaptive Computation and Machine Learning series). MIT Press.
Web Links
Foundation, P. S. (2001-2025). downloads/. Retrieved 12 23, 2024, from python.org:
https://www.python.org/downloads/
JetBrains. (2024, 02 20). configuring-python-interpreter.html#view_list. Retrieved 01
13, 2025, from JetBrains: https://www.jetbrains.com/help/pycharm/configuring-
python-interpreter.html#view_list
JetBrains. (2023, 05 03). creating-virtual-environment.html. Retrieved 01 13, 2025,
from JejBrains.com: https://www.jetbrains.com/help/pycharm/creating-virtual-
environment.html
JetBrains. (2023). download/?section=windows. Retrieved 01 13, 2025, from
JetBrains.com: https://www.jetbrains.com/pycharm/download/?section=windows
JetBrains. (2022). quick-start-guide.html#-lnysrf_12. Retrieved 01 13, 2024, from
JetBrains.com: https://www.jetbrains.com/help/pycharm/quick-start-
guide.html#search.
37 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
Learning Outcome 2: Write Basic Python Program
38 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
Indicative contents
2.1 Applying python basic concepts
2.2 Applying python control structures
2.3 Applying functions in Python
2.4 Applying of Python Collections
2.5 Performing File handling
39 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
Duration: 45 hrs
Resources
40 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
Indicative content 2.1: Applying Python Basic Concepts
Duration: 9 hrs
Tasks:
41 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
Booleans (bool): Represents True or False.
Lists: Ordered, mutable collections, e.g., [1, 2, 3].
Tuples: Ordered, immutable collections, e.g., (1, 2, 3).
Dictionaries (dict): Key-value pairs, e.g., {"name": "Alice", "age": 25}.
Sets: Unordered collections of unique elements, e.g., {1, 2, 3}.
None : Once you have a variable and you didn’t assign any value to it
1.2. Features of mapping data types
Key Features of mapping data types are:
Unordered: The elements in a mapping are not stored in a specific order.
Mutable: Elements can be added, modified, or removed after creation.
Key-value Pairs: Each element consists of a key and a value.
Efficient Lookup: Values can be quickly retrieved using their corresponding
keys.
Key Characteristics of Boolean datatypes are:
Binary: Boolean values can only be one of two states: true or false.
Basic Operations: Boolean operations include AND, OR, NOT, and XOR.
Conditional Statements: Boolean expressions are used in conditional
statements like if, else, and while to control program flow.
Key Features of sets are:
Unordered: The elements in a set are not stored in a specific order.
Mutable: Elements can be added or removed after creation.
Unique Elements: Sets cannot contain duplicate elements.
Efficient Membership Testing: Checking if an element exists in a set is
typically very fast.
1.3. Operation that can be done on set datatypes
Operation that can be done on set datatypes includes:
Union: Combines two sets, including all unique elements from both sets.
Intersection: Finds the elements that are common to both sets.
Difference: Finds the elements that are in the first set but not in the second
set.
Symmetric Difference: Finds the elements that are in either set but not
both.
Membership Testing: Checks if an element exists in the set.
Adding/Removing Elements: Adding or removing elements from a set.
2. Variables
Variables in Python are used to store data. You can create a variable by assigning a
value to it using the assignment operator (=).
2.1. Naming rules of python variables.
When naming variables in Python, you must adhere to the following rules:
Start with a letter or underscore
42 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
Variables cannot begin with a number.
Consist of letters, numbers, and underscores: Only these characters are
allowed in variable names.
Case-sensitive: Python distinguishes between uppercase and lowercase
letters. For example, myVariable and myvariable are considered different
variables.
Do not use keywords as variable names, as they have special meanings in
Python.
Convention: While not strictly enforced, Python has a common naming
convention known as PEP 8. It recommends using lowercase letters with
underscores to separate words (e.g., my_variable).
2.2. Variable declaration
Python does not require explicit variable declaration. You can simply assign a value
to a variable, and the variable will be created automatically.
For example:
x = 10 # Integer
name = "Bob" # String
is_active = True # Boolean
Variable names should be descriptive and can include letters, numbers, and
underscores, but they cannot start with a number.
3. Comments
Comments are used to explain code and are ignored by the Python interpreter. You
can create a single-line comment by using the # symbol:
3.1. The types of comments in python are:
Single-line comment
Multi-line comment
3.2. The difference between single-line and multi-line comments:
single-line comments (#) for short explanations’
multi-line comments (''' ''' or """ """) for longer notes or documentation.
3.3. To write a comment in python
In python, we use the hash symbol # to write a single-line comment. This line
is ignored by the Python interpreter.
In python, you can use triple quotes (''' or """) to write multi-line comment.
# This is a single-line comment
x = 5 # Assign 5 to x
For multi-line comments, you can use triple quotes:
"""
This is a
multi-line comment
"""
43 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
4. Operators
Operators are special symbols that perform operations on variables and values.
Common operators in Python include:
4.1. Arithmetic Operators:
+ (Addition)
- (Subtraction)
* (Multiplication)
/ (Division)
// (Floor Division)
% (Modulus)
** (Exponentiation)
4.2. Comparison Operators:
== (Equal to)
!= (Not equal to)
> (Greater than)
< (Less than)
>= (Greater than or equal to)
<= (Less than or equal to)
4.3. Logical Operators:
And: Returns True if both statements are true
Or: Returns True if one of the statements is true
Not: Reverse the result, returns False if the result is true
4.4. Assignment Operators:
= (Assign)
+= (Add and assign)
-= (Subtract and assign)
*= (Multiply and assign)
/= (Divide and assign)
4.5. Python Membership Operators are used to test if a sequence is presented in
an object:
in : Returns True if a sequence with the specified value is present in the object
not in: Returns True if a sequence with the specified value is not present in the
object
44 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
4.6. Python Bitwise Operators are used to compare (binary) numbers :
Operat Nam Description
or e
& AND Sets each bit to 1 if both bits are 1
| OR Sets each bit to 1 if one of two bits is 1
^ XOR Sets each bit to 1 if only one of two bits is 1
~ NOT Inverts all the bits
<< Zero Shift left by pushing zeros in from the right
fill and let the leftmost bits fall off
left
shift
>> Signe Shift right by pushing copies of the leftmost bit
d in from the left, and let the rightmost bits fall
right off
shift
Task:
1. Data Types
Application: Using different data types to store and manipulate various kinds of data.
# Different data types
integer_value = 42 # Integer
45 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
float_value = 3.14 # Float
string_value = "Hello, Python!" # String
boolean_value = True # Boolean
list_value = [1, 2, 3, 4, 5] # List
tuple_value = (1, 2, 3) # Tuple
dict_value = {"name": "Alice", "age": 30} # Dictionary
set_value = {1, 2, 3} # Set
3. Comments
Application: Documenting code for better understanding.
# Main execution
length = 5 # Length of the rectangle
width = 3 # Width of the rectangle
area = calculate_area(length, width) # Calculate area
46 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
# Arithmetic Operators
a = 10
b=3
# Addition
addition = a + b
print(f"Addition: {a} + {b} = {addition}")
# Subtraction
subtraction = a - b
print(f"Subtraction: {a} - {b} = {subtraction}")
# Multiplication
multiplication = a * b
print(f"Multiplication: {a} * {b} = {multiplication}")
# Division
division = a / b
print(f"Division: {a} / {b} = {division}")
# Floor Division
floor_division = a // b
print(f"Floor Division: {a} // {b} = {floor_division}")
# Modulus
modulus = a % b
print(f"Modulus: {a} % {b} = {modulus}")
# Exponentiation
exponentiation = a ** b
print(f"Exponentiation: {a} ** {b} = {exponentiation}")
4.2 Comparison Operators
# Comparison Operators
x=5
y = 10
# Equal to
print(f"{x} == {y}: {x == y}")
47 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
# Not equal to
print(f"{x} != {y}: {x != y}")
# Greater than
print(f"{x} > {y}: {x > y}")
# Less than
print(f"{x} < {y}: {x < y}")
# Logical Operators
a = True
b = False
# Logical AND
print(f"a and b: {a and b}")
# Logical OR
print(f"a or b: {a or b}")
# Logical NOT
print(f"not a: {not a}")
4.4 Assignment Operators
# Assignment Operators
num = 10
48 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
# Multiply and assign
num *= 2
print(f"After *= 2, num = {num}")
Points to Remember
49 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
Indicative content 2.2: Applying Python Control Structures
Duration: 9 hrs
Task:
1. Introduction
Conditional statements in Python allow you to execute different blocks of code
based on certain conditions.
2. Common frequently used conditional statements
The most common conditional statements are
If
else.
Elif
50 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
Key Points:
if number % 2 == 0:
print(f"{number} is even.")
else:
print(f"{number} is odd.")
51 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
2.4. Nested Conditional Statements
Application: Using conditional statements within other conditional statements.
# Nested if statement
temperature = 30
if temperature > 0:
print("The water is liquid.")
if temperature > 100:
print("The water is boiling.")
else:
print("The water is frozen.")
2.5. Using Logical Operators in Conditions
Application: Combining conditions using logical operators (and, or, not).
Task:
1. Introduction
Looping statements in Python allow you to execute a block of code multiple times.
52 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
The two primary types of loops are “ for loops” and “while loops. “
2. Application of “for loop” and “while loop” statements
Here are some applications with sample examples for each:
print("Even numbers:")
53 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
for number in numbers:
if number % 2 == 0:
print(number)
print("\nUsing continue:")
for number in range(1, 11):
if number % 2 == 0:
continue # Skip even numbers
print(number) # Print only odd numbers
Task:
1. Introduction
Jump statements in Python control the flow of loops and can alter the normal
execution sequence.
2. Common frequently used ump statements
The main jump statements are break, continue, and pass. Here are examples of each:
54 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
2.1. Break Statement
Application: Exits the nearest enclosing loop when a specified condition is met.
# Example of break
for number in range(1, 11):
if number == 6:
print("Breaking the loop at number 6.")
break # Exit the loop
print(number)
# Example of continue
for number in range(1, 11):
if number % 2 == 0:
continue # Skip even numbers
print(number) # Print only odd numbers
# Output will be: 1, 3, 5, 7, 9
Pass Statement
Application: A null operation; it is syntactically required but does nothing when
executed. It's often used as a placeholder.
# Example of pass
for number in range(1, 6):
if number == 3:
pass # Placeholder for future code
print(number)
Points to Remember
55 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
● The elif statement is used to test additional conditions if the previous if or elif
conditions are false.
● Indentation is crucial for defining the code blocks within conditional statements.
● Comparison operators (e.g., ==, !=, <, >, <=, >=) are used to create conditions.
● Logical operators (e.g., and, or, not) can be used to combine multiple conditions.
● Nested conditional statements can be used to create more complex decision-
making logic.
● Proper indentation is essential for ensuring correct code execution.
● Testing different conditions can help verify the correctness of conditional
statements.
● Looping statements are used to repeat a block of code multiple times in Python.
● The for loop is used to iterate over a sequence of elements (e.g., lists, tuples,
strings).
● The while loop is used to repeat a block of code as long as a condition is true.
● The break statement can be used to exit a loop prematurely.
● The continue statement can be used to skip the current iteration of a loop and
move to the next one.
● Nested loops can be used to create more complex looping structures.
● Indentation is crucial for defining the code block within loops.
● Break: Terminates the loop entirely when a condition is met.
● Continue: Skips the current iteration and continues with the next one.
● Pass: Does nothing and is useful for maintaining the structure of code where a
statement is syntactically required.
56 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
Indicative content 2.3: Applying Functions in Python
Duration: 9 hrs
Tasks:
1. You are requested to answer the following questions related to the description of
functions in python:
i. Define function in python
ii. Differentiate two (2) types of function in python
iii. Elaborate characteristics and Advantages of using functions in python
2. Write your findings on paper/flipchart
3. Present your findings to the whole class or trainer
4. For more clarification read key reading 2.3.1 and ask questions where necessary.
1. Definition of Function
A function in Python is a block of reusable code that performs a specific task. It is
defined using the def keyword, followed by the function name and parentheses
containing any parameters.
Functions help organize code, making it more modular and easier to understand.
Example of a Function Definition:
def greet(name):
"""This function greets the person passed as a parameter."""
print(f"Hello, {name}!")
2. Characteristics of Functions
1. Modularity: Functions allow you to break your program into smaller,
manageable pieces.
2. Reusability: Once defined, functions can be reused multiple times throughout
the code.
3. Parameters and Return Values: Functions can accept parameters and return
values, making them flexible.
4. Encapsulation: Functions encapsulate the logic of a task, which can improve
code clarity.
57 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
5. Scope: Variables defined inside a function are local to that function unless
specified otherwise.
3. Advantages of Functions
1. Improved Readability: Breaking code into functions improves readability and
organization.
2. Easier Maintenance: Functions can be modified independently, making
maintenance simpler.
3. Code Reusability: Functions can be reused across different parts of a program
or even in different programs.
4. Debugging: Isolating functionality into functions simplifies debugging since
you can test each function independently.
5. Abstraction: Functions allow you to abstract complex operations, making it
easier to understand and use.
4. Types of Functions
4.1. Built-in Functions
These are functions that are pre-defined in Python and can be used without any
additional code.
Examples include:
print(): Outputs data to the console.
len(): Returns the length of an object.
type(): Returns the type of an object.
sum(): Returns the sum of a collection of numbers.
Example of a Built-in Function:
numbers = [1, 2, 3, 4, 5]
total = sum(numbers) # Using the built-in sum function
print(f"The total is: {total}")
4.2. User-Defined Functions
These are functions that you define yourself to perform specific tasks. You can create
them using the def keyword.
Example of a User-Defined Function
def add(a, b):
"""This function returns the sum of two numbers."""
return a + b
result = add(5, 3) # Calling the user-defined function
print(f"The sum is: {result}")
58 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
Practical Activity 2.3.2: Creating function in python
Task:
1. Defining a Function
In Python, you can define a function using the def keyword. A function is a block of
reusable code that performs a specific task. It can take inputs (called parameters),
execute code, and optionally return a result.
def function_name(parameters):
"""
Optional docstring: Describes the function's purpose.
"""
# Code block to execute
return value # Optional
Example
def greet(name):
"""This function greets the person passed as a parameter."""
print(f"Hello, {name}!")
2. Arguments
Arguments are the values you pass to a function when calling it. You can define
functions with different types of arguments:
Positional Arguments:
These must be provided in the correct order.
def add(a, b):
return a + b
59 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
Keyword Arguments:
You can specify arguments by name, allowing you to pass them in any order.
def describe_pet(animal_type, pet_name):
print(f"I have a {animal_type} named {pet_name}.")
60 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
Practical Activity 2.3.3: Applying special purpose functions
Task:
Lambda functions are efficient whenever you want to create a function that will only
contain simple expressions – that is, expressions that are usually a single line of a
statement. They're also useful when you want to use the function once.
Let's look at an example of a lambda function to see how it works. We'll compare it to a
regular user-defined function.
61 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
Assume I want to write a function that returns twice the number I pass it. We can define
a user-defined function as follows:
def f(x):
return x * 2
f(3)
>> 6
Now for a lambda function. We'll create it like this:
lambda x: x * 3
As we explained above, the lambda function does not have a return keyword. As a result,
it will return the result of the expression on its own. The x in it also serves as a
placeholder for the value to be passed into the expression. You can change it to
whatever you want.
Now if you want to call a lambda function, you will use an approach known as
immediately invoking the function. That looks like this:
(lambda x : x * 2)(3)
>> 6
The reason for this is that since the lambda function does not have a name you can
invoke (it's anonymous), you need to enclose the entire statement when you want to call
it.
So, for example, if you want to create a function with a for-loop, you should use a user-
defined function.
In Python, iterables include strings, lists, dictionaries, ranges, tuples, and so on. When
working with iterables, you can use lambda functions in conjunction with two common
functions: filter() and map().
Filter()
62 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
When you want to focus on specific values in an iterable, you can use the filter function.
The following is the syntax of a filter function:
filter(function, iterable)
As you can see, a filter function requires another function that contains the expression or
operations that will be performed on the iterable.
For example, say I have a list such as [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]. Now let's say that I’m
only interested in those values in that list that have a remainder of 0 when divided by 2. I
can make use of filter() and a lambda function.
Firstly I will use the lambda function to create the expression I want to derive like this:
lambda x: x % 2 == 0
Then I will insert it into the filter function like this:
list1 = [2, 3, 4, 5]
list(map(lambda x: pow(x, 2), list1))
>> [4, 9, 16, 25]
Pandas Series
Another place you'll use lambda functions is in data science when creating a data frame
from Pandas.
A series is a data frame column. You can manipulate all of the values in a series by using
the lambda function.
For example, if I have a data frame with the following columns and want to convert the
values in the name column to lower case, I can do so using the Pandas apply function and
a Python lambda function like this:
import pandas as pd
63 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
df = pd.DataFrame(
{"name": ["IBRAHIM", "SEGUN", "YUSUF", "DARE", "BOLA", "SOKUNBI"],
"score": [50, 32, 45, 45, 23, 45]
}
)
The apply function will apply each element of the series to the lambda function. The
lambda function will then return a value for each element based on the expression you
passed to it. In our case, the expression was to lowercase each element.
2. Python Generators
Definition: Generators are a type of iterable, like lists or tuples. Unlike lists, they do
not store their contents in memory; instead, they generate items on-the-fly using
the yield keyword.
64 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
Example:
# Generator function to yield numbers
def count_up_to(n):
count = 1
while count <= n:
yield count
count += 1
# Using the generator
for number in count_up_to(5):
print(number) # Outputs: 1, 2, 3, 4, 5
3. Python Closures
Definition: A closure is a function that remembers its enclosing lexical scope even
when the program flow is no longer in that scope.
Example:
def outer_function(msg):
def inner_function():
print(msg)
return inner_function
# Create a closure
my_greeting = outer_function("Hello, World!")
my_greeting() # Outputs: Hello, World!
4. Python Decorators
Definition: Decorators are a way to modify or enhance functions or methods without
changing their code. They are applied using the @decorator syntax.
Example:
def decorator_function(original_function):
def wrapper_function():
print("Wrapper executed before {}".format(original_function.__name__))
return original_function()
return wrapper_function
@decorator_function
def display():
print("Display function executed.")
# Calling the decorated function
display()
# Outputs:
# Wrapper executed before display
# Display function executed.
65 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
5. Recursive Function
Definition: A recursive function is a function that calls itself in order to solve a
problem.
Example:
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
# Calling the recursive function
result = factorial(5)
print(f"The factorial of 5 is: {result}") # Outputs: The factorial of 5 is: 120
6. Higher-Order Function
Definition: A higher-order function is a function that takes one or more functions as
arguments or returns a function as its result.
Example:
Points to Remember
66 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
● Characteristics of Functions include: Modularity, Reusability, Parameters and
Return Values, Encapsulation and Scope.
● Advantages of Functions include: Improved Readability, Easier Maintenance,
Code Reusability, Debugging and Abstraction.
● Creation of Function in Python you can follow the following steps:
Step 1: Defining a Function
Step 2: Arguments
Step 3: Default Parameter Value
Step 4: Passing a List as an Argument
Step 5: Calling a Function
● Special purpose functions offer unique capabilities and can be used to solve
specific problems.
● Lambda functions are concise and often used for short, simple expressions.
● Generators provide efficient ways to generate values on demand.
● Closures can be used to create functions with state.
● Decorators can modify the behavior of other functions without directly changing
their code.
● Recursive functions can be used to solve problems that can be broken down into
smaller, similar sub problems.
● Higher-order functions can be used to create more flexible and reusable code.
67 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
Indicative content 2.4: Applying of Python Collections
Duration: 9 hrs
Tasks:
1. You are requested to answer the following questions related to the description of
collections in python:
i. Describe collection Types in Python
ii. Explain Tools from the Collections Module
2. Write your findings on paper/flipchart
3. Present your findings to the whole class or trainer
4. For more clarification read key reading 2.4.1 and ask questions where necessary.
Example:
fruits = ['apple', 'banana', 'cherry']
fruits.append('orange') # Add an item
print(fruits) # Outputs: ['apple', 'banana', 'cherry', 'orange']
1.2. Tuples
Definition: Tuples are ordered, immutable collections. Once created, their elements
cannot be changed.
68 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
Syntax:
Example:
student = {'name': 'Alice', 'age': 25}
student['age'] = 26 # Modify value
print(student) # Outputs: {'name': 'Alice', 'age': 26}
1.4. Sets
Definition: Sets are unordered collections of unique elements. They are mutable and
do not allow duplicate values.
Syntax: my_set = {item1, item2, item3, ...}
Sets are defined using curly braces {} or the set() constructor.
Items in a set are separated by commas ,.
Sets do not allow duplicate elements.
Sets are unordered, so they do not support indexing or slicing.
Example:
unique_numbers = {1, 2, 2, 3}
print(unique_numbers) # Outputs: {1, 2, 3}
1.5. Frozen Set
Definition: A frozen set is an immutable version of a set. Once created, its elements
cannot be changed.
Syntax: my_frozenset = frozenset(iterable)
69 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
Use the frozenset() constructor to create a frozen set.
The iterable can be any iterable object like a list, tuple, set, or string.
Example:
immutable_set = frozenset([1, 2, 3, 4])
print(immutable_set) # Outputs: frozenset({1, 2, 3, 4})
1.6. ChainMaps
Definition: A ChainMap groups multiple dictionaries into a single view. It allows for
searching through multiple dictionaries as if they were one.
Syntax: from collections import ChainMap
Example:
from collections import ChainMap
1.7. Deques
Definition: Deques (double-ended queues) are mutable sequences that allow fast
appends and pops from both ends.
Syntax: from collections import deque
Example:
from collections import deque
70 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
Definition: An OrderedDict is a dictionary subclass that maintains the order of keys
based on their insertion order.
Example:
from collections import OrderedDict
ordered_dict = OrderedDict()
ordered_dict['apple'] = 1
ordered_dict['banana'] = 2
ordered_dict['cherry'] = 3
print(ordered_dict) # Outputs: OrderedDict([('apple', 1), ('banana', 2), ('cherry', 3)])
2.3. Defaultdict
Definition: A defaultdict is a dictionary subclass that provides a default value for a
nonexistent key. It avoids KeyErrors.
Example:
from collections import defaultdict
Task:
71 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
Key readings 2.4.2 Perform common operations on collection
1. Adding and Removing Elements
1.1. Lists
Adding:
fruits = ['apple', 'banana']
fruits.append('cherry') # Add to the end
fruits.insert(1, 'orange') # Add at index 1
print(fruits) # Outputs: ['apple', 'orange', 'banana', 'cherry']
Removing:
fruits.remove('banana') # Remove by value
popped_fruit = fruits.pop() # Remove last item and return it
print(fruits) # Outputs: ['apple', 'orange']
print(f"Popped fruit: {popped_fruit}") # Outputs: Popped fruit: cherry
1.2. Dictionaries
Adding:
student = {'name': 'Alice'}
student['age'] = 25 # Add new key-value pair
print(student) # Outputs: {'name': 'Alice', 'age': 25}
Removing:
del student['age'] # Remove key-value pair by key
print(student) # Outputs: {'name': 'Alice'}
2. Accessing and Iterating Over Elements
2.1. Lists
# Accessing elements
print(fruits[0]) # Outputs: apple
# Accessing values
print(student['name']) # Outputs: Alice
72 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
3. Filtering and Sorting
3.1. Sorting
Sorting Lists
numbers = [5, 2, 9, 1, 7]
# Ascending Order
ascending = sorted(numbers)
print("Ascending:", ascending) # Output: [1, 2, 5, 7, 9]
# Descending Order
descending = sorted(numbers, reverse=True)
print("Descending:", descending) # Output: [9, 7, 5, 2, 1]
numbers = [5, 2, 9, 1, 7]
# Sort in Ascending Order
numbers.sort()
print("Ascending:", numbers) # Output: [1, 2, 5, 7, 9]
# Sort in Descending Order
numbers.sort(reverse=True)
print("Descending:", numbers) # Output: [9, 7, 5, 2, 1]
Sorting Tuples
Tuples are immutable, so you can only use sorted() (returns a new sorted list).
numbers = (5, 2, 9, 1, 7)
ascending = sorted(numbers) # Output: [1, 2, 5, 7, 9]
descending = sorted(numbers, reverse=True) # Output: [9, 7, 5, 2, 1]
print("Ascending:", ascending)
print("Descending:", descending)
Sorting Dictionaries
1. Sorting by Keys
73 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
print("Descending by keys:", descending)
2. Sorting by Values
# Ascending by value
ascending = dict(sorted(students.items(), key=lambda x: x[1]))
print("Ascending by values:", ascending)
# Descending by value
descending = dict(sorted(students.items(), key=lambda x: x[1], reverse=True))
print("Descending by values:", descending)
Sorting Sets
Sets are unordered collections, so you must convert them into a list first.
numbers = {5, 2, 9, 1, 7}
ascending = sorted(numbers) # [1, 2, 5, 7, 9]
descending = sorted(numbers, reverse=True) # [9, 7, 5, 2, 1]
print("Ascending:", ascending)
print("Descending:", descending)
students = [
{"name": "Alice", "score": 85},
{"name": "Bob", "score": 92},
{"name": "Charlie", "score": 78}
]
74 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
Summary
3.2. Filtering
Filtering involves selecting specific elements from collections (list, tuple, dictionary)
based on a condition. Below is how you can filter these collections effectively.
1. Filtering a List
Using filter():
numbers = [1, 2, 3, 4, 5, 6]
2. Filtering a Tuple
Using filter():
numbers = (1, 2, 3, 4, 5, 6)
75 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
# Filter even numbers
even_numbers = tuple(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # Output: (2, 4, 6)
3. Filtering a Dictionary
# Keep items where the key starts with 'c' and the value is greater than 2
filtered_data = {k: v for k, v in data.items() if k.startswith('c') and v > 2}
print(filtered_data) # Output: {'c': 3}
76 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
Each method has its use case:
# Union
union_set = set_a | set_b # or set_a.union(set_b)
print(union_set) # Outputs: {1, 2, 3, 4, 5}
# Intersection
intersection_set = set_a & set_b # or set_a.intersection(set_b)
print(intersection_set) # Outputs: {3}
# Difference
difference_set = set_a - set_b # or set_a.difference(set_b)
print(difference_set) # Outputs: {1, 2}
4.2. Counting Elements (Using Counter):
from collections import Counter
# Push
stack.append('A')
stack.append('B')
stack.append('C')
# Pop
77 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
top_element = stack.pop()
print(top_element) # Outputs: C
print(stack) # Outputs: ['A', 'B']
Queue Operations (Using deque)
Queue: FIFO (First In, First Out)
from collections import deque
queue = deque()
# Enqueue
queue.append('A')
queue.append('B')
queue.append('C')
# Dequeue
first_element = queue.popleft()
print(first_element) # Outputs: A
print(queue) # Outputs: deque(['B', 'C'])
Points to Remember
● Python provides various built-in collection types, each serving different purposes:
Lists, Tuples, dictionaries, sets, frozen sets, ChainMaps and deques.
● The collections module enhances functionality with specialized tools like: Counter,
OrderedDict and defaultdict.
● These are common operations you can perform on various collection types in
Python. Lists, dictionaries, sets: Adding and Removing Elements, Accessing and
Iterating over Elements, Filtering and Sorting, Set Operations and Counting and
Stack and Queue Operations.
● Specialized tools such as deques provide powerful ways to manage and
manipulate data, making Python a versatile language for handling collections.
78 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
Indicative content 2.5: Performing File Handling
Duration: 9 hrs
Tasks:
1. You are requested to answer the following questions related to the description of
file handling libraries in python:
i.Describe the following file handling libraries
a) Os module
b) Pathlib module
c) Shutil module
d) Pandas library
2. Write your findings on paper/flipchart
3. Present your findings to the whole class or trainer
4. For more clarification read key reading 2.5.1 and ask questions where necessary.
File handling libraries in Python, include os, pathlib, shutil, and pandas. Each library
serves different purposes and offers various functionalities for file and directory
manipulation.
1. os Module
Description: The os module provides a way to use operating system-dependent
functionality like reading or writing to the file system, working with directories, and
handling environment variables.
Common Functions:
os.listdir(path): Returns a list of files and directories in the specified path.
os.mkdir(path): Creates a directory at the specified path.
os.remove(path): Deletes a file at the specified path.
os.rename(src, dst): Renames a file or directory.
os.path: Contains functions to manipulate pathnames
(e.g., os.path.join, os.path.exists).
79 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
Example:
import os
2. pathlib Module
Description: The pathlib module offers an object-oriented approach to file system
paths. It allows easier manipulation of paths and provides a more intuitive syntax.
Common Classes and Methods:
Path: Represents a filesystem path.
Path.exists(): Checks if the path exists.
Path.mkdir(): Creates a new directory.
Path.rmdir(): Removes a directory.
Path.read_text(): Reads the contents of a text file.
Example:
from pathlib import Path
80 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
3. shutil Module
Description: The shutil module provides a higher-level interface for file operations,
particularly for copying and removing files and directories. It simplifies tasks like file
and directory management.
Common Functions:
shutil.copy(src, dst): Copies a file from src to dst.
shutil.move(src, dst): Moves a file or directory from src to dst.
shutil.rmtree(path): Deletes an entire directory tree.
shutil.make_archive(base_name, format, root_dir): Creates a zip or tar archive.
Example:
import shutil
# Copy a file
shutil.copy('source.txt', 'destination.txt')
# Move a directory
shutil.move('old_directory', 'new_directory')
# Remove a directory tree
# shutil.rmtree('directory_to_delete')
4. pandas Library
Description: While primarily a data analysis library, pandas provides powerful tools
for reading from and writing to various file formats, including CSV, Excel, JSON, and
more. It simplifies data manipulation and analysis.
Common Functions:
pandas.read_csv(filepath): Reads a CSV file into a DataFrame.
DataFrame.to_csv(filepath): Writes a DataFrame to a CSV file.
pandas.read_excel(filepath): Reads an Excel file into a DataFrame.
DataFrame.to_excel(filepath): Writes a DataFrame to an Excel file.
Example:
import pandas as pd
# Read a CSV file into a DataFrame
df = pd.read_csv('data.csv')
# Display the first few rows
print(df.head())
# Write DataFrame to a new CSV file
df.to_csv('new_data.csv', index=False)
81 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
Practical Activity 2.5.2: Practicing open and read file
Task:
Practice reading a file in Python, covering how to open a file and check file
permissions.
1. Open a File
To open a file in Python, you use the built-in open() function. This function takes at
least one argument: the path to the file. You can also specify a second argument to
indicate the mode in which you want to open the file.
Common File Modes:
'r': Read (default mode) - Opens a file for reading.
'w': Write - Opens a file for writing (creates a new file or truncates an existing
file).
'a': Append - Opens a file for appending (data will be written at the end).
'b': Binary - Opens a file in binary mode.
't': Text - Opens a file in text mode (default).
Example:
# Open a file for reading
file_path = 'example.txt' # Ensure this file exists before running
try:
with open(file_path, 'r') as file:
content = file.read() # Read the entire file
print(content) # Print the file content
except FileNotFoundError:
print(f"The file {file_path} does not exist.")
except IOError:
print("An error occurred while reading the file.")
82 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
2. Read File Permissions
Before opening a file, you may want to check its permissions to ensure you have the
appropriate access rights. You can use the os module to check file permissions.
Example:
import os
file_path = 'example.txt' # Ensure this file exists
# Check if the file exists
if os.path.exists(file_path):
# Get file permissions
permissions = os.stat(file_path).st_mode
# Check read permission
can_read = bool(permissions & 0o400) # Owner can read
can_write = bool(permissions & 0o200) # Owner can write
can_execute = bool(permissions & 0o100) # Owner can execute
print(f"Read permission: {can_read}")
print(f"Write permission: {can_write}")
print(f"Execute permission: {can_execute}")
else:
print(f"The file {file_path} does not exist.")
Task:
83 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
Key readings 2.5.3 Performing write/create and delete file
try:
with open(file_path, 'w') as file:
file.write("This is a new file created with Python.\n")
print(f"File {file_path} created successfully.")
except IOError:
print("An error occurred while creating the file.")
2. Write to an Existing File
To write to an existing file, you can open it in 'a' (append) or 'w' mode. The 'a' mode
will add content to the end of the file without deleting the current content.
Example:
# Write to an existing file
existing_file_path = 'new_file.txt'
try:
with open(existing_file_path, 'a') as file:
file.write("Appending new content to the existing file.\n")
print(f"Content appended to {existing_file_path} successfully.")
except IOError:
print("An error occurred while writing to the file.")
3. Remove a File
To delete a file, you can use the os.remove() function from the os module.
Example:
import os
# Remove a file
file_to_remove = 'new_file.txt'
try:
os.remove(file_to_remove)
84 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
print(f"File {file_to_remove} deleted successfully.")
except FileNotFoundError:
print(f"The file {file_to_remove} does not exist.")
except PermissionError:
print(f"Permission denied to delete the file {file_to_remove}.")
except Exception as e:
print(f"An error occurred: {e}")
4. Delete a Folder
To delete a folder, you can use os.rmdir() for empty directories or shutil.rmtree() for
directories that contain files.
Example (Deleting an Empty Folder):
# Delete an empty folder
folder_to_remove = 'empty_folder'
try:
os.rmdir(folder_to_remove)
print(f"Folder {folder_to_remove} deleted successfully.")
except FileNotFoundError:
print(f"The folder {folder_to_remove} does not exist.")
except OSError:
print(f"The folder {folder_to_remove} is not empty or cannot be deleted.")
except Exception as e:
print(f"An error occurred: {e}")
Example (Deleting a Non-Empty Folder):
import shutil
try:
shutil.rmtree(non_empty_folder)
print(f"Folder {non_empty_folder} deleted successfully.")
except FileNotFoundError:
print(f"The folder {non_empty_folder} does not exist.")
except Exception as e:
print(f"An error occurred: {e}")
85 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
Practical Activity 2.5.4: Applying python best practices
Task:
Best practices for writing Python code, focusing on readability and style, the use of
built-in features, efficiency and memory usage, and error handling and testing.
1. Readability and Style
PEP 8: Follow the Python Enhancement Proposal (PEP) 8 style guide, which outlines
conventions for writing clean and readable code.
Indentation: Use 4 spaces per indentation level.
Line Length: Limit lines to 79 characters.
Naming Conventions: Use descriptive variable and function names.
Use snake_case for variables and functions, and CamelCase for classes.
Example:
def calculate_area(radius):
"""Calculate the area of a circle given its radius."""
return 3.14 * radius ** 2
Docstrings: Use docstrings to describe the purpose of functions and classes.
This helps others understand your code.
2. Use of Built-in Features
Leverage Built-in Functions: Use Python’s built-in functions and libraries whenever
possible, as they are optimized and thoroughly tested.
Example:
# Instead of manually calculating the sum of a list
numbers = [1, 2, 3, 4, 5]
total = sum(numbers) # Use built-in sum function
86 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
List Comprehensions: Use list comprehensions for creating lists in a concise and
readable way.
Example:
squares = [x ** 2 for x in range(10)] # List comprehension for squares
3. Efficiency and Memory Usage
Use Generators: When working with large datasets, use generators to save memory.
Generators yield items one at a time and do not load everything into memory.
Example:
def generate_numbers(n):
for i in range(n):
yield i * 2
87 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
Example:
import unittest
class TestMathFunctions(unittest.TestCase):
def test_add(self):
self.assertEqual(add(1, 2), 3)
if __name__ == "__main__":
unittest.main()
Summary
By following these best practices, you enhance the quality of your Python code:
Readability and Style: Adhere to PEP 8 guidelines and use meaningful names
and docstrings.
Use of Built-in Features: Take advantage of Python’s built-in functions and
libraries for optimized performance.
Efficiency and Memory Usage: Use generators and avoid unnecessary copies
to manage memory effectively.
Error Handling and Testing: Implement robust error handling and write unit
tests to ensure code reliability.
Points to Remember
● Os used for interacting with the operating system and file system.
● Pathlib used for an object-oriented approach to path manipulation.
● Shutil used for high-level file operations such as copying and moving files.
● Pandas used for reading and writing data in various formats, primarily used for
data analysis.
● Creating a New File: Use open (file_path, 'w') or open(file_path, 'x') to create a
new file.
● Writing to an Existing File: Use open (file_path, 'a') to append or 'w' to overwrite.
● Removing a File: sUse os.remove () to delete a file.
● Deleting a Folder: Use os.rmdir () for empty directories and shutil.rmtree() for
non-empty directories.
88 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
● Adhering to Python best practices can improve code quality, readability, and
maintainability.
● Following PEP 8 guidelines promotes consistent coding style.
● Using built-in features can make code more concise and efficient.
● Writing efficient code can reduce resource consumption.
● Proper error handling can prevent unexpected program failures.
● Testing can help identify and fix bugs early in the development process.
● Regular code reviews can help improve coding practices and catch potential
issues.
89 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
Learning outcome 2 end assessment
Theoretical assessment
90 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
C) dict = (key: value)
D) dict = <key: value>
8. Which function is used to read a CSV file into a DataFrame using pandas?
A) pd.read_csv()
B) pd.load_csv()
C) pd.import_csv()
D) pd.open_csv()
9. What will len([1, 2, 3]) return?
A) 2
B) 3
C) 4
D) None
10. Which of the following is a built-in function in Python?
A) print()
B) show()
C) display()
D) output()
11. In Python, what data type is used to represent True or False values?
A) int
B) float
C) bool
D) str
12. What will the output of the following code?
print("Hello, World!"[7])
A) H
B) e
C) W
D) o
13. Which of the following is NOT a valid way to comment in Python?
A) # This is a comment
B) /* This is a comment */
C) """ This is a comment """
D) #!
14. What does the 'continue' statement do in a loop?
A) Exits the loop
B) Skips to the next iteration
C) Restarts the loop
D) Ends the program
15. Which of the following is used to create a set in Python?
A) []
B) ()
91 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
C) {}
D) <>
16. What is the correct way to define a lambda function in Python?
A) lambda x, y: x + y
B) function x, y: x + y
C) def x, y: x + y
D) x, y -> x + y
17. What is the output of print(type(3.14))?
A) <class 'int'>
B) <class 'float'>
C) <class 'str'>
D) <class 'bool'>
18. Which of the following statements is used to import the os module?
A) import os
B) include os
C) using os
D) require os
19. What will the following code output?
x = 20
if x < 10:
print("Small")
else:
print("Large")
A) Small
B) Large
C) 20
D) None
20. Which method can be used to add an item to a list in Python?
A) add()
B) append()
C) insert()
D) Both B and C
II.Complete thefollowing statements by correct word, operator, or keword from the listed
ones :
(function, ==, loop,lambda, os, defaultdict, break, tuple, open, dictionary)
1. A ________ is a block of reusable code that performs a specific task in Python.
2. The __________ operator is used to compare two values for equality.
3. In Python, a __________ allows you to iterate over a sequence.
4. A __________ function can take any number of arguments but can only have one
expression.
92 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
5. The __________ module provides a way to use operating system-dependent
functionality in Python.
6. A __________ is a dictionary subclass that provides a default value for a non-existent
key.
7. The __________ statement is used to exit the nearest enclosing loop in Python.
8. A __________ is an immutable collection that can hold a variety of object types.
9. The __________ function is used to read the contents of a text file.
10. A __________ is a collection of key-value pairs where keys must be unique.
i. Respond to the followings by True or False
1. A list in Python is immutable.
2. A function in Python can return multiple values.
3. The 'else' clause can be used with a 'for' loop.
4. The pandas library is primarily used for file handling.
5. Sets in Python can contain duplicate elements.
6. The 'pass' statement in Python does nothing when executed.
7. You can use the 'with' statement for file handling in Python.
8. A frozen set is a mutable version of a set.
9. The 'elif' keyword is used to check multiple conditions in Python.
10. Variables in Python do not require a declaration before use.
III.Match the following Python data types with their corresponding descriptions:
ANSWER Data Type Description
Practical assessment
93 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
References
James, G., Wi en, D., Has e, T., & Tibshirani, R. (2017). An Introduction to Statistical Learning:
with Applications in R. Springer
LazyProgrammer. (2016). Deep Learning: Recurrent Neural Networks in Python: LSTM, GRU,
and more RNN machine learning architectures in Python and Theano (Machine Learning in
Python).
Mar n, K., Hi mana, E., Ngabonziza, J., Hanyurwimfura, D., Musabe, R., Uwamahoro, A., . . .
Mutonga, K. (2023). Crop Yield Prediction Using Machine Learning Models: Case of Irish
Potato and Maize. Agriculture, 20.
Moolayil, J. J. (2019). Learn Keras for Deep Neural Networks: A Fast-Track Approach to
Modern Deep Learning with Python.
Morgan, P. (2018). Data Analysis from Scratch With Python: Beginner Guide, Pandas,
NumPy, Scikit-Learn, IPython, TensorFlow, and Matplotlib.
Russell, R. (2018). Machine Learning: Step-by-Step Guide To Implement Machine Learning
Algorithms with Python.
Sarkar, D., Raghav, B., & Tushar, S. (2017). Practical Machine Learning with Python: A
Problem-Solver’s Guide to Building Real-World Intelligent Systems.
94 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
Learning Outcome 3: Apply Object-Driven In Python
95 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
Indicative contents
3.1 Applying OOP Concepts
3.2 Applying python Date and time concepts
3.3 Applying Python Libraries
3.4 Applying system Automation
96 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
Duration: 20 hrs
Resources
97 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
Indicative content 3.1: Applying OOP Concepts
Duration: 5 hrs
Tasks:
1: You are requested to answer the following questions related to the introduction to Object
Oriented Programming:
Describe the following terms as applied in OOP:
i. Object
ii. Python class
iii. Inheritance
iv. Polymorphism
v. Encapsulation
2: Write your findings on paper/flipchart
3: Present your findings to the whole class or trainer
4: For more clarification read key reading 3.1.1 and ask questions where necessary.
class MyClass:
x=5
Create Object
Now we can use the class named MyClass to create objects:
Example
Create an object named p1, and print the value of x:
p1 = MyClass()
print(p1.x)
The __init__() Function
98 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
The examples above are classes and objects in their simplest form, and are not
really useful in real life applications.
99 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
class Animal:
def speak(self):
return "Animal speaks"
class Dog(Animal):
def speak(self):
return "Bark"
dog = Dog()
print(dog.speak()) # Output: Bark
class Swimmer:
def swim(self):
return "Swimming"
duck = Duck()
print(duck.fly()) # Output: Flying
print(duck.swim()) # Output: Swimming
class Dog(Animal):
def bark(self):
return "Bark"
class Puppy(Dog):
100 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
def weep(self):
return "Wee wee"
puppy = Puppy()
print(puppy.speak()) # Output: Animal speaks
print(puppy.bark()) # Output: Bark
class Circle(Shape):
def area(self):
return "Area of Circle"
class Square(Shape):
def area(self):
return "Area of Square"
circle = Circle()
square = Square()
print(circle.area()) # Output: Area of Circle
print(square.area()) # Output: Area of Square
4. Polymorphism
4.1. Definition
Polymorphism in Python is a core concept in object-oriented programming that
allows objects of different classes to be treated as objects of a common superclass. It
enables methods to do different things based on the object it is acting upon, even if
they share the same name.
4.2. Types of Polymorphism
Method Overriding: A subclass can provide a specific implementation of a method
that is already defined in its superclass.
class Animal:
def sound(self):
return "Some sound"
class Dog(Animal):
def sound(self):
101 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
return "Bark"
class Cat(Animal):
def sound(self):
return "Meow"
def make_sound(animal):
print(animal.sound())
class Airplane:
def fly(self):
return "Jetting through the sky"
def let_it_fly(flyable):
print(flyable.fly())
102 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
state of the object and to control how data is accessed and modified. Encapsulation
promotes modularity and helps maintain the integrity of the data within an object.
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner # Public attribute
self.__balance = balance # Private attribute
103 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
def get_balance(self):
return self.__balance
# Usage
account = BankAccount("Alice", 100)
account.deposit(50) # Deposited: 50
print(account.get_balance()) # Output: 150
account.withdraw(30) # Withdrew: 30
print(account.get_balance()) # Output: 120
Task:
104 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
Example: Car Class
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
def display_info(self):
return f"{self.year} {self.make} {self.model}"
# Creating an object of the Car class
my_car = Car("Toyota", "Corolla", 2020)
print(my_car.display_info()) # Output: 2020 Toyota Corolla
2.2. Encapsulation
Classes can encapsulate data and provide controlled access through methods.
Example: Bank Account
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.__balance = balance # Private attribute
def deposit(self, amount):
if amount > 0:
self.__balance += amount
def withdraw(self, amount):
if 0 < amount <= self.__balance:
self.__balance -= amount
def get_balance(self):
return self.__balance
# Creating a bank account object
account = BankAccount("Alice", 100)
account.deposit(50)
print(account.get_balance()) # Output: 150
2.3. Inheritance
Classes can inherit attributes and methods from other classes, promoting code reuse.
Example: Employee and Manager Classes
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
def display_info(self):
return f"Employee: {self.name}, Salary: {self.salary}"
105 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
class Manager(Employee):
def __init__(self, name, salary, department):
super().__init__(name, salary)
self.department = department
def display_info(self):
return f"Manager: {self.name}, Salary: {self.salary}, Department:
{self.department}"
# Creating objects
emp = Employee("John", 50000)
mgr = Manager("Alice", 70000, "HR")
print(emp.display_info()) # Output: Employee: John, Salary: 50000
print(mgr.display_info()) # Output: Manager: Alice, Salary: 70000,
Department: HR
2.4. Polymorphism
Classes can define methods with the same name, allowing different behaviors based
on the object type.
Example: Shape Class
class Shape:
def area(self):
pass
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * (self.radius ** 2)
# Function to calculate area
def print_area(shape):
print(f"Area: {shape.area()}")
# Creating objects
rect = Rectangle(10, 5)
circle = Circle(7)
print_area(rect) # Output: Area: 50
print_area(circle) # Output: Area: 153.86
106 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
2.5. Creating Frameworks and Libraries
Classes allow for the creation of modular code that can be reused across different
projects.
Example: Simple Web Framework
class WebApp:
def __init__(self, name):
self.name = name
self.routes = {}
def route(self, path):
def wrapper(func):
self.routes[path] = func
return func
return wrapper
def run(self):
for path, func in self.routes.items():
print(f"Route: {path}, Response: {func()}")
# Creating a web app object
app = WebApp("MyApp")
@app.route("/")
def home():
return "Welcome to the homepage!"
@app.route("/about")
def about():
return "This is the about page."
# Running the web app
app.run()
# Output:
# Route: /, Response: Welcome to the homepage!
# Route: /about, Response: This is the about page.
Sample program of simple calculator in python that can perform simple calculation:
class Calculator:
def add(self, a, b):
return a + b
107 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
return a * b
108 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
Practical Activity 3.1.3: Applying inheritance in python
Task:
109 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
Example: Basic Shapes
class Shape:
def area(self):
pass
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * (self.radius ** 2)
# Using the classes
shapes = [Rectangle(10, 5), Circle(7)]
for shape in shapes:
print(f"Area: {shape.area()}")
2. Method Overriding
Subclasses can provide specific implementations of methods defined in their
superclasses.
Example: Employees
class Employee:
def calculate_salary(self):
return 50000
class Manager(Employee):
def calculate_salary(self):
return super().calculate_salary() + 20000 # Base salary + bonus
class Developer(Employee):
def calculate_salary(self):
return super().calculate_salary() + 10000 # Base salary + bonus
# Using the classes
employees = [Manager(), Developer()]
for emp in employees:
print(f"Salary: {emp.calculate_salary()}")
110 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
Inheritance allows the creation of a hierarchy where subclasses can inherit from a
common superclass.
Example: Animal Kingdom
class Animal:
def speak(self):
return "Some sound"
class Dog(Animal):
def speak(self):
return "Bark"
class Cat(Animal):
def speak(self):
return "Meow"
# Using the classes
animals = [Dog(), Cat()]
for animal in animals:
print(animal.speak())
4. Multiple Inheritance
Python supports multiple inheritance, allowing a subclass to inherit from multiple
superclasses.
Example: Vehicles
class Flyer:
def fly(self):
return "Flying"
class Swimmer:
def swim(self):
return "Swimming"
class Duck(Flyer, Swimmer):
def quack(self):
return "Quack!"
# Using the class
duck = Duck()
print(duck.fly()) # Output: Flying
print(duck.swim()) # Output: Swimming
print(duck.quack()) # Output: Quack!
111 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
class Widget:
def draw(self):
pass
class Button(Widget):
def draw(self):
return "Drawing a button"
class TextBox(Widget):
def draw(self):
return "Drawing a text box"
# Using the classes
widgets = [Button(), TextBox()]
for widget in widgets:
print(widget.draw())
112 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
self.interest_rate = interest_rate
def apply_interest(self):
# Apply interest to the current balance
interest = self.balance * self.interest_rate
self.balance += interest
return f"Interest applied. New balance: {self.balance}"
113 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
# Creating an object of the appropriate account class
if account_type == 'savings':
account = SavingsAccount(owner, initial_balance)
elif account_type == 'checking':
account = CheckingAccount(owner, initial_balance)
else:
print("Invalid account type. Defaulting to BankAccount.")
account = BankAccount(owner, initial_balance)
# User operations
while True:
action = input("Do you want to deposit, withdraw, or apply
interest? (d/w/i/q): ").lower()
if action == 'd':
amount = float(input("Enter amount to deposit: "))
print(account.deposit(amount))
elif action == 'w':
amount = float(input("Enter amount to withdraw: "))
print(account.withdraw(amount))
elif action == 'i' and isinstance(account, SavingsAccount):
print(account.apply_interest())
elif action == 'q':
break
else:
print("Invalid option. Please try again.")
Output of the program
114 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
Practical Activity 3.1.4: Applying polymorphism in python
Task:
def area(self):
return self.width * self.height
class Circle(Shape):
def __init__(self, radius):
115 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
self.radius = radius
def area(self):
return 3.14 * (self.radius ** 2)
# Using polymorphism
shapes = [Rectangle(10, 5), Circle(7)]
for shape in shapes:
print(f"Area: {shape.area()}")
class Airplane:
def fly(self):
return "Jetting through the sky"
def let_it_fly(flyable):
print(flyable.fly())
# Using duck typing
let_it_fly(Bird()) # Output: Flapping wings
let_it_fly(Airplane()) # Output: Jetting through the sky
116 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
v1 = Vector(2, 3)
v2 = Vector(5, 7)
result = v1 + v2
print(result) # Output: Vector(7, 10)
117 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
from datetime import datetime
class Book:
def __init__(self, title, author):
self.title = title
self.author = author
self.is_borrowed = False
self.borrower_name = None
self.department = None
self.rent_date = None
self.return_date = None
def borrow(self, borrower_name, department, rent_date, return_date):
if not self.is_borrowed:
self.is_borrowed = True
self.borrower_name = borrower_name
self.department = department
self.rent_date = rent_date
self.return_date = return_date
return f"You have borrowed '{self.title}' by {self.author}."
return f"'{self.title}' is already borrowed."
def return_book(self):
if self.is_borrowed:
self.is_borrowed = False
details = f"Returned '{self.title}' by {self.author}."
self.borrower_name = None
self.department = None
self.rent_date = None
self.return_date = None
return details
return f"'{self.title}' was not borrowed."
def get_borrow_info(self):
if self.is_borrowed:
return (f"Borrower: {self.borrower_name}, "
f"Department: {self.department}, "
f"Rent Date: {self.rent_date}, "
f"Return Date: {self.return_date}")
return "This book is not currently borrowed."
# User input for book details
title = input("Enter the book title: ")
author = input("Enter the author's name: ")
118 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
# Creating an object of the Book class
book1 = Book(title, author)
# User actions
while True:
action = input("Do you want to borrow or return the book? (b/r/q): ").lower()
if action == 'b':
borrower_name = input("Enter your name: ")
department = input("Enter your department: ")
rent_date = input("Enter rent date (YYYY-MM-DD): ")
return_date = input("Enter return date (YYYY-MM-DD): ")
# Validating date format
try:
rent_date = datetime.strptime(rent_date, '%Y-%m-%d').date()
return_date = datetime.strptime(return_date, '%Y-%m-%d').date()
print(book1.borrow(borrower_name, department, rent_date, return_date))
except ValueError:
print("Invalid date format. Please enter dates in YYYY-MM-DD format.")
elif action == 'r':
print(book1.return_book())
elif action == 'info':
print(book1.get_borrow_info())
elif action == 'q':
break
else:
print("Invalid option. Please try again.")
Program output
119 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
Practical Activity 3.1.5: Applying Encapsulation in python
Task:
1. Introduction
Encapsulation in Python is a fundamental object-oriented programming principle
that restricts direct access to certain attributes and methods of a class. This approach
is used to protect the internal state of an object and to control how data is accessed
and modified.
2. Common applications of encapsulation in Python
Here are some common applications of encapsulation in Python, along with
examples.
2.1. Data Hiding
Encapsulation helps in hiding the internal state of an object from the outside world,
ensuring that only specified methods can modify it. This prevents unintended
interference and misuse.
Example: Bank Account
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.__balance = balance # Private attribute
def deposit(self, amount):
if amount > 0:
self.__balance += amount
else:
120 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
print("Deposit amount must be positive.")
def get_salary(self):
return self.__salary
# Usage
emp = Employee("John", 50000)
print(emp.get_salary()) # Output: 50000
emp.set_salary(-1000) # Output: Salary must be positive.
emp.set_salary(60000)
print(emp.get_salary()) # Output: 60000
121 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
2.3. Implementation Hiding
Encapsulation allows for changes in the internal implementation of a class without
affecting external code that relies on it. This makes the code easier to maintain and
evolve.
Example: Temperature Converter
class Temperature:
def __init__(self, celsius):
self.__celsius = celsius # Private attribute
def to_fahrenheit(self):
return (self.__celsius * 9/5) + 32
def to_kelvin(self):
return self.__celsius + 273.15
# Usage
temp = Temperature(25)
print(temp.to_fahrenheit()) # Output: 77.0
print(temp.to_kelvin()) # Output: 298.15
2.4. API Design
Encapsulation is vital in designing APIs, where you can expose a clean interface while
hiding the underlying complexity.
2.5. Security
Encapsulation enhances security by restricting access to sensitive data. This is
particularly important in applications handling confidential information.
Example: User Credentials
class User:
def __init__(self, username, password):
122 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
self.username = username
self.__password = password # Private attribute
def authenticate(self, password):
return self.__password == password
# Usage
user = User("Alice", "securepassword")
print(user.authenticate("securepassword")) # Output: True
print(user.authenticate("wrongpassword")) # Output: False
Points to Remember
123 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
● Polymorphism in Python is a powerful feature that allows different classes to be
treated as instances of the same class through a common interface.
● Polymorphism can be applied in different ways including: Method Overriding,
Duck Typing, Operator Overloading, Function Overloading and Frameworks and
Libraries
● Encapsulation in Python is a fundamental object-oriented programming principle
that restricts direct access to certain attributes and methods of a class.
● Encapsulation can be used in different ways including: Data Hiding, Controlled
Access, Implementation Hiding, API Design and Security
124 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
Indicative content 3.2: Applying python Date and Time Concepts
Duration: 5 hrs
Tasks:
1. You are requested to describe the following date and time concepts in python
programming:
i. Datetime
ii. Dateutil
iii. Arrow
iv. Pendulum
v. Python-tzdata
2. Write your findings on paper/flipchart
3. Present your findings to the whole class or trainer
4. For more clarification read key reading 3.2.1 and ask questions where necessary.
Key Classes
datetime: Combines date and time into a single object.
date: Represents a date (year, month, day).
time: Represents a time (hour, minute, second, microsecond).
timedelta: Represents the difference between two dates or times.
Example:
from datetime import datetime, timedelta
# Current date and time
now = datetime.now()
print("Current date and time:", now)
# Creating a specific date
new_year = datetime(2024, 1, 1)
print("New Year:", new_year)
# Date arithmetic
125 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
tomorrow = now + timedelta(days=1)
print("Tomorrow:", tomorrow)
2. Dateutil
dateutil is a powerful extension to the standard datetime module. It provides
additional features for parsing, formatting, and manipulating dates and times.
Key Features
Powerful parsing of dates using parse().
Support for relative deltas (e.g., adding months, years).
Time zone handling.
Example:
from dateutil import parser, relativedelta
from datetime import datetime
# Parsing a date string
date_str = "2024-01-01T12:00:00"
parsed_date = parser.parse(date_str)
print("Parsed Date:", parsed_date)
# Adding months
new_date = parsed_date + relativedelta.relativedelta(months=1)
print("One month later:", new_date)
3. Arrow
Arrow is a library that provides a more intuitive way to work with dates and times. It
is designed for better readability and easier manipulation.
Key Features
Easy timezone handling.
Human-friendly formatting.
Natural language support.
Example:
import arrow
# Current time
now = arrow.now()
print("Current time:", now)
# Shift time
shifted = now.shift(days=3)
print("Three days later:", shifted)
# Formatting
formatted = now.format('YYYY-MM-DD HH:mm:ss')
print("Formatted:", formatted)
4. Pendulum
126 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
Pendulum is another library for date and time manipulation that focuses on simplicity
and flexibility. It includes features for working with time zones, durations, and
intervals.
Key Features:
UTC and local time zone support.
Duration and period handling.
Human-friendly methods for manipulating dates.
Example:
import pendulum
# Current time
now = pendulum.now()
print("Current time:", now)
# Adding time
future = now.add(days=7)
print("One week later:", future)
# Time zone support
utc_time = pendulum.now('UTC')
local_time = utc_time.in_tz('America/New_York')
print("Local time:", local_time)
5. Python-tzdata
python-tzdata is a library that provides the IANA Time Zone Database, making it
easier to handle time zones in Python applications. It is often used in combination
with datetime or other date libraries.
Key Features:
Access to time zone data for accurate conversions.
Works well with pytz for timezone-aware datetime objects.
Example:
import pytz
from datetime import datetime
# Time zone conversion
utc_zone = pytz.utc
new_york_zone = pytz.timezone('America/New_York')
# Current time in UTC
utc_time = datetime.now(utc_zone)
print("Current UTC time:", utc_time)
# Convert to New York time
ny_time = utc_time.astimezone(new_york_zone)
print("New York time:", ny_time)
127 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
Practical Activity 3.2.2: Applying python Date and time
Task:
1. Python Dates
A date in Python is not a data type of its own, but we can import a module named
datetime to work with dates as date objects.
Example
Import the datetime module and display the current date:
import datetime
x = datetime.datetime.now()
print(x)
128 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
The datetime() class requires three parameters to create a date: year, month, day.
Example
Create a date object:
import datetime
x = datetime.datetime(2020, 5, 17)
print(x)
The datetime() class also takes parameters for time and timezone (hour, minute,
second, microsecond, tzone), but they are optional, and has a default value of 0,
(None for timezone).
The strftime() Method
The datetime object has a method for formatting date objects into readable strings.
The method is called strftime(), and takes one parameter, format, to specify the
format of the returned string:
Example
Display the name of the month:
import datetime
x = datetime.datetime(2018, 6, 1)
print(x.strftime("%B"))
129 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
name, full x = datetime.datetime.now() er
version print(x.strftime("%B"))
%m Month as a import datetime 12
number 01- x = datetime.datetime.now()
12 print(x.strftime("%m"))
%y Year, short import datetime 18
version, x = datetime.datetime.now()
without print(x.strftime("%y"))
century
%Y Year, full import datetime 2018
version x = datetime.datetime.now()
print(x.strftime("%Y"))
%H Hour 00-23 import datetime 17
x = datetime.datetime.now()
print(x.strftime("%H"))
%p AM/PM import datetime PM
x = datetime.datetime.now()
print(x.strftime("%p"))
%x Local version import datetime 12/31/1
of date x = datetime.datetime.now() 8
print(x.strftime("%x"))
Setting Time Zones
To work with time zones, you can use the pytz library, which provides access to the
IANA time zone database.
Example:
from datetime import datetime
import pytz
# Define time zones
utc_zone = pytz.utc
new_york_zone = pytz.timezone('America/New_York')
130 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
print("Current New York time:", ny_now)
131 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
# Using relativedelta from dateutil for more complex
operations
from dateutil.relativedelta import relativedelta
# Adding months and years
next_month = now + relativedelta(months=1)
print("Next month:", next_month)
next_year = now + relativedelta(years=1)
print("Next year:", next_year)
Points to Remember
● Python provides robust support for date and time manipulation through its built-
in datetime module and several powerful third-party libraries like dateutil, Arrow,
Pendulum, and python-tzdata.
● The datetime module is part of the standard library and provides classes for
manipulating dates and times. It includes functionalities for creating, formatting,
and performing arithmetic on dates and times.
● Dateutil is a powerful extension of the datetime module that provides additional
features, such as parsing dates from strings and handling time zones. It simplifies
date manipulation with utilities for relative deltas, recurrence rules, and more.
● Arrow is a lightweight library that simplifies working with dates and times in
Python. It provides an intuitive API for creating, formatting, and converting dates,
along with built-in timezone handling and human-friendly features.
● Pendulum is a robust datetime library that extends datetime with advanced
features like duration calculations, timezone conversions, and natural language
support. It offers immutable instances, making it easier to work with dates and
times without side effects.
● python-tzdata is a package that provides the IANA time zone database for Python
applications. It allows for accurate timezone conversions and offsets, ensuring
applications handle date and time correctly across different regions.
● In Python, you can effectively manage time zones using pytz, format and parse
dates using strftime and strptime, and perform arithmetic with dates using
timedelta and relativedelta.
132 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
Application of learning 3.2.
As full stack developer you are asked to develop a python program that can be used while
calculating the age of students in order to know if they are allowed to take national id card
depending on entered age and the current date.
The program has to tell user if the entered student is allowed or not.
133 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
Indicative content 3.3: Applying Python Libraries
Duration: 5 hrs
Tasks:
134 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
Support for a wide variety of plots (line, scatter, bar, histogram, etc.).
Extensive customization options (colors, labels, fonts).
Integration with Jupyter notebooks for interactive plotting.
Example:
import matplotlib.pyplot as plt
import numpy as np
# Data
x = np.linspace(0, 10, 100)
y = np.sin(x)
# Plot
plt.plot(x, y)
plt.title("Sine Wave")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.grid(True)
plt.show()
4. NumPy
Description: NumPy (Numerical Python) is a library for numerical computing in
Python. It provides support for arrays, matrices, and a wide range of mathematical
functions to operate on these data structures.
Key Features:
N-dimensional arrays (ndarray) for efficient storage and manipulation.
Mathematical functions for linear algebra, statistical analysis, and more.
Broadcasting capabilities for arithmetic operations on arrays of different
shapes.
Example:
import numpy as np
# Creating an array
arr = np.array([[1, 2, 3], [4, 5, 6]])
# Basic operations
print("Array:\n", arr)
print("Sum:", np.sum(arr))
print("Mean:", np.mean(arr))
print("Transpose:\n", arr.T)
135 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
5. Pandas
Description: Pandas is a powerful data manipulation and analysis library built on top
of NumPy. It provides data structures like Series and DataFrame to handle labeled
data efficiently.
Key Features:
# Creating a DataFrame
data = {
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'City': ['New York', 'Los Angeles', 'Chicago']
}
df = pd.DataFrame(data)
# DataFrame operations
print("DataFrame:\n", df)
print("Mean Age:", df['Age'].mean())
print("Filtered:\n", df[df['Age'] > 28])
Task:
136 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
Key readings 3.3.2 Using python libraries
1. Importing Libraries
To use any library in Python, you need to import it. This is typically done at the
beginning of your script or notebook.
Example of Importing Libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
numpy is imported as np for brevity.
pandas is imported as pd.
matplotlib.pyplot is imported as plt.
2. Accessing Functionality
NumPy
NumPy provides a powerful array object and a range of functions for numerical
operations.
Example:
# Create a NumPy array
array = np.array([1, 2, 3, 4, 5])
# Basic operations
mean_value = np.mean(array)
sum_value = np.sum(array)
print("Array:", array)
print("Mean:", mean_value)
print("Sum:", sum_value)
Pandas
Pandas is used for data manipulation and analysis, primarily with its DataFrame
structure.
Example:
# Create a DataFrame
data = {
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35]
}
df = pd.DataFrame(data)
# Accessing DataFrame functionalities
mean_age = df['Age'].mean()
filtered_df = df[df['Age'] > 28]
print("DataFrame:\n", df)
print("Mean Age:", mean_age)
137 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
print("Filtered DataFrame:\n", filtered_df)
Matplotlib
Matplotlib is used for creating static, animated, and interactive visualizations.
Example:
# Simple plot using Matplotlib
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.plot(x, y)
plt.title("Sine Wave")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.grid(True)
plt.show()
3. Understanding Scope According to the Namespace
In Python, a namespace is a container that holds a set of identifiers (names) and
ensures that all names are unique within that namespace. When you import
libraries, their functions and classes are accessible within the current namespace.
Example of Scope and Namespace
# Importing libraries
import numpy as np
import pandas as pd
# Defining a function that uses NumPy
def calculate_statistics(data):
mean = np.mean(data)
return mean
# Using the function
data_array = np.array([1, 2, 3, 4, 5])
mean_value = calculate_statistics(data_array)
print("Mean Value:", mean_value)
# Accessing a Pandas function directly
df = pd.DataFrame({'A': [1, 2, 3]})
print("DataFrame:\n", df)
Scope Considerations
Global Scope: Functions and variables defined outside any function have a
global scope and can be accessed anywhere in the file.
Local Scope: Variables defined inside a function are local to that function and
cannot be accessed outside of it.
Namespace Access: When you import libraries, you access their functions
using the specified alias (like np for NumPy). If you try to access a function
without the alias, you will get a NameError.
138 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
Example of Scope Errors
# Attempting to access a function without the namespace
try:
np.mean([1, 2, 3]) # Correct usage
mean([1, 2, 3]) # Incorrect, will raise NameError
except NameError as e:
print(e) # Output: name 'mean' is not defined
Points to Remember
● The Python Standard Library provides a robust foundation for programming tasks,
while libraries like Matplotlib, NumPy, and Pandas significantly enhance Python's
capabilities in data visualization, numerical computing, and data analysis.
Together, these libraries make Python a powerful tool for scientific computing,
data analysis, and more.
● To use any library in Python, you need to import it. This is typically done at the
beginning of your script or notebook.
● NumPy provides a powerful array object and a range of functions for numerical
operations.
● Pandas is used for data manipulation and analysis, primarily with its DataFrame
structure.
● Matplotlib is used for creating static, animated, and interactive visualizations.
139 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
Indicative content 3.4: Applying System Automation
Duration: 5 hrs
140 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
Examples: data backups, report generation, and code deployments.
2.2. Time-Consuming
Tasks that take a significant amount of manual time.
Examples: manual data entry, resource provisioning, and batch processing.
2.3. Error-Prone
Tasks that are susceptible to human error, leading to inconsistencies or failures.
Examples: manual configuration updates, data migrations, and testing processes.
2.4. Critical for Deployment Speed
Tasks that impact the speed and efficiency of the deployment pipeline.
Examples: automated testing and deployment scripts that need to be executed
quickly to reduce downtime.
Task:
141 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
Easy to define tasks in Python code.
Supports task parallelism.
Use Cases:
Deploying applications to remote servers.
Running administrative commands across multiple servers.
Considerations:
Best for small to medium-scale deployments.
Requires familiarity with SSH.
2. Ansible
Ansible is a powerful automation tool for configuration management, application
deployment, and orchestration, using a simple YAML syntax.
Key Features:
Agentless architecture.
Extensive module library for various tasks.
Strong community and enterprise support.
Use Cases:
Automating configuration management.
Orchestrating complex deployments across multiple environments.
Considerations:
Requires YAML knowledge.
More suited for larger environments with complex setups.
3. SaltStack
SaltStack is a configuration management and orchestration tool that allows for real-
time automation and monitoring.
Key Features:
Event-driven automation.
High scalability with a master-minion architecture.
Supports a wide range of operating systems.
Use Cases
Managing large infrastructures.
Real-time monitoring and automation.
Considerations:
More complex setup compared to other tools.
Best for environments requiring real-time updates.
4. Boto3
Boto3 is the Amazon Web Services (AWS) SDK for Python, allowing Python developers
to write software that makes use of AWS services.
Key Features:
Comprehensive access to AWS services.
Simple and intuitive API.
142 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
Supports resource management and automation.
Use Cases:
Automating AWS resource provisioning.
Managing AWS services like S3, EC2, and Lambda.
Considerations:
Specific to AWS environments.
Requires understanding of AWS services.
5. vSphere Automation SDK for Python
This SDK provides a Python client for automating VMware vSphere environments,
enabling easy interaction with vSphere APIs.
Key Features:
Access to vSphere APIs for managing virtualized environments.
Supports operations such as VM lifecycle management, networking, and
storage.
Use Cases:
Automating VM provisioning and management.
Integrating with existing VMware workflows.
Considerations:
Best suited for organizations using VMware vSphere.
Requires familiarity with VMware's architecture and APIs.
Factors to Consider
Ease of Use
How easy is it to get started with the library?
Does it require extensive setup or configuration?
Community Support
Is there a strong community or documentation available?
Are there frequent updates and active maintenance?
Features
Does the library provide the necessary features for your specific automation
tasks?
How well does it integrate with other tools or environments?
Scalability
Can the library handle the scale of your infrastructure?
Is it suitable for both small and large environments?
Specific Use Cases
Does the library cater to your specific needs (e.g., cloud automation,
configuration management)?
Are there any dependencies on certain platforms or services?
143 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
Practical Activity 3.4.3: Developing python script
Task:
1. Introduction
Developing a Python script that demonstrates the use of library functions, logical
structuring, and logging. For this example, we'll create a script that automates the
deployment of a simple web application using Fabric for SSH tasks, alongside
logging to track its operations.
Example Script: Web Application Deployment
2. Install Required Library
Ensure you have Fabric installed. You can install it using pip:
pip install fabric
3. Script Structure
The script will:
Connect to a remote server.
Upload application files.
Restart the web server.
Log the deployment process.
4. Python Script
import logging
from fabric import Connection
# Set up logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler("deployment.log"),
logging.StreamHandler()
]
144 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
)
# Define the deployment function
def deploy_application(host, user, app_path, remote_path):
try:
logging.info("Starting deployment to %s", host)
# Create a connection to the remote server
with Connection(host=host, user=user) as conn:
logging.info("Connected to %s", host)
# Upload application files
logging.info("Uploading files from %s to %s", app_path, remote_path)
conn.put(app_path, remote=remote_path)
# Restart the web server
logging.info("Restarting the web server")
conn.run("sudo systemctl restart apache2") # Change this command
based on your web server
logging.info("Deployment completed successfully to %s", host)
except Exception as e:
logging.error("Deployment failed: %s", e)
# Main execution
if __name__ == "__main__":
# Configuration
HOST = "your_remote_server_ip"
USER = "your_username"
APP_PATH = "./path_to_your_application/*" # Local path to your application
files
REMOTE_PATH = "/var/www/html" # Remote path where files will be
deployed
deploy_application(HOST, USER, APP_PATH, REMOTE_PATH)
Breakdown of the Script
5. Logging Setup
The logging module is configured to log messages to both a file (deployment.log)
and the console.
Log levels (INFO, ERROR) help track the flow and any issues.
6. Function Definition
The deploy_application function handles the deployment process.
It connects to the remote server using Fabric, uploads files, and restarts the web
server.
Each step is logged for transparency and debugging.
7. Main Execution Block
145 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
The script's entry point sets configuration variables (host, user, app paths).
It calls the deploy_application function with these variables.
Conclusion
This Python script demonstrates how to use library functions from Fabric, structure
code logically, and implement logging for tracking operations. Adjust the server
commands and paths according to your specific needs to make it functional in your
environment.
Task:
146 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
Example in a Shell Script:
# After deployment commands
echo "Deployment completed successfully."
python3 deploy_script.py
Step3 : Integration with CI/CD Pipelines
Integrate the Python script into your CI/CD pipeline using tools like Jenkins, GitHub
Actions, or GitLab CI. You can add a step in your pipeline configuration file to run the
script.
Example for GitHub Actions:
name: Deploy Application
on:
push:
branches:
- main
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v2
- name: Deploy application
run: |
# Your deployment commands here
- name: Run deployment script
run: python3 deploy_script.py
Step 4 : Scheduled Execution at Specific Intervals
You can schedule the execution of the script using cron jobs on Linux or Task
Scheduler on Windows.
Example of a Cron Job:
# Open crontab
crontab -e
# Schedule the script to run daily at midnight
0 0 * * * /usr/bin/python3 /path/to/deploy_script.py
2. Implement Security Measures
To ensure that sensitive information is protected and access to the script is
controlled, consider the following measures:
a. Restrict Script Access
File Permissions: Set appropriate file permissions to restrict access to the script.
chmod 700 deploy_script.py # Only the owner can read, write, and execute
User Roles: Limit access to the script to specific user roles that need to execute it.
147 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
b. Environment Variables for Sensitive Information
Store sensitive information (like passwords, API keys) in environment variables
instead of hardcoding them in the script.
Example:
import os
DB_PASSWORD = os.getenv('DB_PASSWORD')
You can set the environment variables in your shell or CI/CD pipeline
configuration.
c. Use Secrets Management Tools
Utilize secrets management tools like HashiCorp Vault, AWS Secrets Manager, or
Azure Key Vault to store and manage sensitive information securely.
Example Using AWS Secrets Manager:
import boto3
# Load secret
def get_secret():
client = boto3.client('secretsmanager')
secret_value = client.get_secret_value(SecretId='my_secret_id')
return secret_value['SecretString']
Conclusion
Integrating your Python script into the deployment process can enhance automation
and efficiency. By triggering the script post-deployment, integrating it into CI/CD
pipelines, scheduling it, and implementing robust security measures, you can ensure
a smooth and secure deployment workflow. Always prioritize securing sensitive
information and controlling access to your automation scripts.
Task:
148 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
Key readings 3.4.5 Testing and monitoring the automated tasks
Approach to testing and monitoring your Python automation scripts, ensuring they
operate effectively and efficiently.
1. Thorough Testing
To ensure your automation script functions as intended, implement various testing
strategies:
a. Unit Testing
Write unit tests for individual functions within your script using the unittest or pytest
frameworks.
Example:
import unittest
from your_script import deploy_application # Import your function
class TestDeployment(unittest.TestCase):
def test_deploy_application(self):
# Mock parameters
host = "test_host"
user = "test_user"
app_path = "test_path"
remote_path = "test_remote_path"
# Call the function and assert expected results
result = deploy_application(host, user, app_path, remote_path)
self.assertIsNone(result) # Assuming the function returns None on success
if __name__ == "__main__":
unittest.main()
b. Integration Testing
Test the script in a staging environment that mimics production. This will help
identify issues in the interaction between components.
Example:
Deploy to a staging server and run the script, verifying that all steps complete
successfully and the application behaves as expected.
c. End-to-End Testing
Conduct end-to-end tests that cover the entire deployment process, from code
commit to deployment.
2. Monitor Script Logs Execution
Monitoring is crucial for identifying issues and ensuring smooth operation.
Implement logging and monitoring practices:
a. Logging
Use Python’s built-in logging module to record important events, errors, and
execution flow.
149 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
Example:
import logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler("deployment.log"),
logging.StreamHandler()
]
)
# Log an example message
logging.info("Starting deployment...")
b. Log Monitoring
Use log monitoring tools like ELK Stack (Elasticsearch, Logstash, Kibana), Splunk, or
Papertrail to analyze logs in real-time.
Set up alerts for errors or critical warnings in your logs.
4. Refine and Improve
Continuous improvement is key to maintaining a robust automation script:
a. Code Review
Regularly review the code for improvements, ensuring it adheres to best practices.
Peer reviews can help catch potential issues and provide feedback for enhancements.
b. Performance Monitoring
Analyze the script’s performance, noting execution time and resource usage.
Use profiling tools like cProfile to identify bottlenecks.
Example:
import cProfile
def main():
# Your main deployment function
deploy_application(...)
cProfile.run('main()')
c. Feedback Loop
Collect feedback from users or stakeholders regarding the deployment process.
Identify pain points or areas that require improvement.
d. Regular Updates
Keep dependencies up to date and review the latest features or improvements in
libraries used.
Regularly test the script against new versions of relevant libraries.
Conclusion
By implementing thorough testing, actively monitoring script execution, and refining
150 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
your automation process, you can ensure that your Python scripts remain robust,
efficient, and effective. Continuous improvements based on testing outcomes and
user feedback will help maintain a high level of reliability in your deployment
automation efforts.
Step-by-step guide to testing a Python automation script, complete with a real-life
example that illustrates each step clearly.
Example Scenario: Deploying a Web Application
Assume you have a Python script that automates the deployment of a web
application to a server. The script includes functions for uploading files, restarting
services, and logging actions.
Steps to Follow for Testing
Step 1: Write Unit Tests
Objective: Test individual functions to ensure they work correctly.
Example Function:
def upload_files(local_path, remote_path):
# Simulate file upload
if not local_path or not remote_path:
raise ValueError("Both paths are required")
return True # Simulate successful upload
Unit Test
import unittest
class TestDeploymentFunctions(unittest.TestCase):
def test_upload_files_success(self):
result = upload_files("local/file/path", "remote/file/path")
self.assertTrue(result)
def test_upload_files_failure(self):
with self.assertRaises(ValueError):
upload_files("", "remote/file/path")
Run the Tests
python -m unittest test_deployment.py
Step 2: Perform Integration Testing
Objective: Test the interaction between components. Ensure that the entire
deployment process works as expected.
Integration Test Example:
class TestDeploymentIntegration(unittest.TestCase):
def test_deployment_process(self):
# Simulate the entire deployment process
result = deploy_application("host", "user", "local/path", "remote/path")
self.assertIsNone(result) # Assuming it returns None on success
151 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
Run the Tests
python -m unittest test_integration.py
Step 3: Conduct End-to-End Testing
Objective: Test the complete workflow from start to finish in a staging
environment.
Set up a Staging Environment: Create a replica of your production
environment.
Deploy the Application: Run the deployment script in the staging environment.
Verify Functionality: Check that the application is running as expected and all
features work.
Example:
# Deploy to staging server
python deploy_script.py
# Verify the application
curl http://staging-server-url
Step 4: Monitor Script Logs Execution
Objective: Keep track of the script's execution and identify any issues.
Log Important Events: Use the logging module to capture key actions.
import logging
logging.basicConfig(filename='deployment.log', level=logging.INFO)
logging.info("Starting deployment process.")
Analyze Logs: After running the script, check the logs for any errors or warnings.
cat deployment.log
Step 5: Collect Feedback and Refine
Objective: Gather input from stakeholders and improve the script based on
real-world usage.
Collect User Feedback: After deployment, ask users about their experience.
Identify Pain Points: Look for any issues they encountered during the process.
Make Improvements: Update the script based on feedback.
Example: If users report that the deployment takes too long, you might
optimize file uploads or reduce the number of services restarted.
Step 6: Regular Updates and Regression Testing
Objective: Ensure that updates to the script or dependencies do not introduce
new issues.
Update Dependencies: Periodically check for updates to libraries and tools used
in your script.
Run All Tests: Execute unit, integration, and end-to-end tests after any changes.
python -m unittest discover
Conclusion
By following these steps—writing unit tests, performing integration and end-to-
152 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
end testing, monitoring logs, collecting feedback, and regularly updating your
script—you can ensure a reliable and effective automation process for your
deployment tasks. This structured approach helps identify issues early and
enhances the overall quality of your automation efforts.
Points to Remember
● Automating certain tasks can greatly improve efficiency, reduce errors, and speed
up deployment processes.
● By focusing on repetitive, time-consuming, error-prone tasks that are critical for
deployment speed, teams can maximize their productivity and ensure a smoother
workflow.
● Automating these tasks not only saves time but also enhances the reliability of the
development and deployment processes.
● To install python automation libraries you can use “pip install library name” and
remember to replace the library name with the one that you are installing. E.g pip
install fabric, pip install ansible, pip install salt, pip install boto3 and pip install
vsphere-automation-sdk.
● To develop Python scripts effectively, plan your goals, import necessary libraries,
structure your code logically, write functions for reusable code, use library
functions, handle errors, and document your work.
● Consider using a virtual environment to isolate dependencies and leverage
logging for debugging.
● By following these steps and incorporating best practices, you can create efficient,
maintainable, and well-structured Python scripts.
● While Integrating script with Deployment Process you follow the fllowing steps:
Step 1: Trigger method to initiate the Python script post-deployment
Step 2: Direct execution after deployment completion
Step 3: Integration with CI/CD pipelines
Step 4: Scheduled execution at specific intervals
Step 5: Implement security measures to restrict script access and control
sensitive information.
● Selecting the right Python automation library depends on your specific needs,
existing infrastructure, and the complexity of the tasks you want to automate. By
evaluating the features, ease of use, scalability, and community support of each
option, you can make an informed decision that aligns with your automation
goals.
153 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
● While testing and monitoring the automated task you have to: Thorough testing,
Monitor script logs execution, Refine and improve.
154 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
Learning outcome 3 end assessment
Written assessment
II. Match the following Python libraries with their corresponding primary use cases:
ANSWER Python libraries Primary use cases
………. 1. Matplotlib A. Data manipulation and analysis
………. 2. NumPy B. Numerical operations on arrays and matrices
………. 3. Pandas C. Data visualization
………. 4. Ansible D. Automation and configuration management
………. 5. datetime E. Date and time handling
III. Select the correct answer from the listed one
1. What keyword is used to define a class in Python?
A) define
B) class
C) object
D) function
2. Which of the following allows a class to inherit properties from multiple classes?
A) Single Inheritance
B) Multiple
C) Inheritance
D) Multilevel Inheritance
155 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
E) Hierarchical Inheritance
3. What does the __init__() method do?
A) It creates a new class.
B) It initializes an object's attributes.
C) It defines a new method.
D) It overrides a method.
4. What is the primary benefit of encapsulation?
A) It increases redundancy.
B) It hides the internal state of an object.
C) It allows multiple inheritance.
D) It simplifies code readability.
5. In Python, what is polymorphism primarily used for?
A) To create new classes.
B) To allow different classes to be treated as instances of the same class.
C) To hide data.
D) To define class methods.
IV. State whether the following statements are True or False.
1. An object is an instance of a class.
2. In Python, all classes must inherit from a superclass.
3. Encapsulation allows for direct access to an object's private attributes.
4. Polymorphism can be achieved through method overloading.
5. A subclass can override methods from its superclass.
6. Inheritance promotes code reuse.
7. The self keyword is used to refer to an instance of a class.
8. All attributes in a class are public by default.
9. The __str__() method is used to represent an object as a string.
10. Method overloading is directly supported in Python.
6. Complete the following sentences with correct keyword chosen in box below .
(class, inheritance, class, constructor, Method overriding , encapsulation,
object, hierarchical, polymorphism, Encapsulation)
156 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
9. The ability to treat objects of different classes as objects of a common superclass is
known as __________.
10. __________ is achieved when a subclass inherits methods and properties from a
superclass.
Practical assessment
As a full stack devoloper, you have been assigned the task of developing and managing a
Health Management System for GIRUBUZIMA HOSPITAL. The system will handle patient
data, automate deployment tasks, and analyze health trends to ensure smooth operation
and efficient service delivery. This project involves applying concepts from Object-Oriented
Programming (OOP), date and time handling, Python libraries, and automation of post-
deployment tasks.
Tasks:
1. Create a Patient class with attributes like name, age, gender, and disease.
2. Create specialized classes like in_patient and Outpatient inheriting from Patient.
3. Use methods that behave differently based on patient type.
4. Keep patient information private and control access through methods.
5. Ensure records are aligned with Rwanda’s timezone (Central Africa Time).
6. Format timestamps for patient records.
7. Calculate days between tests and monitor recovery progress.
8. Visualize patient recovery trends.
9. Perform statistical operations on patient records.
10. Manage large datasets with patient info.
11. Use Fabric or Ansible to automate deployment-related tasks such as restarting
services and updating configurations
157 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
References
158 | P y t h o n P r o g r a m m i n g F u n d a m e n t a l s – T r a i n e e M a n u a l
Mm, YYY
October 2024