TeM GENPP50 Python Programming
TeM GENPP50 Python Programming
GENPP501
NETWORKING AND
INTERNET
TECHNOLOGIES
Python
Programming
Fundamentals
TRAINEE'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 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 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 e 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 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
Indicative content 3.4: Applying System Automation -------------------------------------------- 147
Learning outcome 3 end assessment ---------------------------------------------------------------- 162
References-------------------------------------------------------------------------------------------------- 165
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
ACRONYMS
ix | 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 Networking and
Internet Technologies, 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:
6. Application of python
The applications of Python programming are diverse and span various fields.
6.1. Data Science
Data analysis: Python's libraries like NumPy, Pandas, and Matplotlib facilitate
data cleaning, exploration, and visualization.
Machine learning: Frameworks like TensorFlow and PyTorch enable building
and training complex machine learning models.
Deep learning: Python is widely used for developing deep neural networks for
tasks like image recognition and natural language processing.
6.2. Software Development
Web development: Frameworks like Django and Flask streamline the creation
of web applications.
Desktop applications: Libraries like Tkinter, PyQt, and wxPython allow for
building graphical user interfaces.
Game development: Pygame is a popular framework for creating simple
games.
6.3. Automation:
Task automation: Python can automate repetitive tasks, such as sending emails,
downloading files, or interacting with web applications.
System administration: Python scripts can be used to automate system
management tasks, like backing up data or monitoring system performance.
6.4. Data Analysis:
Statistical analysis: Python's libraries like SciPy and Stats models provide tools
for statistical analysis and modelling.
Data mining: Python can be used for discovering patterns and trends in large
datasets.
Data visualization: Matplotlib and Seaborn allow for creating informative and
visually appealing charts and graphs.
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
A strong community and good support can make a big difference. Look for tools
with active communities, frequent updates, and responsive support.
1.7. Security
Ensure the tool has robust security features, especially if you’re dealing with
sensitive data.
1.8. Cost
Consider the cost of the tool. While some tools are free and open-source, others
may require a subscription or one-time purchase.
1.9. Flexibility
The tool should be flexible enough to adapt to your project’s evolving needs. It
should allow for customization and extension.
1.10. Compatibility
Ensure the tool is compatible with your operating system and other tools you plan
to 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
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
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.
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
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
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
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
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: 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
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
● 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.
● Key characteristics of python include: Readability, Versatility, Efficiency and
Community and Ecosystem.
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
● 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, Matplotlib.
● In python we can use the following automation Libraries: Selenium, PyAutoGUI,
Requests, Beautiful Soup, Airflow, Celery, Paramiko, Fabric, Pywinauto, And
Schedule.
● 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 web 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.
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).
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
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.).
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
b. RUN the Installer
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).
Click "Install Now" or "Customize installation" for more advanced options.
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
Select the Windows installer.
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
A Python virtual environment is a tool that helps you create an isolated
environment for your Python projects. This means you can manage dependencies
for each project separately, avoiding conflicts between different projects’
requirements.
2. Creating a Virtual Environment
Open your terminal or command prompt.
Navigate to your project directory.
Run the following command “python -m venv myenv”
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
4. Deactivating the Virtual Environment
To exit the virtual environment, simply run
“deactivate”
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
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
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
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.
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
Indicative content 1.3: Testing Python Installation
Duration: 5 hrs
Task:
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
Exit the Interpreter
To exit, type “exit()” or press Ctrl + D (macOS/Linux) or Ctrl + Z followed by Enter
(Windows).
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
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 e M a n u a l
Learning outcome 1 end assessment
Written assessment
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) Machine learning
c) Data visualization
d) Game development
16. Which of the following is NOT a characteristic of Python?
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?
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
a) PyCharm
b) Jupyter Notebook
c) Visual Studio Code
d) Thonny
24. The command to deactivate a Python virtual environment is:
a) end venv
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 ____________.
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
III. Matching questions
1. Match the IDE in column A with their corresponding primary features in column B
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
…….. d) Versatility (iv) Wide range of applications
5. Match the Python command in column A with its corresponding function of column B
Answers Column A Column B
…….. a) python --version (i) Display the Python version
…….. b) pip install (iii) Install Python packages
…….. c) deactivate (iv) Exit the virtual environment
…….. d) pip list (ii) Display installed packages
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 venv (iii) Creates a new virtual environment
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
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
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
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 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.
The company will provide all tools, materials and equipment.
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
References
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
Learning Outcome 2: Write Basic Python Program
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
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
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
Duration: 45 hrs
Resources
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
Indicative content 2.1: Applying Python Basic Concepts
Duration: 9 hrs
Tasks:
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
Floating Point Numbers (float): Decimal numbers, e.g., 3.14, -0.001.
Strings (str): Sequences of characters, e.g., "Hello, World!".
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 (=).
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
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
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
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
For multi-line comments, you can use triple quotes:
"""
This is a
multi-line comment
"""
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
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
not in: Returns True if a sequence with the specified value is not present in the object
Task:
1. Data Types
Application: Using different data types to store and manipulate various kinds of data.
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
# Different data types
integer_value = 42 # Integer
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
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
4. Operators
Application: Performing calculations and comparisons.
4.1 A
rithmetic Operators
# 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
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
x=5
y = 10
# Equal to
print(f"{x} == {y}: {x == y}")
# 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
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
# Add and assign
num += 5
print(f"After += 5, num = {num}")
Points to Remember
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
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.
elsif
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
Key Points:
if number % 2 == 0:
print(f"{number} is even.")
else:
print(f"{number} is odd.")
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
grade = 'D'
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:
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
Key readings 2.2.2 Application of Looping Statements
1. Introduction
Looping statements in Python allow you to execute a block of code multiple times. 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:
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
4. Looping with Conditional Statements
Application: Combining loops with conditional statements to filter results.
# Using a loop with a conditional statement
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print("Even numbers:")
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:
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
Key readings 2.2.3 Using Jump Statements
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:
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)
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
Note: All jump statements are written in small letter while developing python program.
Points to Remember
● Conditional statements are used to execute different code blocks based on specific
conditions.
● The if statement is used to execute a block of code if a condition is true.
● 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.
● 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.
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
Write a python program that can display all even numbers from 0 to 100 and the program skip
60 and stops execution if value is equal to 90.
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
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.
Definition of Function
Functions help organize code, making it more modular and easier to understand.
def greet(name):
print(f"Hello, {name}!")
Characteristics of Functions
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
Modularity: Functions allow you to break your program into smaller, manageable
pieces.
Reusability: Once defined, functions can be reused multiple times throughout the
code.
Parameters and Return Values: Functions can accept parameters and return values,
making them flexible.
Encapsulation: Functions encapsulate the logic of a task, which can improve code
clarity.
Scope: Variables defined inside a function are local to that function unless specified
otherwise.
Advantages of Functions
Code Reusability: Functions can be reused across different parts of a program or even
in different programs.
Debugging: Isolating functionality into functions simplifies debugging since you can
test each function independently.
Types of Functions
These are functions that are pre-defined in Python and can be used without any
additional code.
Examples include:
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
type(): Returns the type of an object.
numbers = [1, 2, 3, 4, 5]
These are functions that you define yourself to perform specific tasks. You can create
them using the def keyword.
Task:
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
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.
"""
Example
# Code block to execute
def return
greet(name):
value # Optional
"""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
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
4. Passing a List as an Argument
You can pass a list (or any other collection) as an argument to a function. Inside the
function, you can manipulate it as needed.
Example:
def print_fruits(fruits):
"""This function prints each fruit in the list."""
for fruit in fruits:
print(fruit)
Task:
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
Lambda Functions
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.
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
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
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.
You should use the lambda function to create simple expressions. For example,
expressions that do not include complex structures such as if-else, for-loops, and so
on.
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()
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)
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
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
df = pd.DataFrame(
{"name": ["IBRAHIM", "SEGUN", "YUSUF", "DARE", "BOLA", "SOKUNBI"],
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
"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.
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
1. 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.
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
2. 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!
3. 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():
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
print("Display function executed.")
# Calling the decorated function
display()
# Outputs:
# Wrapper executed before display
# Display function executed.
4. 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
5. 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:
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
Points to Remember
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
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.
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
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}
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
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)
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
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
Example:
from collections import Counter
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
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
Practical Activity 2.4.2: Performing common operations on collection
Task:
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
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.2. Dictionaries
# Accessing values
print(student['name']) # Outputs: Alice
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]
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
2. Using .sort() (Modifies the List In-Place)
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
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)
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
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}
]
Summary
Collect Sorting Method Ascending Descending
ion
Type
List .sort() (modifies) sorted(list) sorted(list,
or sorted() reverse=True)
Tuple sorted() sorted(tuple) sorted(tuple,
reverse=True)
Diction sorted(dict.items( sorted(dict.items( sorted(dict.items(),
ary )) )) reverse=True)
(Keys)
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
Diction sorted(dict.items( sorted(dict.items( sorted(dict.items(),
ary ), key=lambda x: ), key=lambda x: key=lambda x: x[1],
(Value x[1]) x[1]) reverse=True)
s)
Set sorted(set) sorted(set) sorted(set,
reverse=True)
Custo sorted(objects, sorted(objects, sorted(objects,
m key=lambda x: key=lambda x: key=lambda x:
Object x['property']) x['property']) x['property'],
s reverse=True)
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)
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
# Filter even numbers
even_numbers = tuple(x for x in numbers if x % 2 == 0)
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}
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
Use filter() for functional-style filtering.
Use comprehensions for a concise, readable approach.
For dictionaries, comprehensions are the primary way to filter based on keys or
values.
# 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')
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
# Pop
top_element = stack.pop()
print(top_element) # Outputs: C
print(stack) # Outputs: ['A', 'B']
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.
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).
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
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
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
content = path.read_text()
print(content)
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
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
df.to_csv('new_data.csv', index=False)
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).
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
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.")
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:
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
1. Read the task bellow:
As machine learning engineer, you are requested to go to the computer lab to perform the
following operations on file:
Write
Create
Delete file
2. Refers to provided key reading 2.5.3, perform the task described above.
3. Present your work to the trainer and whole class.
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.")
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
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)
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):
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
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}")
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.
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
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
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
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
4. Error Handling and Testing
Use Exceptions: Use try and except blocks for error handling to make your code
robust. Handle specific exceptions rather than using a bare except.
Example:
try:
result = 10 / 0
except ZeroDivisionError:
print("You cannot divide by zero.")
Assertions: Use assertions to enforce conditions that must be true for your program
to work correctly.
Example:
def divide(a, b):
assert b != 0, "The denominator cannot be zero."
return a / b
Unit Testing: Write unit tests using the unittest or pytest framework to ensure that
your code works as expected. Testing helps catch bugs early and improves code
reliability.
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.
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
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.
● 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.
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
Learning outcome 2 end assessment
Theoretical assessment
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
D) Ends the program
15. Which of the following is used to create a set in Python?
A) []
B) ()
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)
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
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.
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
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
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 cart.csv The project will be implemented using Python.
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
References
Hitimana, 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.
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.
https://www.jetbrains.com/help/pycharm/quick-start-guide.html visited on 19.10.2024
Python Software Foundation. (n.d.). Installing Python. Retrieved from
https://www.python.org/downloads/ visited on 19.10.2024
JetBrains. (n.d.). Install PyCharm. Retrieved from
https://www.jetbrains.com/pycharm/download/ visited on 19.10.2024
https://www.youtube.com/watch?v=kqtD5dpn9C8
https://www.coursera.org/specializations/python
https://cs50.harvard.edu/python/2022/
https://www.coursera.org/specializations/python
https://docs.python.org/3/
https://automatetheboringstuff.com/
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
Learning Outcome 3: Apply Object-Driven in Python
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
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
Key Competencies for Learning Outcome 3: Apply object-driven in python
Knowledge Skills Attitudes
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
Duration: 40 hrs
Resources
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
Indicative content 3.1: Applying OOP Concepts
Duration: 10 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()
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
print(p1.x)
The __init__() Function
The examples above are classes and objects in their simplest form, and are not
really useful in real life applications.
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
Single Inheritance: A subclass inherits from one superclass.
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"
class Duck(Flyer, Swimmer):
pass
duck = Duck()
print(duck.fly()) # Output: Flying
print(duck.swim()) # Output: Swimming
class Dog(Animal):
def bark(self):
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
return "Bark"
class Puppy(Dog):
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:
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
def sound(self):
return "Some sound"
class Dog(Animal):
def sound(self):
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())
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
Code Reusability: Common interfaces can be used across different classes.
Simplification: Code becomes easier to read and maintain by using a consistent
interface.
5. Encapsulation
5.1. Definition
Encapsulation in Python is an object-oriented programming principle that restricts
direct access to certain components of an object. This is done to protect the internal
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
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
print("Deposit amount must be positive.")
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:
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
1. Introduction
Classes and objects in Python enable developers to model real-world entities and their
behavior. This object-oriented approach promotes code organization, reusability, and
abstraction.
2. Application of classes and object
Here are some common applications of classes and objects, along with examples.
2.1. Modeling Real-World Entities
Classes can represent real-world entities with attributes and methods.
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
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
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}"
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):
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
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
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():
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
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
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
operation = input("Enter the operation number (1/2/3/4): ")
Task:
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()}")
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
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()}")
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
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!
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
# Base class for a bank account
class BankAccount:
def __init__(self, owner, balance=0):
# Initialize the account with owner and starting balance
self.owner = owner
self.balance = balance
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}"
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
super().__init__(owner, balance)
self.overdraft_limit = overdraft_limit
# User operations
while True:
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
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
Task:
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
3. Apply safety precautions.
4. Referring to the steps provided in key readings, develop the required program.
5. Present out the steps to be followed.
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 polymorphism
shapes = [Rectangle(10, 5), Circle(7)]
for shape in shapes:
print(f"Area: {shape.area()}")
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.2. Duck Typing
Python’s dynamic typing allows objects to be used based on their behavior rather than
their actual type, a concept known as duck typing.
Example: Flying Objects
class Bird:
def fly(self):
return "Flapping wings"
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
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
Example: Print Function
def print_info(data):
if isinstance(data, str):
print(f"String: {data}")
elif isinstance(data, int):
print(f"Integer: {data}")
elif isinstance(data, list):
print(f"List: {data}")
# Using the function
print_info("Hello") # Output: String: Hello
print_info(42) # Output: Integer: 42
print_info([1, 2, 3]) # Output: List: [1, 2, 3]
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
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: ")
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
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
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
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
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
else:
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)
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
print(emp.get_salary()) # Output: 60000
2.5. Security
Encapsulation enhances security by restricting access to sensitive data. This is
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
particularly important in applications handling confidential information.
Example: User Credentials
class User:
def __init__(self, username, password):
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
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
● 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: Code Reusability, Method
Overriding, Creating a Hierarchical Structure, Multiple Inheritance and Framework
and Library Development.
● 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
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
Indicative content 3.2: Applying python Date and Time Concepts
Duration: 10 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
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
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)
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
4. Pendulum
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
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
ny_time = utc_time.astimezone(new_york_zone)
print("New York time:", ny_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)
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
Return the year and name of weekday:
import datetime
x = datetime.datetime.now()
print(x.year)
print(x.strftime("%A"))
1.2. Creating Date Objects
To create a date, we can use the datetime() class (constructor) of the datetime
module.
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"))
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
%w Weekday as import datetime 2
a number 0- x = datetime.datetime.now()
6, 0 is Sunday print(x.strftime("%w"))
%d Day of month import datetime 23
01-31 x = datetime.datetime.now()
print(x.strftime("%d"))
%b Month import datetime Dec
name, short x = datetime.datetime.now()
version print(x.strftime("%b"))
%B Month import datetime Decemb
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"))
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
# Define time zones
utc_zone = pytz.utc
new_york_zone = pytz.timezone('America/New_York')
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
with dates and times, allowing you to easily calculate relative dates.
Example:
from datetime import datetime, timedelta
# Current date and time
now = datetime.now()
print("Current date and time:", now)
# Calculate relative dates
tomorrow = now + timedelta(days=1)
print("Tomorrow:", tomorrow)
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.
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
● 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.
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.3: Applying Python Libraries
Duration: 10 hrs
Tasks:
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
Description: Matplotlib is a plotting library for Python that enables the creation of static,
animated, and interactive visualizations. It is highly customizable and works well with
NumPy and Pandas.
Key Features
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()
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
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
print("Array:\n", arr)
print("Sum:", np.sum(arr))
print("Mean:", np.mean(arr))
print("Transpose:\n", arr.T)
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])
Tasks:
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
As machine learning engineer, you are asked to go to the computer lab to use python
libraries described in key readings 3.3.1.
2. Refers to provided key reading 3.3.2, perform the task described above.
3. Present your work to the trainer and whole class.
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
'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)
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
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
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.
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.
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
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.
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
Indicative content 3.4: Applying System Automation
Duration: 10 hrs
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
Tasks that are performed frequently (e.g., daily, weekly).
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:
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
Fabric is a simple and lightweight Python library for streamlining the use of SSH for
application deployment and system administration tasks.
Key Features:
SSH command execution and file transfer.
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.
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.
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.
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
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.
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.
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
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
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?
Tasks:
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.
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
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
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()
]
)
# 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)
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
Breakdown of the Script
a. 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.
b. 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.
c. Main Execution Block
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:
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
After the main deployment tasks are completed, the script can be triggered
automatically. This can be done using a simple command in a shell script or a
deployment tool.
Example:
# Shell script to deploy an application and trigger the Python script
#!/bin/bash
# Deploy the application (pseudo-command)
echo "Deploying application..."
# (Your deployment commands here)
# Trigger the Python deployment script
python3 deploy_script.py
Step2 : Direct Execution After Deployment Completion
You can directly call the Python script at the end of your deployment process, ensuring
it runs only after the main deployment is successful.
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
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
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.
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
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
smooth and secure deployment workflow. Always prioritize securing sensitive
information and controlling access to your automation scripts.
Task:
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
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.
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.
3. Refine and Improve
Continuous improvement is key to maintaining a robust automation script:
a. Code Review
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
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
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:
Unit Test
def upload_files(local_path, remote_path):
# Simulate file upload
if not local_path or not remote_path:
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
raise ValueError("Both paths are required")
return True # Simulate successful upload
Run the Tests
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")
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
159 | 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
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-
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.
160 | 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
● 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.
● While testing and monitoring the automated task you have to: Thorough testing,
Monitor script logs execution, Refine and improve.
161 | 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
162 | 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) Inheritance
D) Multilevel Inheritance
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)
163 | 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. Data hiding is a feature of __________ that restricts direct access to some attributes.
7. A __________ is an instance of a class.
8. Inheritance allows for the creation of a __________ structure among classes.
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 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
164 | 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
165 | 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