TRM GENPP501 Python Programming
TRM GENPP501 Python Programming
GENPP501
NETWORKING AND
INTERNET
TECHNOLOGIES
Python
Programming
Fundamentals
TRAINER'S 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 r 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 Networking
and Internet Technologies, 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 r M a n u a l
This training manual was developed:
PRODUCTION TEAM
Authoring and Review
NGARAMBE François
NSABIMANA Jean Pierre
Validation
MUSABIREMA Janviere
MURWANASHYAKA Eric
Conception, Adaptation and Editorial works
HATEGEKIMANA Olivier
GANZA Jean Francois Regis
HARELIMANA Wilson
NZABIRINDA Aimable
DUKUZIMANA Therese
NIYONKURU Sylvestre
NGENDAHAYO Henry Gabriel
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 r 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 r 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 r M a n u a l
INTRODUCTION
This trainer's manual includes all the methodologies required to effectively deliver the
module title "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 trainer'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 trainer, you will begin by asking questions related to the activities to encourage critical
thinking and guide trainees toward real-world applications in the labor market. The manual
also outlines essential information such as learning hours, didactic materials, and suggested
methodologies.
This manual outlines the procedures and methodologies for guiding trainees through various
activities as detailed in their respective trainee manuals. The activities included in this training
manual are designed to offer students opportunities for both individual and group work.
Upon completing all activities, you will assist trainees in conducting a formative assessment
known as the end learning outcome assessment. Ensure that students review the key reading
and the points to remember section.
Duration: 15 hrs
By the end of the learning outcome, the trainees will be able to:
1. Describe correctly python programming as applied in software development.
2. Select properly python tools in accordance with computer operating system.
3. Identify properly computer system requirements in line with operating system.
4. Select correctly python tools depending on project to be developed.
5. Install correctly python software tools based on output of python version command.
6. Configure correctly python virtual environment based on operating system.
7. Test correctly python installation based on output of python version command.
Advance Preparation:
Before delivering this learning outcome, you are recommended to:
• Have prepared computer lab.
Duration: 5 hrs
Key steps:
Step 1: Introduce the activity and ask trainees to answer the following questions:
i. Define python
ii. Discuss on benefits of python
iii. Explain characteristics of python
iv. Python programming is applied in different areas, describe each of the
following areas:
a) Data science
b) Software development
c) Automation
d) Data analysis
Step 2: Ask trainees to write their answers on papers or flipcharts
Step 3: Ask trainees to present their findings
Step 4: Provide expert view and clarification where necessary
Step 5: Address any questions or concerns
Step 6: Ask trainees to read the key reading 1.1.1 in the trainee manual
Points to Remember
● Python is a versatile programming language known for its simplicity and readability.
● Python has several benefits including: simplicity and readability, versatility, extensive
libraries and frameworks, strong community support, cross-platform, compatibility,
dynamic typing, interpreted language, integration capabilities, object-oriented and
functional programming, rapid development.
● Python can be used in data science and machine learning by using the following
frameworks: TensorFlow, PyTorch and Scikit-learn.
• This activity should take place in computer lab where trainees have to select python
tools.
Key steps:
Step 1: Introduce the activity and ask trainees to perform the task described below:
Ubumwe ltd need to develop a web application that help it in selling their
products online and the system will have capabilities to perform automatic
updates while products are sold and automatic deployment on the side of system
administrator. You are hired as machine learning engineer responsible for
selecting the best tools that will be used.
• Selecting the right Python tools for your project is crucial for productivity and quality.
Start by defining your project’s primary goal, whether it’s web development, data
analysis, or machine learning.
• Consider the tool’s ease of use, integration with existing systems, scalability, and
performance. A strong community and support, robust security features, and cost are
also important factors.
• Ensure the tool is flexible, customizable, and compatible with your operating system
and other tools you plan to use.
• Python support the following IDEs: VS Code, PyCharm, Jupyter Notebook, Spyder,
Sublime Text, and Thonny
• Python support the following frameworks: Django, Flask, and FastAPI
• Python can be used in data science and machine learning by using the following
frameworks: TensorFlow, PyTorch, and Scikit-learn
• 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.
HH ltd want to develop a system that will be used while selling their products online and
performing some automations once new features have added to their website and
performing automatic deployment. You are hired as machine learning engineer responsible
for selecting the right tools that will be used to develop that software.
Checklist:
Duration: 5 hrs
● While delivering this content, small groups can be used for identifying system
requirements to install python tools.
Key steps:
Step 1: Introduce the activity and ask trainees to identify system to install python tools.
Step 2: Ask trainees to write their findings on paper or flipchart
Step 3: Ask trainees to present their findings
Step 4: Provide expert view by using didactic materials
Step 5: Address any questions or concerns
Step 6: Ask trainees to read the key reading 1.2.1 in the trainee manual
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
● This activity should take place in computer lab where trainees have to install python
and PyCharm IDE.
Key steps:
Step 1: Introduce the topic and ask trainees to do the task described below:
As a machine learning engineer, you are asked to go to the computer lab to install
python and PyCharm.
Step 2: Explain the task and provide clear work instruction.
Step 3: Demonstrate how to install python and PyCharm check if python and PyCharm is
installed.
Step 4: Asks trainees to perform the activity of step 4 and monitor the procedures.
Step 5: Verify whether the tasks are clearly performed.
Step 6: Provide feedback if necessary.
Step 7: Ask trainees to read key reading 1.2.2.
Points to Remember
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 r M a n u a l
Practical Activity 1.2.3: Configuring python virtual environment
● This activity should take place in computer lab where trainees have to configure
python virtual environment.
Key steps:
Step 1: Introduce the topic and ask trainees to do the task described below:
As machine learning engineer, you are asked to go to the computer lab to
configure python virtual environment.
Step 2: Explain the task and provide clear work instruction.
Step 3: Demonstrate how to configure python virtual environment, while demonstrating
explain the steps to be followed.
Step 4: Asks trainees to also configure python virtual environment and monitor the
procedures.
Step 5: Verify whether the tasks are clearly performed. And provide feedback if necessary.
Step 6: Ask trainees to read key reading 1.2.3.
Points to Remember
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 r M a n u a l
● Freeze dependencies with pip freeze > [Link].
HHT LTD is software Development Company located in Kicukiro district, they want 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 machine learning engineer, responsible for installing and configuring all python tools that
will be needed to develop that project.
Checklist:
Observation
Criteria Indicators
Yes No
Python is installed
Python software tools
PyCharm is installed
are well installed
Installation is verified
Virtual environment is created
Virtual environment is activated
Packages are installed in virtual
environment
Python virtual
Is able to freeze all packages in
environment is clearly
requirements file.
configured
Is able to install packages from
requirements file.
Is able to deactivate virtual
environment.
Decision
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 r M a n u a l
Indicative content 1.3: Testing python installation
Duration: 5 hrs
● This activity should take place in the computer lab where trainees should Run python
version command, Check python interpreter and Test package manager.
Key steps:
Step 1: Introduce the topic and ask trainees to do the task described below:
As machine learning engineer, you are asked to go to the computer lab to Run
python version command, Check python interpreter and Test package manager.
Step 3: Demonstrate how to Run python version command, Check python interpreter and
Test package manager. While demonstrating, explain the steps to be followed.
Step 4: Asks learners to Run python version command, check python interpreter, Test
package manager, and monitor the procedures.
Step 5: Verify whether the tasks have been well performed and provide feedback if
necessary
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 r M a n u a l
Points to Remember
● To Check Python Version run that command in terminal: python --version or python3
--version
● To Test Package Manager: Check pip version pip –version and Install a package: pip
install Django
HHT LTD is software Development Company located in Kicukiro district, they want 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. You have
been hired as machine learning engineer, responsible for testing the python installation and
installing required packages that will be used.
Checklist
Observation
Criteria Indicators
Yes No
Python Version is checked
Python Interpreter is checked
Python installation is well tested pip version is checked
Package are installed
Installed packages are listed
Decision
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 r M a n u a l
Learning outcome 1 end assessment
Written assessment
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 r M a n u a l
6. Python is classified as a(n):
a) Compiled language
b) Interpreted language
c) Assembly language
d) Machine language
ANSWER: b) Interpreted language
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 r M a n u a l
12. Python’s memory management is handled by:
a) The developer
b) The Python interpreter automatically
c) An external tool
d) Manual memory allocation
ANSWER: b) The Python interpreter automatically
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
ANSWER: d) All of the above
14. Python was first released in:
a) 1989
b) 1991
c) 1995
d) 2000
ANSWER: b) 1991
15. What is the primary use of the TensorFlow library?
a) Web development
b) Machine learning
c) Data visualization
d) Game development
ANSWER: b) Machine learning
16. Which of the following is NOT a characteristic of Python?
a) Dynamic typing
b) Complex syntax
c) Object-oriented programming
d) Readability
ANSWER: b) Complex syntax
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
ANSWER: b) Displays the current Python version installed
18. Which Python library is widely used for data visualization?
a) Matplotlib
b) TensorFlow
c) Flask
d) Pandas
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 r M a n u a l
ANSWER: a) Matplotlib
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
ANSWER: a) Integrated Development Environment
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
ANSWER: b) python -m venv
21. Which Python framework is designed for asynchronous networking?
a) Kivy
b) Twisted
c) CherryPy
d) Flask
ANSWER: b) Twisted
22. In Python, a function is defined using the keyword:
a) func
b) function
c) def
d) define
ANSWER: c) def
23. Which IDE is web-based and primarily used for data analysis?
a) PyCharm
b) Jupyter Notebook
c) Visual Studio Code
d) Thonny
ANSWER: b) Jupyter Notebook
24. The command to deactivate a Python virtual environment is:
a) end venv
b) stop venv
c) deactivate
d) exit venv
ANSWER: c) deactivate
25. What type of language is Python?
a) Low-level
b) High-level
c) Mid-level
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 r M a n u a l
d) Machine-level
ANSWER: b) High-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
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 r M a n u a l
14. TensorFlow
15. Include libraries
III. Matching questions
1. Match the IDE in column A with their corresponding primary features in column B
ANSWER:
a) PyCharm –(i)
b) Jupyter Notebook –(ii)
c) Thonny –(iii)
d)Visual Studio Code–(iv)
16. Match the Python framework in column A with its corresponding description in
column B
ANSWER:
a) Django –(i)
b) Flask –(ii)
c) FastAPI–(iii)
d) Kivy–(iv)
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 r M a n u a l
2. Match the Python library of column A with its corresponding application in column
B
Answers Column A Column B
a)…….. a) NumPy (i) Numerical computing
b)…….. b) Pandas (ii) Data manipulation
c)…….. c) Matplotlib (iii) Data visualization
d)…….. d) Scikit learn (iv) Machine learning
ANSWER:
a) NumPy –(i)
b) Pandas –(ii)
c) Matplotlib –(iii)
d) Scikit learn –(iv)
3. Match the Python characteristic in column A with its corresponding feature of
column B
Answers Column A Column B
a)…….. a) Dynamic typing (i) Clear syntax and structure
b)…….. b) Readability (ii) No explicit data type declaration
c)…….. c) Efficiency (iii) Large standard library
d)…….. d) Versatility (iv) Wide range of applications
ANSWER:
a) Dynamic typing –(i)
b) Readability –(ii)
c) Efficiency –(iii)
d) Versatility–(iv)
4. Match the Python command in column A with its corresponding function of column
B
Answers Column A Column B
a)…….. a) python --version (i) Display the Python version
b)…….. b) pip install (iii) Install Python packages
c)…….. c) deactivate (iv) Exit the virtual environment
d)…….. d) pip list (ii) Display installed packages
ANSWER:
a) python --version –(i)
b) pip install –(ii)
c) deactivate –(iii)
d) pip list–(iv)
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 r M a n u a l
5. Match the Python tools of column A with its corresponding description in column B
Answers Column A Column B
a)…….. a) PyTorch (i) Computer vision library
b)…….. b) TensorFlow (ii) Flexible machine learning framework
c)…….. c) SciPy (iii) Platform for deep learning
d)…….. d) OpenCV (iv) Scientific computing and statistics
ANSWER:
a) PyTorch –(i)
b) TensorFlow –(ii)
c) SciPy –(iii)
d) OpenCV–(iv)
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 r M a n u a l
8. Match the Python command in Column A with the corresponding action it performs
in Column B:
Answers Column A Column B
a)…….. a) import (i) Defines a function
b)…….. b) def (ii) Imports a module or library
c)…….. c) print (iv) Outputs data to the console
d)…….. d) class (iii) Defines a new class
ANSWER:
a) import –(i)
b) def –(ii)
c) print –(iii)
d) class –(iv)
Match the following Python versions in Column A with their corresponding key
characteristics in Column B:
Answers Column A Column B
a)…….. a) Python 2.x (i) Legacy version with different print syntax
b)…….. b) Python 3.x (ii) Current version with updated syntax
c)…….. c) Python 3.6+ (iv) Introduced f string formatting
d)…….. d) Python 3.8+ (iii) Introduced assignment expressions
ANSWER:
a) Python 2.x –(i)
b) Python 3.x –(ii)
c) Python 3.6+ –(iii)
d) Python 3.8+ –(iv)
Practical assessment
HHT LTD is software Development Company located in Kicukiro district, they want 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 machine learning
engineer, 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.
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 r M a n u a l
Checklist:
Observation
Criteria Indicators
Yes No
Python is installed
Python software tools
PyCharm is installed
are well installed
Installation is verified
Virtual environment is created
Virtual environment is activated
Python virtual
Packages are installed in virtual environment
environment is clearly
Is able to freeze all packages in requirements file
configured
Is able to install packages from requirements file
Is able to disactivate virtual environment
Python Version is checked
Python Interpreter is checked
Python installation is
pip version is checked
well tested
Package are installed
Installed packages are listed
Decision
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 r M a n u a l
Further information to the trainer
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 r M a n u a l
Learning Outcome 2: Write Basic Python Program
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 r M a n u a l
Indicative contents
● Performing
operations on
collection
● Performing
write/create and
delete file
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 r M a n u a l
Applying python best
practices
Duration: 45 hrs
By the end of the learning outcome, the trainees will be able to:
Resources
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 r M a n u a l
Advance Preparation:
● Have computers installed with python and PyCharm or any other IDE that support
python.
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 r M a n u a l
Indicative content 2.1: Applying python basic concepts
Duration: 9 hrs
● While delivering this activity small groups can be used to discuss python basic
concepts.
Key steps:
Step 1: Introduce the topic and ask trainees to describe the following python basic
concepts:
i. Data types
ii. Variable
iii. Comments
iv. Operators
Step 2: Ask trainees to write their answers on paper or flipchart
Step 3: Ask trainees to present their findings
Step 4: Provide expert view by using didactic materials
Step 5: Address any questions or concerns
Step 6: Ask trainees to read the key reading 2.1.1 in the trainee manual
Points to Remember
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 r M a n u a l
Practical Activity 2.1.2: Applying python basic concepts
● This activity has to take place in computer lab where trainees have to apply python
basic concepts.
Key steps:
Step 1: Introduce the topic and ask trainees to do the task described below:
As machine learning engineer, you are asked to go to the computer lab to apply
python data types, variable, python comments and operators while developing a
python program that can perform simple calculation add, subtract, multiply,
divide and calculate the module and exponent for two entered numbers by user.
Step 2: Explain the task and provide clear work instruction.
Step 3: Demonstrate how to apply python basic concepts while developing a simple
calculator, while demonstrating explain the code to be used.
Step 4: Asks trainees to perform the activity of step 3 and monitor the procedures.
Step 5: Verify whether the tasks are clearly performed.
Step 6: Provide feedback if necessary.
Step 7: Ask trainees to read key reading 2.1.2.
Points to Remember
● Python supports numeric, sequence, mapping, set, and Boolean data types.
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 r M a n u a l
Application of learning 2.1.
As machine learning engineer, you are asked to develop a python program that can perform
simple calculation add, subtract, multiply, divide and calculate the module and exponent for
two entered numbers by user. The developed program has to contain comments for better
explanation.
Checklist:
Observation
Criteria Indicators
Yes No
Variables are declared
Python basic concepts
Datatypes are used
are well applied
Comments are used
+ operator is used for addition
* operator is used for multiplication
/ operator is used for division
% is used for modulus
- Operator is used for subtraction
Decision
Solution/output:
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 r M a n u a l
"""Return the quotient of x and y. Handles division by zero."""
if y == 0:
return "Error: Division by zero!"
return x / y
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 r M a n u a l
elif operation == '4':
print("{num1} / {num2} = {divide(num1, num2)}")
elif operation == '5':
print("{num1} % {num2} = {modulus(num1, num2)}")
elif operation == '6':
print("{num1} ** {num2} = {exponent(num1, num2)}")
else:
print("Invalid operation! Please enter a number between 1 and 6.")
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 r M a n u a l
Indicative content 2.2: Applying python control structures
Duration: 9 hrs
● This activity has to take place in computer lab where trainees have to apply
conditional statement in python programs.
Key steps:
Step 1: Introduce the topic and ask trainees to do the task described below:
As machine learning engineer, you are asked to go to the computer lab to apply if,
elif and else statement while developing a python program that can be used when
displaying the grade of students depending on entered marks as requested by NESA
once analysing marks and student placement.
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 r M a n u a l
Points to Remember
● Conditional statements are used to execute different code blocks based on specific
conditions.
● The “else statement” is used to execute a block of code if the if condition is false.
● 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.
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 r M a n u a l
Practical Activity 2.2.2: Applying Looping Statements
● This activity has to take place in computer lab where trainees have to apply looping
statement in python programs.
Key steps:
Step 1: Introduce the topic and ask trainees to do the task described below:
As machine learning engineer, you are asked to go to the computer lab to apply
looping statement while writing python programs.
Step 2: Explain the task and provide clear work instruction.
Step 3: Demonstrate how to apply loping statement, while demonstrating explain the
code to be used.
Step 4: Asks trainees to perform the activity of step 3 and monitor the procedures.
Step 5: Verify whether the tasks are clearly performed.
Step 6: Provide feedback if necessary.
Step 7: Ask trainees to read key reading 2.2.2.
Points to Remember
● 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 continue statement can be used to skip the current iteration of a loop and move
to the next one.
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 r M a n u a l
● Nested loops can be used to create more complex looping structures.
• This activity has to take place in computer lab where trainees have to use jump
statements.
• While delivering this content the trainer has to:
✓ Avail computer installed with python and PyCharm.
✓ Avail video to be used as didactic material
Key steps:
Step 1: Introduce the topic and ask trainees to do the task described below:
As machine learning engineer, you are asked to go to the computer lab to apply looping
statement while writing python programs and inside looping statement use break,
continue and pass statements.
Points to Remember
● “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.
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 r M a n u a l
Application of learning 2.2.
Write a python program that can display all even numbers from 0 to 100 and the program
skip 60 and 80 and stops execution if value is equal to 90.
Checklist:
Observation
Criteria Indicators
Yes No
Loop is used
Python control structures are well applied Continue is used
Break is used
Conditions are well applied
Decision
Solution/Output:
Explanation:
● The program uses a for loop to iterate through numbers from 0 to 100.
● It skips the numbers 60 and 80 by checking if the number is not in the tuple (60, 80).
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 r M a n u a l
Indicative content 2.3: Applying functions in Python
Duration: 9 hrs
While delivering this activity small groups can be used to describe functions in
python programming.
Key steps:
Step 1: Introduce the topic and ask trainees to answer the followings questions related to
functions in python programming:
i. Define function in python
ii. Differentiate two (2) types of function in python
iii. Elaborate characteristics and Advantages of Functions in python
Step 2: Ask trainees to write their answers on paper or flipchart
Step 3: Ask trainees to present their findings
Step 4: Provide expert view by using didactic materials
Step 5: Address any questions or concerns
Step 6:Ask trainees to read the key reading 2.3.1 in the trainee manual
Points to Remember
● Built-in Functions: These are functions that are pre-defined in Python and can be
used without any additional code.
● User-Defined Functions: These are functions that you define yourself to perform
specific tasks. You can create them using the def keyword.
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 r M a n u a l
● Characteristics of Functions include: Modularity, Reusability, Parameters and Return
Values, Encapsulation and Scope.
● This activity has to take place in computer lab where trainees have to create
functions in python.
Key steps:
Step 1: Introduce the topic and ask trainees to do the task described below:
As machine learning engineer, you are requested to go to the computer lab to
create a function with arguments, default parameter value, passing a list as an
argument and calling a function.
Points to Remember
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 r M a n u a l
Step 4: Passing a List as an Argument
Step 5: Calling a Function
● This activity has to take place in computer lab where trainees have to apply special
purpose functions.
Key steps:
Step 1: Introduce the topic and ask trainees to do the task described below:
As machine learning engineer, you are requested to go to the computer lab to
apply special purpose functions such as Lambda, Python Generators, Python
Closures, Python Decorators, Recursive function, and Higher-order function.
Step 2: Explain the task and provide clear work instruction.
Step 3: Demonstrate how to apply special purpose functions, while demonstrating
explain the code to be used.
Step 4: Asks trainees to perform the activity of step 3 and monitor the procedures.
Step 5: Verify whether the tasks are clearly performed.
Step 6: Provide feedback if necessary.
Step 7: Ask trainees to read key reading 2.3.3.
Points to Remember
● 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.
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 r M a n u a l
● 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.
Write a Python program that defines a function that generates Fibonacci numbers using a
generator, uses a lambda function to filter even numbers from the generated sequence then
prints the first 10 even Fibonacci numbers.
Checklist:
Observation
Criteria Indicators
Yes No
Python functions are The Fibonacci generator function is
well applied defined
A lambda function is used to filter even
Fibonacci numbers.
The filtering logic correctly identifies
even numbers.
The loop correctly iterates over the
filtered results and prints the first 10.
The output contains the correct first 10
even Fibonacci numbers.
Decision
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 r M a n u a l
Solution/Output:
Explanation:
• Fibonacci Generator: The fibonacci_generator function yields Fibonacci numbers
indefinitely.
• Filtering Even Numbers: A list comprehension generates the first 100 Fibonacci
numbers, and then filter with a lambda function is used to select only the even
numbers.
• Output: Finally, it prints the first 10 even Fibonacci numbers.
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 r M a n u a l
Indicative content 2.4: Applying Python Collections
Duration: 9hrs
• While delivering this activity small groups can be used to describe python collections.
Key steps:
Step 1: Introduce the topic and ask trainees to describe the concepts of OOP below:
i. Describe collection Types in Python
ii. Explain Tools from the Collections Module
Step 2: Ask trainees to write their answers on paper or flipchart
Step 3: Ask trainees to present their findings
Step 4: Provide expert view by using didactic materials
Step 5: Address any questions or concerns
Step 6: Ask trainees to read the key reading 2.4.1 in the trainee manual
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.
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 r M a n u a l
Practical Activity 2.4.2: Performing common operations on collection.
• This activity has to take place in computer lab where trainees have to perform operations
on collections.
• While delivering this content the trainer has to:
✓ Avail computer installed with python and PyCharm.
✓ Avail sample videos to be used as didactic materials.
Key steps:
Step 1: Introduce the topic and ask trainees to do the task described below:
As machine learning engineer , you are requested to go to the computer lab to
perform the following operations on collections:
i. Adding and Removing Elements
ii. Accessing and Iterating Over Elements
iii. Filtering and Sorting
iv. Set Operations and Counting
v. Stack and Queue Operations
Step 2: Explain the task and provide clear work instruction.
Step 3: Demonstrate how to create functions in python, while demonstrating explain the
code to be used.
Step 4: Asks trainees to perform the activity of step 3 and monitor the procedures.
Step 5: Verify whether the tasks are clearly performed.
Step 6: Provide feedback if necessary.
Step 7:Ask trainees to read key reading 2.3.2.
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 r M a n u a l
Points to Remember
● 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, 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.
Write a Python program that creates a list of numbers, filters out even numbers, sorts the
remaining numbers in ascending order and then prints the sorted list.
Checklist:
Observation
Criteria Indicators
Yes No
The program creates a list of numbers
The filtering logic identifies and retains only
Python collections are
odd numbers (i.e. x % 2 != 0)
well applied
A lambda function is used effectively within
the filter function
The program uses the sorted function to
sort the list in ascending order
The program prints the sorted list of odd
numbers
Decision
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 r M a n u a l
Solution/output:
sorted_odd_numbers = sorted(odd_numbers)
print(sorted_odd_numbers)
Explanation:
1. List Creation: A list of numbers is defined.
2. Filtering: A list comprehension filters out even numbers (keeping only odd numbers).
3. Sorting: The sorted() function is used to sort the filtered list in ascending order.
4. Output: The sorted list of odd numbers is printed.
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 r M a n u a l
Indicative content 2.5: Performing File handling
Duration: 9hrs
● While delivering this activity small groups can be used to describe file handling
libraries.
Key steps:
Step 1: Introduce the topic and ask trainees to describe the following file handling
libraries:
i. os module
ii. pathlib module
iii. shutil module
iv. pandas library
Step 2: Ask trainees to write their answers on paper or flipchart
Step 3: Ask trainees to present their findings
Step 4: Provide expert view by using didactic materials
Step 5: Address any questions or concerns
Step 6: Ask trainees to read the key reading 2.5.1 in the trainee manual
Points to Remember
● Os library used for interacting with the operating system and file system;
● Shutil library used for high-level file operations such as copying and moving files;
● Pandas library used for reading and writing data in various formats, primarily used
for data analysis.
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 r M a n u a l
Practical Activity 2.5.2: Practicing open and read file
• This activity has to take place in computer lab where trainees have to practice read file.
• While delivering this content the trainer has to:
✓ Avail computer installed with python and PyCharm.
✓ Avail a text file that will be used to implement those practice.
✓ Avail sample videos to be used as didactic materials.
Key steps:
Step 1: Introduce the topic and ask trainees to do the task described below:
As machine learning engineer, you are requested to go to the computer lab to
perform the following operations on file:
i. Open a File
ii. Read File Permissions
Step 2: Explain the task and provide clear work instruction.
Step 3: Demonstrate how to open and read file permission, while demonstrating explain
the code to be used.
Step 4: Asks trainees to perform the activity of step 3 and monitor the procedures.
Step 5: Verify whether the tasks are clearly performed.
Step 6: Provide feedback if necessary.
Step 7: Ask trainees to read key reading 2.5.2.
Points to Remember
● Opening a File: Use the open() function with the appropriate mode to read from or
write to a file.
● Reading a File: You can read the entire content using [Link](), or read line by line
using [Link]() or [Link]().
● Checking Permissions: Use the os module to check whether you have read, write, or
execute permissions for a file before attempting to open it.
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 r M a n u a l
Practical Activity 2.5.3: Performing write/create and delete file
● This activity has to take place in computer lab where trainees have to write, create
and delete file.
Key steps:
Step 1: Introduce the topic and ask trainees to do the task described below:
As machine learning engineer, you are requested to go to the computer lab to
perform the following operations on file:
i. Write
ii. Create
iii. Delete file
Step 2: Explain the task and provide clear work instruction.
Step 3: Demonstrate how to write, Create and delete file, while demonstrating explain
the code to be used.
Step 4: Asks trainees to perform the activity of step 3 and monitor the procedures.
Step 5: Verify whether the tasks are clearly performed.
Step 6: Provide feedback if necessary.
Step 7: Ask trainees to read key reading 2.5.3.
Points to Remember
● Creating a New File: Use open(file_path, 'w') or open(file_path, 'x') to create a new
file.
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 r M a n u a l
● Deleting a Folder: Use [Link]() for empty directories and [Link]() for non-
empty directories.
● This activity has to take place in computer lab where trainees have to apply python
best practices.
Key steps:
Step 1: Introduce the topic and ask trainees to do the task described below:
As machine learning engineer developer, you are requested to go to the computer lab to apply
the following:
i. Readability and Style
ii. Use of Built-in Features
iii. Efficiency and Memory Usage
iv. Error Handling and Testing
Step 2: Explain the task and provide clear work instruction.
Step 3: Demonstrate how to apply python best practices, while demonstrating explain the
code to be used.
Step 4: Asks trainees to perform the activity of step 3 and monitor the procedures.
Step 5: Verify whether the tasks are clearly performed.
Step 6: Provide feedback if necessary.
Step 7: Ask trainees to read key reading 2.5.4.
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 r M a n u a l
Points to Remember
● Adhering to Python best practices can improve code quality, readability, and
maintainability.
● Using built-in features can make code more concise and efficient.
● Testing can help identify and fix bugs early in the development process.
● Regular code reviews can help improve coding practices and catch potential issues.
Develop a python program that can create a file in excel format "list of TVET schools" and
attach the following as header (District, School name, Trade, Number of students) and
attach sample data in row 1 (Your district, Your school name, SWD,23). The created file has
to be saved on desktop of your computer in directory works if that directory don't exist it
has to create it before saving that file.
Checklist
Yes No
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 r M a n u a l
1.7 The program is proving the correct
output
Solution/Output:
import openpyxl
import os
if not desktop_path.exists():
desktop_path.mkdir(parents=True, exist_ok=True)
workbook = [Link]()
sheet = [Link]
[Link](headers)
[Link](sample_data)
# Define the file path where the Excel file will be saved
[Link](file_name)
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 r M a n u a l
# Display the contents of the created Excel file
workbook = openpyxl.load_workbook(file_name)
sheet = [Link]
print(row)
Key Points:
✓ Path Handling: [Link]() is used to get the home directory of the current user, and
Desktop is appended to it to form the path to the desktop.
✓ Saving the File: The Excel file is saved in the "Works" directory on the desktop as
list_of_TVET_schools.xlsx.
✓ Reading and Displaying File Contents: The contents of the Excel file are read and
displayed in the terminal using openpyxl.
Expected Output:
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 r M a n u a l
Learning outcome 2 end assessment
Written assessment
A) list = (1, 2, 3)
B) list = [1, 2, 3]
C) list = {1, 2, 3}
D) list = <1, 2, 3>
ANSWERS: B) list = [1, 2, 3]
2. Which of the following is an immutable data type in Python?
A) List
B) Dictionary
C) Tuple
D) Set
ANSWERS: C) Tuple
3. What will the output of the following code be?
x=5
y = 10
print(x > y)
A) True
B) False
C) 5
D) 10
ANSWER: B) False
4. Which operator is used for exponentiation in Python?
A) ^
B) **
C) //
D) ***
ANSWER: B) **
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 r M a n u a l
5. Which keyword is used to define a function in Python?
A) function
B) def
C) define
D) func
ANSWER: B) def
6. What does the 'break' statement do in a loop?
A) pd.read_csv()
B) pd.load_csv()
C) pd.import_csv()
D) pd.open_csv()
ANSWER: A) pd.read_csv()
9. What will len([1, 2, 3]) return?
A) 2
B) 3
C) 4
D) None
ANSWER: B) 3
10. Which of the following is a built-in function in Python?
A) print()
B) show()
C) display()
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 r M a n u a l
D) output()
ANSWER: A) print()
11. In Python, what data type is used to represent True or False values?
A) int
B) float
C) bool
D) str
ANSWER: C) bool
12. What will the output of the following code snippet?
print("Hello, World!"[7])
A) H
B) e
C) W
D) o
ANSWER: C) W
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) #!
ANSWER: B) /* This is a comment */
14. What does the 'continue' statement do in a loop?
A) []
B) ()
C) {}
D) <>
ANSWER: C) {}
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 r M a n u a l
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
ANSWER : A) lambda 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'>
ANSWER: B) <class 'float'>
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
ANSWER: A) import 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
ANSWER: B) Large
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
ANSWER: D) Both B and C
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 r M a n u a l
1. Complete the following 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.
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.
ANSWER:
1. function
2. ==
3. loop
4. lambda
5. os
6. defaultdict
7. break
8. tuple
9. open
10. Dictionary
II. Answer by True or False to the followings:
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.
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 r M a n u a l
ANSWERS:
1. False
2. True
3. True
4. False
5. False
6. True
7. True
8. False
9. True
10. True
III. Match the following Python data types with their corresponding descriptions:
Answers Data Type Description
1……... 1. List A. Unordered collection of unique elements
2……... 2. Tuple B. Ordered, mutable collection
3……... 3. Dictionary C. Key-value pairs
4……... 4. Set D. Ordered, immutable collection
ANSWER:
1. List -A
2. Tuple – B
3. Dictionary – C
4. Set – D
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 r M a n u a l
Practical assessment
CODEX DEV LTD, a Kigali-based Software Development company, is seeking a machine
learning engineer to implement a shopping cart feature in their existing system. The
developer will be responsible for receiving a list of items to be purchased, allowing users to
remove items from the cart, and providing an option to empty the cart entirely. And app must
store that cart information to file named [Link] The project will be implemented using
Python.
Checklist:
Observation
Criteria Indicators
Yes No
Cart item is added
Python
Items can be removed from cart
collection is
Cart items is displayed
well applied
Cart can be emptied
Python file [Link] file is created
handling are
well applied Cart items written to [Link]
Cart items is retrieved from [Link]
All cart items can be removed from [Link]
Function to load cart data is created
Python
Function for adding items to cart is created
functions are
Function for removing items to cart is created
correctly
Function for unpacking items from cart is
applied
created
Python control Proper conditional statements are used
structure are
Proper looping statements is used
well applied
Decision
Solution/output:
import csv
import os
CART_FILE = '[Link]'
def load_cart():
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 r M a n u a l
"""Load the cart data from the CSV file."""
cart = []
if [Link](CART_FILE):
with open(CART_FILE, mode='r') as file:
reader = [Link](file)
cart = list(reader)
return cart
def save_cart(cart):
"""Save the cart data to the CSV file."""
with open(CART_FILE, mode='w', newline='') as file:
writer = [Link](file)
[Link](cart)
def remove_item(name):
"""Remove an item from the cart."""
cart = load_cart()
cart = [item for item in cart if item[0] != name]
save_cart(cart)
print(f'Removed {name} from the cart.')
def empty_cart():
"""Empty the cart."""
save_cart([])
print('The cart has been emptied.')
def view_cart():
"""Display the items in the cart."""
cart = load_cart()
if not cart:
print('The cart is empty.')
else:
print('Items in the cart:')
for item in cart:
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 r M a n u a l
print('- {item[0]}: {item[1]}')
def main():
"""Main function to handle user commands."""
while True:
print('\nShopping Cart Menu:')
print('1. Add item')
print('2. Remove item')
print('3. View cart')
print('4. Empty cart')
print('5. Quit')
if __name__ == '__main__':
main()
END
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 r M a n u a l
Further information to the trainer
Hi mana, E., Richard, M., Bajpai, G., Louis, S., & Kayalvizhi, J. (2021). Implementation of
IoT Framework with Data Analysis Using Deep Learning Methods for Occupancy Predic on
in a Building. Future Internet.
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.
Sarkar, D., Raghav, B., & Tushar, S. (2017). Practical Machine Learning with Python: A
Problem-Solver’s Guide to Building Real-World Intelligent Systems.
James, G., Wi en, D., Has e, T., & Tibshirani, R. (2017). An Introduction to Statistical
Learning: with Applications in R. Springer.
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
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 r M a n u a l
Learning Outcome 3: Apply Object-Driven in Python
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 r M a n u a l
Indicative contents
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 r M a n u a l
Duration: 40 hrs
Learning outcome 3 objectives:
By the end of the learning outcome, the trainees will be able to:
1. Describe correctly date and time as according to python standards
2. Describe correctly Python Library in accordance with python standards
3. Understand correctly Scope of library according to the name space
4. Identify clearly tasks to automate based on specific task
5. Identify correctly tasks to be prioritized based on specific task
6. Apply correctly OOP Concepts in line with python standards
7. Set properly Time zones in line with python standard
8. Use correctly python libraries in accordance with python standards
9. Select correctly Python Automation Library based on specific task
10. Develop correctly Python Script based on specific task to be automated
11. Integrate properly script with Deployment Process based on specific task
12. Test and monitor correctly automated task in accordance with python standards
Resources
● IDE
● Jupyter notebook
Advance Preparation:
Before delivering this learning outcome, you are recommended to:
• Have python installed on all computers to be used
• Have prepared computer lab
• Have IDE (Pycharm) installed on all computers to be used
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 r M a n u a l
Indicative content 3.1: Applying OOP Concepts
Duration: 10 hrs
● While delivering this activity small groups can be used to discuss on OOP concepts.
Key steps:
Step 1: Introduce the activity and ask trainees to to answer the following questions
related to the introduction to Object Oriented Programming.
Describe the concepts as applied in OOP:
i. Object
ii. Class
iii. Inheritance
iv. Polymorphism
v. Encapsulation
Step 2: Ask trainees to write their answers on paper or flipchart
Step 3: Ask trainees to present their findings
Step 4: Provide expert view by using didactic materials
Step 5: Address any questions or concerns
Step 6: Ask trainees to read the key reading 3.1.1 in the trainee manual
Points to Remember
● Classes serve as blueprints for creating objects, defining attributes and methods.
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 r M a n u a l
● Inheritance allows one class (subclass) to inherit properties and methods from
another class (superclass), promoting code reuse and establishing a hierarchical
relationship.
• This activity has to take place in computer lab where trainees have to apply classes and
objects in python programs.
• While delivering this content the trainer has to:
✓ Avail computer installed with python and PyCharm.
✓ Prepare python program that will be developed including the application of classes
and objects.
Key steps:
Step 1: Introduce the topic and ask trainees to do the task described below:
As a machine learning engineer, you have been asked to develop a python
program to perform simple calculation (add, subtract, divide and multiply). That
program has to let numbers to be entered by user using keyboard, and after
entering numbers it has to let user to select the operation to be performed and
display the results according to selected operation.
Step 2: Explain the task and provide clear work instruction.
Step 3: Demonstrate how to apply classes and object in python while developing a simple
calculator, while demonstrating explain the code to be used.
Step 4: Asks trainees to perform the activity of step 3 and monitor the procedures.
Step 5: Verify whether the tasks are clearly performed.
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 r M a n u a l
Step 6: Provide feedback if necessary.
Step 7: Ask trainees to read key reading 3.1.2.
Points to Remember
• Classes and objects in Python provide a powerful way to model complex systems,
encapsulate data, and promote code reuse. From simple data structures to complex
frameworks, object-oriented programming enhances the clarity and maintainability of
code.
• Classes and object in python are most applicable in different ways like the followings:
in the development of calculator programs, in banking transaction programs, and in
library management programs.
● This activity has to take place in computer lab where trainees have to apply
inheritance in python programs.
Key steps:
Step 1: Introduce the topic and ask trainees to do the task described below:
As machine learning engineer, you have been asked to develop a python program to
perform bank transactions including deposit and withdraw, for withdraw you cannot
let the account to be empty means it has to let 100 Rfw on the account and for all
transactions it has to display the messages.
Step 2: Explain the task and provide clear work instruction.
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 r M a n u a l
Step 3: Demonstrate how to apply inheritance in python while developing a simple bank
transaction program, while demonstrating explain the line of code to be used.
Step 4: Asks trainees to perform the activity of step 3 and monitor the procedures.
Step 5: Verify whether the tasks are clearly performed.
Step 6: Provide feedback if necessary.
Step 7: Ask trainees to read key reading 3.1.3.
Points to Remember
• Inheritance in Python is a powerful feature that allows one class (the subclass) to
inherit attributes and methods from another class (the superclass).
• Common applications of inheritance in Python are: Code reusability, method
overriding, creating a hierarchical structure, multiple inheritance, and framework and
library development.
● This activity has to take place in computer lab where trainees have to apply
polymorphism in python programs.
Key steps:
Step 1: Introduce the topic and ask trainees to do the task described below:
As machine learning engineer, you have been asked to develop a python program
to perform bank transactions including deposit and withdraw, for withdraw you
cannot let the account to be empty; means it has to let 100 Rfw on the account
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 r M a n u a l
and for all transactions it have to display the messages the program have to
include the application of polymorphism.
Step 2: Explain the task and provide clear work instruction.
Step 3: Demonstrate how to apply polymorphism in python while developing a simple
bank transaction program, while demonstrating explain the line of code to be
used.
Step 4: Asks trainees to perform the activity of step 3 and monitor the procedures.
Step 5: Verify whether the tasks are clearly performed.
Step 6: Provide feedback if necessary.
Step 7: Ask trainees to read key reading 3.1.4.
Points to Remember
• This activity has to take place in computer lab where trainees have to apply polymorphism
in python programs.
• While delivering this content the trainer has to:
✓ Avail computer installed with python and PyCharm.
✓ Prepare python program that will be developed including the application of
encapsulation.
Key steps:
Step 1: Introduce the topic and ask trainees to do the task described below:
As machine learning engineer, you have been asked to develop a python program to
perform simple calculation (add, subtract, divide and multiply). That program has to
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 r M a n u a l
let numbers to be entered by user using keyboard, and after entering numbers it has
to let user to select the operation to be performed and display the results according
to selected operation. In addition, the program has to show the application of
encapsulation.
Step 2: Explain the task and provide clear work instruction.
Step 3: Demonstrate how to apply classes and object in python while developing a simple
calculator, while demonstrating explain the code to be used.
Step 4: Asks trainees to perform the activity of step 3 and monitor the procedures.
Step 5: Verify whether the tasks are clearly performed.
Step 6: Provide feedback if necessary.
Step 7: Ask trainees to read key reading 3.1.5.
Points to Remember
● Encapsulation can be used in different ways including: Data hiding, controlled access,
implementation hiding, API design, and security.
As machine learning engineer, you are requested to develop a simple bank account
transaction python program where there is application of inheritance the system have to
accept to input the account owner and choose the action to be performed including withdraw,
deposit and the system have to show the amount to be withdrawn based on settings of bank.
The program has to include the followings: Object, class, inheritance, polymorphism, and
encapsulation.
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 r M a n u a l
Checklist:
Observation
Criteria Indicators
Yes No
Base class for a bank account is declared
The balance is initialised to zero
Initialize the account with owner and starting
Classes and
balance
objects are well
Add amount to the balance is performed
applied
Calculate the maximum amount that can be
withdrawn is performed
Creating an object of the appropriate account
class
Derived class for a savings account is used
Initialize the savings account with owner, balance,
and interest rate
Apply interest to the current balance is
Inheritance is
performed
well applied
Derived class for a checking account is used
Derived class for a checking account is used
Calculate the maximum amount that can be
withdrawn is performed
Allow withdrawal up to the overdraft limit is done
User input for account details is performed
Polymorphism Ensure the initial balance is above 100
is well applied User operations is displayed
Choose account type is displayed
Decision
Solution/output:
class BankAccount:
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 r M a n u a l
[Link] = owner
[Link] = balance
[Link] += amount
[Link] -= amount
class SavingsAccount(BankAccount):
# Initialize the savings account with owner, balance, and interest rate
self.interest_rate = interest_rate
def apply_interest(self):
[Link] += interest
class CheckingAccount(BankAccount):
# Initialize the checking account with owner, balance, and overdraft limit
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 r M a n u a l
super().__init__(owner, balance)
self.overdraft_limit = overdraft_limit
[Link] -= amount
if account_type == 'savings':
else:
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 r M a n u a l
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':
print([Link](amount))
print([Link](amount))
print(account.apply_interest())
break
else:
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 r M a n u a l
Indicative content 3.2: Applying python Date and time concepts
Duration: 10 hrs
• While delivering this content, small groups can be used for describing date and time in
python.
Key steps:
Step 1: Introduce the activity and ask trainees to describe date and time concepts in
python programming:
i. Datetime
ii. Dateutil
iii. Arrow
iv. Pendulum
v. Python-tzdata
Step 2: Ask trainees to write their answers on paper or flipchart
Step 3: Ask trainees to present their findings
Step 4: Provide expert view by using didactic materials
Step 5: Address any questions or concerns
Step 6: Ask trainees to read the key reading 3.2.1 in the trainee manual
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 r M a n u a l
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.
● 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.
● This activity should take place in computer lab where trainees have to apply python
date and time concepts.
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 r M a n u a l
Key steps:
Step 1: Introduce the topic and ask trainees to do the task described below:
As machine learning engineer, you are asked to go to the computer lab apply date
and time concepts while performing different operations on date and time
calculating the difference between date, calculating the age depending on current
date and date of birth.
Step 2: Explain the task and provide clear work instruction.
Step 3: Demonstrate how to apply date and time concepts. And while demonstrating
explain the application of each concept.
Step 4: Asks trainees to perform the activity of step 3 and monitor the procedures.
Step 5: Verify whether the tasks are clearly performed.
Step 6: Provide feedback if necessary.
Step 7: Ask trainees to read key reading 3.2.2.
Points to Remember
● 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.
● These tools provide a robust framework for handling date and time calculations in
your applications.
As machine learning engineer, 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.
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 r M a n u a l
Checklist:
Observation
Criteria Indicators
Yes No
Datetime library is imported
Python Date Get user input for birth date is done
and time Calculate age is performed
concepts are Adjust age if the birthday hasn't occurred
well applied yet this year is done
Check if allowed for ID is done
Decision
Solution/output:
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 r M a n u a l
Explanation
● The program first prompts for the birth date and attempts to parse it.
● It calculates the age directly within the main block and checks the eligibility for a
national ID card.
● Finally, it prints the result or an error message if the input format is invalid.
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 r M a n u a l
Indicative content 3.3: Applying Python Libraries
Duration: 10 hrs
● While delivering this content, small groups can be used for describing python
libraries.
Key steps:
Step 1: Introduce the activity and ask trainees to describe the following python libraries:
i. Matplotlib
ii. Numpy
iii. Pandas
Step 2: Ask trainees to write their answers on paper or flipchart
Step 3: Ask trainees to present their findings
Step 4: Provide expert view by using didactic materials
Step 5: Address any questions or concerns
Step 6: Ask trainees to read the key reading 3.3.1 in the trainee manual
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.
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 r M a n u a l
Practical Activity 3.3.2: Using python libraries
● This activity should take place in computer lab where trainees have to use python
libraries.
Key steps:
Step 1: Introduce the topic and ask trainees to do the task described below:
As machine learning engineer, you are asked to go to the computer lab to use python
libraries described in key readings 3.3.1.
Step 2: Explain the task and provide clear work instruction.
Step 3: Demonstrate how to use python libraries and while demonstrating explain how to
use python libraries.
Step 4: Asks trainees to perform the activity of step 3 and monitor the procedures.
Step 5: Verify whether the tasks are clearly performed.
Step 6: Provide feedback if necessary.
Step 7: Ask trainees to read key reading 3.3.2.
Points to Remember
• 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.
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 r M a n u a l
Application of learning 3.3.
You’re working for a retail store located in Nyanza District. You are tasked with analysing the
monthly sales data for a retail store. The sales data is manually defined in a Python dictionary.
The objective is to calculate total and average sales, and visualize the sales trend over the
months using Python libraries.
Checklist:
Observation
Criteria Indicators
Yes No
Pandas library is installed
Mathplotlib is installed
Python libraries Sample sales data are displayed
are well used DataFrame is created
Total and average sales are calculated
Visualize sales trend is performed
Decision
Solution/Output:
import pandas as pd
import [Link] as plt
# Sample sales data (replace with your actual data)
sales_data = {
"Month": ["Jan", "Feb", "Mar", "Apr", "May"],
"Sales": [10000, 12000, 15000, 8000, 13000]}
# Create a DataFrame
df = [Link](sales_data)
# Calculate total and average sales
total_sales = df["Sales"].sum()
average_sales = df["Sales"].mean()
print("Total Sales:", total_sales)
print("Average Sales:", average_sales)
# Visualize sales trend
[Link]([Link], df["Sales"])
[Link]("Month")
[Link]("Sales")
[Link]("Monthly Sales Trend")
[Link]()
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 r M a n u a l
Explaination:
● The pandas library is used to create a DataFrame from the sales data dictionary.
● The sum() and mean() functions are used to calculate total and average sales.
● Matplotlib is used to create a line chart to visualize the sales trend over the months.
Output:
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 r M a n u a l
Indicative content 3.4: Applying system Automation
Duration: 10 hrs
● While delivering this content, small groups can be used to identify task to automate
and to be prioritised.
Key steps:
Step 1: Introduce the activity and ask trainees to identify tasks to automate and to be
prioritized.
Step 2: Ask trainees to write their answers on paper or flipchart
Step 3: Ask trainees to present their findings
Step 4: Provide expert view by using didactic materials
Step 5: Address any questions or concerns
Step 6: Ask trainees to read the key reading 3.4.1 in the trainee manual
Points to Remember
● Automating certain tasks can greatly improve efficiency, reduce errors, and speed up
deployment processes.
● Automating these tasks not only saves time but also enhances the reliability of the
development and deployment processes.
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 r M a n u a l
Practical Activity 3.4.2: Installing Python Automation Libraries
● This activity should take place in computer lab where trainees have to select python
automation library.
Key steps:
Step 1: Introduce the topic and ask trainees to do the task described below:
As machine learning engineer, you are asked to go to the computer lab to install
python automation libraries.:
i. fabric
ii. ansible
iii. salt
iv. boto3
v. vsphere-automation-sdk
Points to Remember
● 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 like: pip
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 r M a n u a l
install fabric, pip install ansible, pip install salt, pip install boto3, pip install vSphere-
automation-sdk.
● This activity should take place in computer lab where trainees have to develop
python script.
Key steps:
Step 1: Introduce the topic and ask trainees to do the task described below:
As machine learning engineer, you are asked to go to the computer lab to develop
python scripts.
Step 2: Explain the task and provide clear work instruction.
Step 3: Demonstrate how to develop python scripts, while demonstrating explain the
steps to be followed.
Step 4: Asks trainees to perform the activity of step 3 and monitor the procedures.
Step 5: Verify whether the tasks are clearly performed.
Step 6: Provide feedback if necessary.
Step 7: Ask trainees to read key reading 3.4.3.
Points to Remember
● 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.
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 r M a n u a l
● By following these steps and incorporating best practices, you can create efficient,
maintainable, and well-structured Python scripts
● This activity should take place in computer lab where trainees have to integrate
script with deployment process.
Key steps:
Step 1: Introduce the topic and ask trainees to do the task described below:
As a machine learning engineer, you are asked to go to the computer lab to integrate
script with deployment process.
Step 2: Explain the task and provide clear work instruction.
Step 3: Demonstrate how to integrate script with deployment process, while
demonstrating explain the steps to be followed.
Step 4: Asks trainees to perform the activity of step 3 and monitor the procedures.
Step 5: Verify whether the tasks are clearly performed.
Step 6: Provide feedback if necessary.
Step 7: Ask trainees to read key reading 3.4.4.
Points to Remember
● While Integrating script with Deployment Process you follow the flowing steps:
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 r M a n u a l
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.
● This activity should take place in computer lab where trainees have to test and
monitor the automated tasks.
Key steps:
Step 1: Introduce the topic and ask trainees to do the task described below:
As a machine learning engineer, you are asked to go to the computer lab to test and
monitor the automated tasks.
Step 2: Explain the task and provide clear work instruction.
Step 3: Demonstrate how to test and monitor the automated tasks, while demonstrating
explain the steps to be followed.
Step 4: Asks trainees to perform the activity of step 3 and monitor the procedures.
Step 5: Verify whether the tasks are clearly performed.
Step 6: Provide feedback if necessary.
Step 7: Ask trainees to read key reading 3.4.5.
Points to Remember
● While testing and monitoring the automated task you have to: Thorough testing,
monitor script logs execution, and refine and improve.
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 r M a n u a l
Application of learning 3.4.
Manzi as a machine learning engineer, has built a web application for BERWA School. After
each deployment of the application, certain tasks must be automated to ensure the
application is correctly configured and ready for use. These tasks include configuring the
server, backing up the database, and sending notifications upon completion. To enhance
automation, Manzi decides to integrate a Python script into the deployment process, ensuring
it runs after each successful deployment and meets necessary security measures. As a
machine learning engineer, you are asked to integrate a Python script into the deployment
process to handle these tasks automatically, ensuring they are secure and run only after a
successful deployment.
Checklist:
Observation
Criteria Indicators
Yes No
Python boto3 is installed
Automation
Library are well import necessary packages and library is done
installed
Setup logging is performed
Function to get secrets from AWS Secrets
Manager is developed
Function to configure server is developed
Set environment variable for app mode is done
Python script is
Function to clean up temporary files is developed
developed
Function to trigger database backup is developed
Function to send notification (e.g., via email or
API) is developed
Main function to run post-deployment tasks is
developed
Decision
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 r M a n u a l
Solution/output:
import os
import subprocess
import shutil
import logging
from datetime import datetime
import boto3
# Setup logging
[Link](filename='post_deployment.log', level=[Link],
format='%(asctime)s - %(levelname)s - %(message)s')
# Function to get secrets from AWS Secrets Manager
def get_secret(secret_id):
try:
client = [Link]('secretsmanager')
secret_value = client.get_secret_value(SecretId=secret_id)
[Link](f"Successfully retrieved secret {secret_id}")
return secret_value['SecretString']
except Exception as e:
[Link](f"Failed to retrieve secret {secret_id}: {e}")
raise
# Function to configure server
def configure_server():
try:
# Set environment variable for app mode (example)
[Link]['APP_MODE'] = 'production'
[Link](f"Server configured to {[Link]('APP_MODE')} mode.")
except Exception as e:
[Link](f"Failed to configure server: {e}")
raise
# Function to clean up temporary files
def clean_temp_files():
try:
temp_dir = '/tmp/app_temp/'
if [Link](temp_dir):
[Link](temp_dir)
[Link](f"Temporary files in {temp_dir} cleaned.")
except Exception as e:
[Link](f"Failed to clean temporary files: {e}")
raise
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 r M a n u a l
# Function to trigger database backup
def trigger_backup():
try:
# Get database password from environment variables or secret manager
db_password = [Link]('DB_PASSWORD') or get_secret('DB_PASSWORD_SECRET_ID')
# Example of triggering a backup command (pseudo-command)
backup_command = f"backup_command --db production_db –password {db_password}"
[Link](backup_command.split(), check=True)
[Link]("Database backup completed.")
except [Link] as e:
[Link](f"Backup command failed: {e}")
raise
except Exception as e:
[Link](f"Failed to trigger backup: {e}")
raise
# Function to send notification (e.g., via email or API)
def send_notification(message):
try:
# Placeholder for sending notification (pseudo-code)
# For example, send an email or API request to a notification service
[Link](f"Notification sent: {message}")
except Exception as e:
[Link](f"Failed to send notification: {e}")
raise
# Main function to run post-deployment tasks
def main():
try:
[Link]("Starting post-deployment tasks.")
configure_server() # Configure the server environment
clean_temp_files() # Clean up temporary files
trigger_backup() # Trigger the database backup
send_notification("Post-deployment tasks completed successfully.") # Send success
notification
[Link]("All post-deployment tasks completed successfully.")
except Exception as e:
[Link](f"Post-deployment tasks failed: {e}")
send_notification(f"Post-deployment tasks failed: {e}")
raise
if __name__ == "__main__":
main()
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 r M a n u a l
Learning outcome 3 end assessment
Written assessment
ANSWER:
1. Class - A
2. Object - B
3. Inheritance - J
4. Polymorphism - C
5. Encapsulation - D
6. Method Overriding - G
7. Constructor - H
8. Data Hiding - I
9. Superclass - E
10. Subclass – F
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 r M a n u a l
II. Match the following Python libraries with their corresponding primary use cases:
ANSWER:
1. Matplotlib - C
2. NumPy - B
3. Pandas - A
4. Ansible - D
5. Datetime - E
2. Which of the following allows a class to inherit properties from multiple classes?
A) Single Inheritance
B) Multiple Inheritance
C) Multilevel Inheritance
D) Hierarchical Inheritance
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 r M a n u a l
ANSWERS: B) It initializes an object's attributes.
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.
ANSWER: C) datetime
7. What is the purpose of the timezone attribute in the datetime module?
A) To convert dates and times between different time zones
B) To set the current time zone for the system
C) To calculate time differences between time zones
D) To format dates and times according to a specific time zone
ANSWER: B) dateutil
9. What is the correct syntax for creating a datetime object representing the current
time?
A) [Link]()
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 r M a n u a l
B) [Link]()
C) [Link]()
D) [Link]()
ANSWER: A) [Link]()
10. Which Python library is commonly used for data visualization and plotting?
A) NumPy
B) Pandas
C) Matplotlib
D) datetime
ANSWER: C) Matplotlib
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.
11. The datetime module provides functions for formatting and parsing dates and times.
12. The dateutil library is primarily used for numerical operations on arrays and
matrices.
13. The arrow library offers a more intuitive API for working with dates and times.
14. The Pendulum library is specifically designed for time zone handling.
15. The Python-tzdata library is included by default in Python installations.
ANSWER:
1. True
2. False
3. False
4. False
5. True
6. True
7. True
8. True
9. True
10. False
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 r M a n u a l
11. True
12. False
13. True
14. False
15. False
ANSWER:
1. class
2. inheritance.
3. class
4. constructor
5. Method overriding
6. encapsulation
7. object
8. hierarchical
9. polymorphism
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 r M a n u a l
10. Encapsulation
11. strftime()
12. timedelta()
13. Ansible
14. schedule
15. Pandas
Practical assessment
As a machine learning engineer, 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.
Checklist:
Observation
Criteria Indicators
Yes No
Patient class with attributes like name, age,
gender, and disease are created
OOP concepts Specialized classes like In_patient and Outpatient
are well applied inheriting from Patient are created
Methods that behave differently based on patient
type are used
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 r M a n u a l
Patient information private and control access
through methods are kept secret
Records are aligned with Rwanda’s timezone
Python Date Timestamps for patient records are formated
and time
Days between tests and monitor recovery
concepts are
progress are calculated
well applied
Large datasets with patient info are managed
Pytz library is installed
Python Libraries
Datetime library is imported
are well applied
Pandas library is installed
System Fabric or ansible library is installed
Automation is The script is written depending on task to
well applied automate
Decision
Solution:
from datetime import datetime
import pytz
def get_patient_info(self):
return {
"name": self.__name,
"age": self.__age,
"gender": self.__gender,
"disease": self.__disease,
"recorded_at": self.__recorded_at.strftime("%Y-%m-%d %H:%M:%S")}
# InPatient class
class InPatient(Patient):
def __init__(self, name: str, age: int, gender: str, disease: str, room_number: str,
admission_date: datetime):
super().__init__(name, age, gender, disease)
self.room_number = room_number
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 r M a n u a l
self.admission_date = admission_date
def get_patient_info(self):
info = super().get_patient_info()
info['room_number'] = self.room_number
info['admission_date'] = self.admission_date.strftime("%Y-%m-%d %H:%M:%S")
return info
# OutPatient class
class OutPatient(Patient):
def __init__(self, name: str, age: int, gender: str, disease: str, visit_date: datetime):
super().__init__(name, age, gender, disease)
self.visit_date = visit_date
def get_patient_info(self):
info = super().get_patient_info()
info['visit_date'] = self.visit_date.strftime("%Y-%m-%d %H:%M:%S")
return info
# Admission details
room_number = input("Enter room number (for inpatient): ")
admission_date_str = input("Enter admission date (YYYY-MM-DD): ")
admission_date = [Link](admission_date_str, "%Y-%m-
%d").replace(tzinfo=[Link]('Africa/Kigali'))
# Create InPatient object
inpatient = InPatient(name, age, gender, disease, room_number, admission_date)
# Discharge details
discharge_date_str = input("Enter discharge date (YYYY-MM-DD): ")
discharge_date = [Link](discharge_date_str, "%Y-%m-
%d").replace(tzinfo=[Link]('Africa/Kigali'))
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 r M a n u a l
# Daily rate example
daily_rate = float(input("Enter daily rate: "))
# Calculate payment
total_payment = inpatient.calculate_payment(daily_rate, discharge_date)
# Example usage
if __name__ == "__main__":
manage_patients()
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 r M a n u a l
Further information to the trainer
Goodfellow, I., Bengio, Y., Courville, A., & Bengio, Y. (2016). Deep Learning (Adaptive
Computation and Machine Learning series). MIT Press.
Murphy, K. P. (2012). Machine Learning: A Probabilistic Perspective. MIT Press.
Has e, T., Tibshirani, R., & Friedman, J. (2009). The Elements of Statistical Learning:
Data Mining, Inference, and Prediction. Springer.
Chollet, F. (2017). Deep Learning with Python. Manning Publications.
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.
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
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 r M a n u a l
Mm, YYY
October, 2024
106 | M o d u l e t i t l e – T r a i n e r M a n u a l