0% found this document useful (0 votes)
59 views

Lecture notes on Introduction to Python programming final

Uploaded by

Gershon Ayieko
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
59 views

Lecture notes on Introduction to Python programming final

Uploaded by

Gershon Ayieko
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 68

@edgar cc.

LECTURE NOTES
UNIT NAME: Python Programming
PREPARED BY: Edgar Addero

TOPIC 1: INTRODUCTION TO PYTHON


Overview of Python and Its Applications
Python is a high-level, interpreted programming language created by Guido
van Rossum and first released in 1991. Known for its simplicity and
readability, Python is designed to be easy to learn and use, making it an ideal
choice for beginners and experienced developers alike.
Key Features of Python
1. Readability: Python syntax is clear and intuitive, making code easy to
read and understand.
2. Interpreted Language: Python code is executed line-by-line, allowing for
immediate feedback and easier debugging.
3. Dynamically Typed: Variable types are determined at runtime, which
provides flexibility in coding.
4. Extensive Libraries: Python has a rich ecosystem of libraries and
frameworks that extend its functionality, supporting various
applications.
5. Cross-Platform: Python runs on multiple operating systems, including
Windows, macOS, and Linux.
Applications of Python
Python is versatile and widely used across different domains:
1. Web Development:
• Frameworks like Django and Flask facilitate building robust web
applications.
• Supports backend development, REST APIs, and more.
2. Data Science and Analytics:
• Libraries such as Pandas, NumPy, and Matplotlib are used for
data manipulation, analysis, and visualization.
• Widely adopted in data-driven decision-making processes.
3. Machine Learning and Artificial Intelligence:
• Python is a preferred language for machine learning frameworks
like TensorFlow and Scikit-learn.
• Enables the development of predictive models and AI
applications.
4. Automation and Scripting:

1
@edgar cc.

• Python scripts are commonly used for automating repetitive


tasks, such as file management and data entry.
• Tools like Selenium allow for web testing and automation.
5. Game Development:
• Libraries such as Pygame enable developers to create games
and interactive applications.
• Used for prototyping and developing simple games.
6. Scientific Computing:
• Python is used in scientific research for simulations,
mathematical modeling, and data analysis.
• Libraries like SciPy provide tools for scientific computing.
7. Internet of Things (IoT):
• Python can be used to program IoT devices, often in conjunction
with platforms like Raspberry Pi.
• Supports various IoT applications, from home automation to
industrial monitoring.

Here are some notable examples of real software applications that have been
developed using Python:
1. YouTube
• Description: The world’s largest video-sharing platform uses Python
for various functionalities, including video processing and
management.
2. Instagram
• Description: Instagram's backend is primarily built using Python,
leveraging its efficiency in handling web requests and data.
3. Spotify
• Description: This music streaming service uses Python for data
analysis, backend services, and recommendation algorithms.
4. Dropbox
• Description: Dropbox’s desktop client is written in Python, allowing for
cross-platform compatibility and ease of use.
5. Reddit
• Description: The social news aggregation site was originally built in
Lisp but was rewritten in Python to improve performance and
scalability.
6. Pinterest
• Description: Pinterest uses Python for its server-side application,
particularly for data handling and processing.

2
@edgar cc.

7. Google
• Description: Google employs Python in various services, including
their search algorithms, and supports Python in its cloud services.
8. Quora
• Description: This question-and-answer platform uses Python for its
backend, allowing for rapid development and deployment.
9. BitTorrent
• Description: The popular file-sharing protocol implementation has
components that are built in Python, facilitating its functionality.
10. OpenStack
• Description: This cloud computing platform is developed in Python
and is widely used for managing and deploying cloud infrastructure.
11. Ansible
• Description: A powerful IT automation tool, Ansible is written in Python
and is used for configuration management and application deployment.
12. TensorFlow
• Description: While TensorFlow itself is a library for machine learning, it
enables the development of a wide range of applications and
frameworks, and it supports Python as a primary interface.
13. Blender
• Description: Blender is an open-source 3D creation suite that uses
Python for scripting and automation within the software.
14. Pandas
• Description: A widely used data analysis and manipulation library in
Python, essential for data scientists and analysts.

Python's simplicity, versatility, and rich ecosystem have made it one of the
most popular programming languages today. Its applications span numerous
fields, making it an essential tool for developers, data scientists, and
researchers. Whether you're building a web application, analyzing data, or
developing machine learning models, Python provides the tools and libraries
needed to succeed.

Installing Python and Setting Up the


Environment

3
@edgar cc.

Installing Python and setting up your development environment is a


straightforward process. Below are step-by-step instructions to help you get
started.
1. Downloading Python
Step 1: Visit the Official Python Website
• Go to the Python official website.
Step 2: Choose the Latest Version
• Click on the "Downloads" section. The site usually recommends the
latest version for your operating system (Windows, macOS, or Linux).
2. Installing Python
Step 1: Run the Installer
• After downloading the installer, run it.
Step 2: Follow the Installation Prompts
1. Check "Add Python to PATH":
• This option is crucial as it makes Python accessible from the
command line.
2. Choose Installation Type:
• You can select "Install Now" for the default settings or
"Customize Installation" to choose specific features.
Step 3: Complete the Installation
• Click "Install" and wait for the process to finish.
• Once the installation is complete, you can close the installer.

3. Verifying the Installation


Step 1: Open Command Prompt or Terminal
• For Windows: Press Win + R, type cmd, and hit Enter.
• For macOS: Open Terminal from the Applications folder.
• For Linux: Open your terminal from the applications menu.
Step 2: Check the Python Version
• Type the following command and press Enter:
python --version
or
python3 --version
• You should see the installed Python version displayed in the terminal.
4. Setting Up the Development Environment
Recommended Tools
1. Text Editors and IDEs:
• Visual Studio Code: A powerful and customizable code editor
with Python support.

4
@edgar cc.

•PyCharm: A feature-rich IDE specifically designed for Python


development.
• Jupyter Notebook: Ideal for data science and interactive coding,
allowing you to run code in blocks.
Step 1: Install a Text Editor or IDE
• Download and install your preferred text editor or IDE:
• Visual Studio Code: Download VS Code
• PyCharm: Download PyCharm
• Jupyter Notebook: Install via pip (Python package manager):
pip install notebook
Step 2: Configure the Editor/IDE for Python
• For Visual Studio Code:
• Install the Python extension from the Extensions Marketplace.
• For PyCharm:
• Follow the setup instructions to create a new Python project.
• For Jupyter Notebook:
• Launch it by typing jupyter notebook in the terminal.

5. Writing Your First Python Program


Step 1: Create a New Python File
• Open your text editor or IDE and create a new file named hello.py.
Step 2: Write the Code
print("Hello, World!")
Step 3: Save the File
Step 4: Run the Program
• In your terminal, navigate to the directory where hello.py is saved and
run:
python hello.py
or
python3 hello.py
Output
You should see:
Hello, World!

5
@edgar cc.

TOPIC 2: BASIC SYNTAX AND DATA TYPES IN


PYTHON
Python is known for its clean and easy-to-read syntax. Understanding how to
define variables and use different data types is fundamental to programming
in Python. This guide covers the basic syntax along with the four primary
data types: integers, floats, strings, and booleans.
Basic Syntax
1. Comments
• Single-line Comment: Begins with a #.
# This is a single-line comment
• Multi-line Comment: Enclosed in triple quotes (''' or """).
"""
This is a
multi-line comment
"""
2. Indentation
• Python uses indentation (spaces or tabs) to define code blocks.
Consistent indentation is crucial for code execution.
Variables
A variable is a name that refers to a value. In Python, you do not need to
declare a variable type explicitly; Python infers the type based on the
assigned value.
Variable Assignment
x = 5 # Integer
name = "Alice" # String

Data Types
1. Integer (int)
• Represents whole numbers, both positive and negative.
• Example:
age = 30
2. Float (float)
• Represents numbers with a decimal point (floating-point numbers).
• Example:
price = 19.99
3. String (str)
• Represents a sequence of characters enclosed in single (') or double (")
quotes.
• Example:
greeting = "Hello, World!"
4. Boolean (bool)

6
@edgar cc.

• Represents one of two values: True or False.


• Example:
is_student = True

Examples of Using Variables and Data Types


Example Code
# Integer
age = 25
print("Age:", age)

# Float
height = 5.9
print("Height:", height)

# String
name = "John Doe"
print("Name:", name)

# Boolean
is_employed = False
print("Is Employed:", is_employed)
Output
When you run the above code, the output will be:
Age: 25
Height: 5.9
Name: John Doe
Is Employed: False

Type Checking
You can check the data type of a variable using the type() function:
print(type(age)) # <class 'int'>
print(type(height)) # <class 'float'>
print(type(name)) # <class 'str'>
print(type(is_employed)) # <class 'bool'>

Understanding variables and data types is essential for effective


programming in Python. The ability to work with different data types allows
you to represent and manipulate information in various ways. As you
continue learning Python, you'll use these fundamentals to build more
complex programs.

Basic Input and Output in Python


Input and output (I/O) operations are fundamental to any programming
language, including Python. This guide covers how to take user input and
display output in Python.

7
@edgar cc.

1. Output in Python
Using the print() Function
The print() function is used to display output to the console. It can take
multiple arguments and format them.
Basic Usage
print("Hello, World!")
Printing Variables
You can print variables directly:
name = "Alice"
age = 30
print("Name:", name)
print("Age:", age)
String Formatting
1. Using f-Strings (Python 3.6+):

f-Strings provide a concise and efficient way to format strings in


Python, making code more readable and easier to maintain. They are
particularly useful for embedding expressions and formatting numbers
directly within strings.

print(f"{name} is {age} years old.")


format()
2. Using the Method:

The format() method in Python is a versatile way to format strings. It


allows you to insert values into strings using placeholders, making it a
powerful tool for creating dynamic output.
print("{} is {} years old.".format(name, age))
3. Using Percent Formatting:

Percent formatting in Python is an older method of string formatting


that uses the % operator. Although it is less common now due to the
introduction of str.format() and f-Strings, it is still useful to know.
print("%s is %d years old." % (name, age))

2. Input in Python
Using the input() Function
The input() function allows you to take input from the user. By default, it
returns the input as a string.
Basic Usage
user_input = input("Enter your name: ")
print("Hello,", user_input)

8
@edgar cc.

Type Conversion
Since input is returned as a string, you may need to convert it to another
type, such as int or float.
Example of Type Conversion:
age = input("Enter your age: ")
age = int(age) # Convert the input to an integer
print("Next year, you will be", age + 1)

Complete Example: Input and Output


Here’s a complete example combining input and output:
# Get user input
name = input("Enter your name: ")
age = input("Enter your age: ")
age = int(age) # Convert age to an integer

# Output the results


print(f"{name} is {age} years old.")
print(f"Next year, {name} will be {age + 1} years old.")
Expected Output
If the user inputs "Alice" for the name and "30" for the age, the output will be:
Alice is 30 years old.
Next year, Alice will be 31 years old.
Understanding basic input and output operations in Python is essential for
interacting with users and processing their data. The print() function allows
you to display information, while the input() function enables you to gather
user input. By combining these features, you can create interactive programs
that respond to user data effectively.

String Operations and Formatting in Python


Strings are one of the most commonly used data types in Python. This guide
will cover various string operations and formatting techniques that can help
you manipulate and display strings effectively.
1. Basic String Operations
Creating Strings
Strings can be created by enclosing characters in either single (') or double
(") quotes.
string1 = 'Hello, World!'
string2 = "Python is fun!"
Accessing Characters
You can access individual characters in a string using indexing (starting from
0).
first_char = string1[0] # 'H'
last_char = string1[-1] # '!'

9
@edgar cc.

Slicing Strings
You can extract a substring using slicing.
substring = string1[0:5] # 'Hello'
String Length
Use the len() function to get the length of a string.
length = len(string1) # 13
Concatenation
You can combine strings using the + operator.
greeting = string1 + " " + string2 # 'Hello, World! Python is fun!'
Repetition
You can repeat a string using the * operator.
repeat = "Ha" * 3 # 'HaHaHa'

2. String Methods
Python provides a variety of built-in string methods that allow you to
manipulate strings easily.
Common String Methods
• str.lower(): Converts a string to lowercase.

print(string1.lower()) # 'hello, world!'


str.upper()
• : Converts a string to uppercase.
print(string1.upper()) # 'HELLO, WORLD!'
str.strip()
• : Removes leading and trailing whitespace.
whitespace_string = " Hello "
print(whitespace_string.strip()) # 'Hello'
str.replace(old, new)
• : Replaces occurrences of a substring.
new_string = string1.replace("World", "Python") # 'Hello, Python!'
str.split(delimiter)
• : Splits a string into a list based on a delimiter.
words = string1.split(", ") # ['Hello', 'World!']
str.join(iterable)
• : Joins elements of an iterable into a single string using
a specified separator.
fruits = ["apple", "banana", "cherry"]
fruit_string = ", ".join(fruits) # 'apple, banana, cherry'

3. String Formatting
Python offers several ways to format strings for output. Here are the most
common methods:
1. f-Strings (Python 3.6+)

10
@edgar cc.

f-Strings allow you to embed expressions inside string literals using curly
braces {}.
name = "Alice"
age = 30
formatted_string = f"{name} is {age} years old."
# Output: 'Alice is 30 years old.'
2. str.format()
The format() method allows you to format strings using placeholders.
formatted_string = "{} is {} years old.".format(name, age)
# Output: 'Alice is 30 years old.'
3. Percent Formatting
This is an older method of string formatting that uses the % operator.
formatted_string = "%s is %d years old." % (name, age)
# Output: 'Alice is 30 years old.'

Complete Example
Here’s a complete example demonstrating string operations and formatting:
# String variables
name = "Alice"
age = 30
hobby = "painting"

# Basic operations
greeting = f"Hello, my name is {name}."
info = f"I am {age} years old and I enjoy {hobby}."

# Output
print(greeting)
print(info)

# String manipulation
new_info = info.replace("enjoy", "love")
print(new_info)

# Using string methods


print(name.lower())
print(name.upper())
Expected Output
Hello, my name is Alice.
I am 30 years old and I enjoy painting.
I am 30 years old and I love painting.
alice
ALICE

String operations and formatting are essential skills in Python programming.


Understanding how to manipulate strings and format them for output will help
you create more dynamic and user-friendly applications. With the rich set of
string methods and formatting techniques available in Python, you can
handle text data efficiently and effectively.

11
@edgar cc.

TOPIC 3: CONTROL STRUCTURES IN PYTHON


Control structures allow you to dictate the flow of execution in your
programs. One of the most common types of control structures is conditional
statements, which enable your program to make decisions based on certain
conditions. In Python, conditional statements are implemented using if, elif,
and else.
1. Conditional Statements
1.1 if Statement
The if statement evaluates a condition (an expression that results
in True or False). If the condition is True, the block of code inside
the if statement is executed.
Syntax
if condition:
# Code to execute if condition is True
Example
age = 18

if age >= 18:


print("You are an adult.")
1.2 elif Statement
The elif (short for "else if") statement allows you to check multiple
conditions. If the first if condition is False, the program checks
the elif condition.
Syntax
if condition1:
# Code if condition1 is True
elif condition2:
# Code if condition2 is True
Example
age = 16

if age >= 18:


print("You are an adult.")
elif age >= 13:
print("You are a teenager.")
1.3 else Statement
The else statement is used to define a block of code that will execute if none
of the preceding conditions are True.
Syntax
if condition:
# Code if condition is True
else:
# Code if condition is False
Example
age = 10

12
@edgar cc.

if age >= 18:


print("You are an adult.")
elif age >= 13:
print("You are a teenager.")
else:
print("You are a child.")

2. Complete Example
Here’s a complete example that combines if, elif, and else statements to
categorize a person's age:
# User input for age
age = int(input("Enter your age: "))

# Conditional statements to determine age category


if age >= 18:
print("You are an adult.")
elif age >= 13:
print("You are a teenager.")
else:
print("You are a child.")
Expected Output
If the user inputs 15, the output will be:
You are a teenager.

Complete example 2
# Function to perform the selected operation
def calculate(num1, num2, operator):
if operator == '+':
return num1 + num2
elif operator == '-':
return num1 - num2
elif operator == '*':
return num1 * num2
elif operator == '/':
if num2 != 0:
return num1 / num2
else:
return "Error! Division by zero."
else:
return "Invalid operator. Please use +, -, *, or /."

# Main program
while True:
try:
# Input numbers
number1 = float(input("Enter the first number: "))
number2 = float(input("Enter the second number: "))

# Input operator
operator = input("Enter an operator (+, -, *, /): ")

13
@edgar cc.

# Calculate and display the result


result = calculate(number1, number2, operator)
print(f"The result is: {result}")

# Ask if the user wants to perform another calculation


another = input("Do you want to perform another calculation? (yes/no): ").low
er()
if another != 'yes':
break
except ValueError:
print("Invalid input. Please enter numeric values.")
Explanation:
1. Function calculate: This function takes two numbers and an operator,
performs the operation, and returns the result.
2. Input Handling:
• It prompts the user for two numbers and an operator.
• It checks for division by zero.
3. Loop: The program continues to prompt the user until they choose not
to perform another calculation.
4. Error Handling: It catches any ValueError that occurs if the user inputs
non-numeric values.
You can run this code in any Python environment to perform basic arithmetic
operations based on user input

3. Comparison Operators
You can use various comparison operators in your conditions:
• == : Equal to
• != : Not equal to
• > : Greater than
• < : Less than
• >= : Greater than or equal to
• <= : Less than or equal to
Example with Comparison Operators
x = 10
y = 20

if x < y:
print("x is less than y")
elif x > y:
print("x is greater than y")
else:
print("x is equal to y")

14
@edgar cc.

Conditional statements are a fundamental aspect of programming that allows


you to control the flow of your code based on different conditions. By
using if, elif, and else, you can create complex decision-making logic in your
Python programs. Understanding how to leverage these statements
effectively is crucial for building responsive and dynamic applications.

Looping Constructs in Python


Looping constructs allow you to execute a block of code repeatedly based
on a condition or over a sequence of items. Python provides two main types
of loops: for loops and while loops. Additionally, control statements
like break and continue can alter the flow of loops.
1. for Loop
The for loop is used to iterate over a sequence (like a list, tuple, string, or a
range of numbers).
Syntax
for variable in sequence:
# Code to execute for each item
Example
# Iterating over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Using range()
You can use the range() function to generate a sequence of numbers.
for i in range(5): # Iterates from 0 to 4
print(i)

2. while Loop
The while loop continues to execute as long as a specified condition is True.
Syntax
while condition:
# Code to execute as long as condition is True
Example
count = 0
while count < 5:
print(count)
count += 1 # Increment the counter

3. break Statement
The break statement is used to exit a loop prematurely, regardless of the
loop's condition.
Example
for i in range(10):

15
@edgar cc.

if i == 5:
break # Exit the loop when i is 5
print(i)
Output
0
1
2
3
4

4. continue Statement
The continue statement skips the current iteration and continues with the next
iteration of the loop.
Example
for i in range(5):
if i == 2:
continue # Skip the iteration when i is 2
print(i)
Output
0
1
3
4

Complete Example
Here's a full example that combines both types of loops along
with break and continue:
# Using a for loop
print("For Loop:")
for i in range(10):
if i % 2 == 0: # Skip even numbers
continue
print(i) # Print odd numbers

# Using a while loop


print("\nWhile Loop:")
count = 0
while count < 10:
if count == 7:
break # Exit the loop when count is 7
print(count)
count += 1
Expected Output

For Loop:
1
3
5
7
9

While Loop:

16
@edgar cc.

0
1
2
3
4
5
6

Loops are essential for executing repetitive tasks in Python. The for loop is
great for iterating over sequences, while the while loop is useful when you
need to repeat actions until a condition changes. Control statements
like break and continue give you additional flexibility in managing loop
execution, allowing for more complex logic in your programs. Understanding
how to use these constructs effectively will enhance your programming
capabilities in Python.

17
@edgar cc.

TOPIC 4: DATA STRUCTURES IN PYTHON


Python offers several built-in data structures that enable you to store and
manipulate data efficiently. This guide will cover four essential data
structures: lists, tuples, dictionaries, and sets.
1. Lists
A list in Python is a built-in data structure that allows you to store an ordered
collection of items. Lists are mutable, meaning that their contents can be
changed after the list has been created. They can hold a mix of data types,
including integers, floats, strings, and even other lists.
Key Features of Lists:
1. Ordered: The items in a list maintain the order in which they were
added, and you can access them using their index (starting from 0).
2. Mutable: You can modify a list by adding, removing, or changing
items.
3. Dynamic Size: Lists can grow and shrink as needed, allowing for
flexible data management.
4. Heterogeneous: Lists can contain elements of different data types,
including other lists.
Syntax for Creating a List
You can create a list using square brackets []:
my_list = [1, 2, 3, "apple", 4.5, True]
Common List Operations
• Accessing Elements:

first_item = my_list[0] # Access the first element


• Adding Elements:
my_list.append("banana") # Add an item to the end of the list
• Removing Elements:
my_list.remove(2) # Remove the first occurrence of the value 2
• Slicing:
sub_list = my_list[1:4] # Get a sublist from index 1 to 3
Example
# Create a list
fruits = ["apple", "banana", "cherry"]

# Access an element
print(fruits[1]) # Output: banana

# Add an element
fruits.append("orange")

18
@edgar cc.

# Remove an element
fruits.remove("apple")

# Print the modified list


print(fruits) # Output: ['banana', 'cherry', 'orange']
In summary, lists are a versatile and commonly used data structure in
Python, ideal for storing collections of items that may need to be modified
over time.

List Comprehensions
List comprehensions provide a concise way to create lists. The syntax
is [expression for item in iterable].
Example
squares = [x**2 for x in range(10)] # Creates a list of squares from 0 to 9
print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

2. Tuples
List Comprehensions in Python
List comprehensions are a concise way to create lists in Python. They allow
you to generate lists by applying an expression to each item in an iterable
(like a list, tuple, or string) and can include an optional condition to filter the
items.
Key Features of List Comprehensions:
1. Concise Syntax: List comprehensions provide a more readable and
compact way to create lists compared to traditional methods (like using
loops).
2. Expression Evaluation: You can apply an expression to each element
in the iterable, transforming the data as needed.
3. Optional Condition: You can include a conditional statement to filter
items, allowing you to include only those that meet certain criteria.
Syntax
The basic syntax for a list comprehension is:
[expression for item in iterable if condition]
•expression: The value to include in the list (can be a transformation
of item).
• item: The variable representing each element in the iterable.
• iterable: The collection you are iterating over (like a list or range).
• condition (optional): A filter that determines whether to include the item
in the new list.
Example

19
@edgar cc.

1. Creating a List of Squares:


squares = [x**2 for x in range(10)]
print(squares) # Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
2. Filtering with a Condition:
even_squares = [x**2 for x in range(10) if x % 2 == 0]
print(even_squares) # Output: [0, 4, 16, 36, 64]
3. Transforming Strings:
fruits = ["apple", "banana", "cherry"]
upper_fruits = [fruit.upper() for fruit in fruits]
print(upper_fruits) # Output: ['APPLE', 'BANANA', 'CHERRY']
Conclusion
List comprehensions are a powerful feature in Python that enhance code
readability and efficiency. They are especially useful for creating new lists by
transforming or filtering existing iterables in a single, concise statement.
Understanding how to use list comprehensions effectively can greatly
improve your coding practices in Python.

3. Dictionaries
Dictionaries in Python
A dictionary in Python is a built-in data structure that stores data in key-
value pairs. It is unordered, mutable, and does not allow duplicate keys.
Dictionaries are defined using curly braces {} or the dict() constructor.
Key Features of Dictionaries:
1. Key-Value Pairs: Each item in a dictionary is stored as a pair
consisting of a key and its corresponding value. The key is a unique
identifier for the value.
2. Unordered: The items in a dictionary do not have a specific order.
When you iterate over a dictionary, the order of items may not be the
same as the order in which they were added.
3. Mutable: You can change, add, or remove items from a dictionary after
it has been created.
4. No Duplicate Keys: Each key in a dictionary must be unique. If a key is
repeated, the last assignment will overwrite the previous value.
Syntax
You can create a dictionary using curly braces or the dict() function:
# Using curly braces
my_dict = {
"name": "Alice",
"age": 30,

20
@edgar cc.

"city": "New York"


}

# Using the dict() constructor


my_dict = dict(name="Alice", age=30, city="New York")
Accessing Values
You can access values in a dictionary using their keys:
print(my_dict["name"]) # Output: Alice
Modifying Dictionaries
You can add, update, or remove key-value pairs:
# Adding a new key-value pair
my_dict["email"] = "[email protected]"

# Updating an existing key


my_dict["age"] = 31

# Removing a key-value pair


del my_dict["city"]
Example
Here's a complete example demonstrating the use of dictionaries:
# Create a dictionary
person = {
"name": "Alice",
"age": 30,
"city": "New York"
}

# Access a value
print(person["name"]) # Output: Alice

# Update a value
person["age"] = 31

# Add a new key-value pair


person["email"] = "[email protected]"

# Remove a key-value pair


del person["city"]

# Print the modified dictionary


print(person) # Output: {'name': 'Alice', 'age': 31, 'email': '[email protected]'}

Dictionaries are a versatile and powerful data structure in Python, ideal for
storing related data as key-value pairs. Their ability to store and retrieve data
efficiently makes them essential for many programming tasks, particularly
when you need to associate unique keys with specific values. Understanding
how to work with dictionaries will enhance your ability to manage and
manipulate data in Python.

21
@edgar cc.

4. Sets
Sets in Python
A set in Python is a built-in data structure that represents an unordered
collection of unique elements. Sets are mutable, meaning you can add or
remove items from them, but they do not allow duplicate values. Sets are
defined using curly braces {} or the set() function.
Key Features of Sets:
1. Unordered: The elements in a set do not have a defined order. This
means that the items cannot be accessed by an index, and the order
may change when items are added or removed.
2. Unique Elements: Sets automatically eliminate duplicate entries. If you
try to add an item that already exists in the set, it will not be added
again.
3. Mutable: You can modify a set by adding or removing elements after it
has been created.
4. No Indexing: Since sets are unordered, you cannot access elements
using an index. However, you can check for membership using
the in keyword.
Syntax
You can create a set using curly braces or the set() function:
python
Copy
# Using curly braces
my_set = {1, 2, 3, 4, 5}

# Using the set() function


my_set = set([1, 2, 3, 4, 5])
Basic Operations
Adding Elements
You can add elements to a set using the add() method:
python
Copy
my_set.add(6) # Adds 6 to the set
Removing Elements
You can remove elements using the remove() or discard() methods:
python
Copy
my_set.remove(3) # Removes 3 from the set; raises an error if not found
my_set.discard(4) # Removes 4 from the set; does not raise an error if not found
Set Operations
Sets support various mathematical operations:

22
@edgar cc.

• Union: Combines elements from both sets.

set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1 | set2 # {1, 2, 3, 4, 5}
• Intersection: Returns elements common to both sets.

intersection_set = set1 & set2 # {3}


• Difference: Returns elements in one set but not in the other.

difference_set = set1 - set2 # {1, 2}


Example
Here's a complete example demonstrating the use of sets:
# Create a set
my_set = {1, 2, 3, 4, 5}

# Add an element
my_set.add(6)

# Remove an element
my_set.remove(3)

# Check membership
print(2 in my_set) # Output: True

# Perform set operations


set_a = {1, 2, 3}
set_b = {3, 4, 5}

# Union
union_set = set_a | set_b # {1, 2, 3, 4, 5}
print("Union:", union_set)

# Intersection
intersection_set = set_a & set_b # {3}
print("Intersection:", intersection_set)

# Difference
difference_set = set_a - set_b # {1, 2}

Sets are a powerful and flexible data structure in Python, ideal for storing
unique elements and performing mathematical set operations. Their
properties make them particularly useful for tasks that require membership
testing, eliminating duplicates, or performing operations that involve multiple
collections of data. Understanding how to work with sets will enhance your
ability to manage and manipulate data effectively in Python.

23
@edgar cc.

Complete Example
Here’s a complete example that demonstrates the use of lists, tuples,
dictionaries, and sets:
# Working with Lists
fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
print("Fruits:", fruits)

# Using List Comprehensions


squares = [x**2 for x in range(5)]
print("Squares:", squares)

# Working with Tuples


coordinates = (10, 20)
print("Coordinates:", coordinates)

# Working with Dictionaries


person = {"name": "Alice", "age": 30}
person["city"] = "New York"
print("Person:", person)

# Working with Sets


colors = {"red", "green", "blue"}
colors.add("yellow")
print("Colors:", colors)
Expected Output
Fruits: ['apple', 'banana', 'cherry', 'orange']
Squares: [0, 1, 4, 9, 16]
Coordinates: (10, 20)
Person: {'name': 'Alice', 'age': 30, 'city': 'New York'}
Colors: {'yellow', 'red', 'green', 'blue'} # Order may vary

Understanding these four core data structures—lists, tuples, dictionaries, and


sets—is crucial for effective programming in Python. Each data structure has
its own characteristics and use cases, allowing you to choose the most
appropriate one based on your needs. Mastering these data structures will
help you organize and manipulate data efficiently in your Python applications.

24
@edgar cc.

TOPIC 5: FUNCTIONS IN PYTHON


Functions are a fundamental building block in Python that allow you to
encapsulate code into reusable blocks. They help to organize your code,
improve readability, and enable modular programming.
1. Defining Functions
You can define a function using the def keyword, followed by the function
name and parentheses. Any parameters the function should accept are listed
within the parentheses.
Syntax
def function_name(parameters):
"""Optional docstring describing the function."""
# Code block
return value # Optional
Example
def greet(name):
"""Function to greet a person by name."""
return f"Hello, {name}!"

# Calling the function


message = greet("Alice")
print(message) # Output: Hello, Alice!
Parameters and Arguments
• Parameters are variables listed in the function definition.
• Arguments are the values you pass to the function when you call it.
You can define functions with:
• No parameters:

def say_hello():
print("Hello!")
• Multiple parameters:
def add(x, y):
return x + y

2. Return Statement
The return statement is used to exit a function and optionally pass a value
back to the caller.
Example
def square(number):
return number ** 2

result = square(5)
print(result) # Output: 25

3. Function Scope

25
@edgar cc.

Scope refers to the visibility or accessibility of variables within different parts


of your code. In Python, there are primarily two types of scope related to
functions:
3.1 Local Scope
Variables defined inside a function are local to that function and cannot be
accessed from outside.
def my_function():
local_var = "I am local!"
print(local_var)

my_function() # Output: I am local!


# print(local_var) # This will raise an error
3.2 Global Scope
Variables defined outside of all functions have a global scope and can be
accessed from anywhere in the code, including inside functions.
global_var = "I am global!"

def access_global():
print(global_var)

access_global() # Output: I am global!


Modifying Global Variables
If you need to modify a global variable inside a function, you must declare it
as global:
count = 0

def increment():
global count
count += 1

increment()
print(count) # Output: 1

Complete Example
Here’s a complete example that demonstrates defining functions, using
parameters, return values, and variable scope:
# Global variable
factor = 2

def multiply(number):
"""Multiplies the input number by a global factor."""
return number * factor

def main():
local_number = 5
result = multiply(local_number)
print(f"The result of multiplying {local_number} by {factor} is {result}.")

# Call the main function


main() # Output: The result of multiplying 5 by 2 is 10.

26
@edgar cc.

Functions are essential for organizing and reusing code in Python. They allow
for modular design, making your programs easier to read and maintain.
Understanding function scope is crucial for managing variable visibility and
ensuring that your code behaves as expected. With practice, you'll become
proficient in defining and using functions effectively in your Python programs.

Function Arguments and Return Values in Python


Functions in Python can accept various types of arguments and can return
values. Understanding how to work with function arguments and return
values is essential for effective programming.
1. Function Arguments
1.1 Positional Arguments
Positional arguments are the most common type of arguments. They are
passed to the function in the order in which they are defined.
Example
def add(a, b):
return a + b

result = add(5, 3) # 5 is assigned to a and 3 to b


print(result) # Output: 8
1.2 Keyword Arguments
Keyword arguments allow you to specify the parameter names when calling
the function. This makes the function call clearer and allows for flexibility in
the order of arguments.
Example
def greet(name, age):
return f"Hello, {name}! You are {age} years old."

message = greet(age=30, name="Alice") # Order doesn't matter


print(message) # Output: Hello, Alice! You are 30 years old.
1.3 Default Arguments
You can provide default values for parameters. If the caller does not provide
a value for those parameters, the default value is used.
Example
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"

print(greet("Alice")) # Output: Hello, Alice!


print(greet("Bob", "Hi")) # Output: Hi, Bob!
1.4 Variable-Length Arguments

27
@edgar cc.

You can define functions that accept a variable number of arguments


using *args for positional arguments and **kwargs for keyword arguments.
Using *args
def add_numbers(*args):
return sum(args)

result = add_numbers(1, 2, 3, 4)
print(result) # Output: 10
Using **kwargs
def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")

print_info(name="Alice", age=30, city="New York")

2. Return Values
Functions can return values using the return statement. If no return statement
is specified, the function will return None by default.
Example of Returning a Value
def square(number):
return number ** 2

result = square(4)
print(result) # Output: 16
Returning Multiple Values
You can return multiple values from a function as a tuple:
def get_coordinates():
return (10, 20)

x, y = get_coordinates()
print(f"x: {x}, y: {y}") # Output: x: 10, y: 20
Example: Combining Arguments and Return Values
Here’s a complete example that combines different types of arguments and
return values:
def calculate_area(length, width=1):
"""Calculate the area of a rectangle or a square."""
return length * width

area_square = calculate_area(5) # Using default width


area_rectangle = calculate_area(5, 3) # Specifying both length and width

print(f"Area of square: {area_square}") # Output: Area of square: 5


print(f"Area of rectangle: {area_rectangle}") # Output: Area of rectangle: 15

Understanding function arguments and return values is crucial for writing


flexible and reusable code in Python. By utilizing different types of arguments
(positional, keyword, default, and variable-length) and effectively managing
return values, you can create functions that are powerful and easy to use.

28
@edgar cc.

This capability enhances the modularity and readability of your code, making
it easier to maintain and expand.

Lambda Functions and Higher-Order Functions


in Python
In Python, functions are first-class citizens, meaning they can be passed
around and manipulated just like other objects. This section covers lambda
functions and higher-order functions, which are important concepts in
functional programming.
1. Lambda Functions
Lambda functions are small, anonymous functions defined using
the lambda keyword. They can take any number of arguments but can only
have one expression. Lambda functions are often used for short, throwaway
functions that are not needed elsewhere.
Syntax
lambda arguments: expression
Example
Here’s a simple example of a lambda function that adds two numbers:
add = lambda x, y: x + y
result = add(5, 3)
print(result) # Output: 8
Using Lambda Functions with map()
Lambda functions are commonly used with functions like map(), filter(),
and reduce().
Example with map()
numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x ** 2, numbers))
print(squared) # Output: [1, 4, 9, 16]
Using Lambda Functions with filter()
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # Output: [2, 4, 6]

2. Higher-Order Functions
Higher-order functions are functions that can take other functions as
arguments or return them as results. This allows for more abstract and
flexible programming paradigms.
Example of a Higher-Order Function
Here’s an example of a higher-order function that takes a function as an
argument:
def apply_function(func, value):

29
@edgar cc.

return func(value)

result = apply_function(lambda x: x ** 2, 5)
print(result) # Output: 25
Returning Functions
Higher-order functions can also return other functions:
def make_multiplier(factor):
return lambda x: x * factor

double = make_multiplier(2)
triple = make_multiplier(3)

print(double(5)) # Output: 10
print(triple(5)) # Output: 15

3. Complete Example
Here’s a complete example that combines lambda functions and higher-
order functions:
# Higher-order function that applies a function to each element in a list
def apply_to_each(func, items):
return [func(item) for item in items]

# Using lambda to double each number


numbers = [1, 2, 3, 4, 5]
doubled_numbers = apply_to_each(lambda x: x * 2, numbers)

print(doubled_numbers) # Output: [2, 4, 6, 8, 10]

Lambda functions provide a concise way to create simple functions in


Python, while higher-order functions allow for more abstract and flexible
function manipulation. Understanding these concepts enhances your ability
to write functional-style code, making your programs more concise and
expressive. By leveraging lambda functions and higher-order functions, you
can create powerful and reusable components in your Python applications.

30
@edgar cc.

TOPIC 6: MODULES AND PACKAGES IN PYTHON


In Python, modules and packages are essential for organizing and structuring
code. They allow you to encapsulate functionality into separate files and
directories, making it easier to manage and reuse code across different
projects.
1. Modules
A module is a single file (with a .py extension) that contains Python code,
including functions, classes, and variables. You can create your own modules
or use built-in modules provided by Python.
Creating a Module
To create a module, simply write your code in a .py file. For example, create a
file named mymodule.py:
# mymodule.py

def greet(name):
return f"Hello, {name}!"

def add(a, b):


return a + b
Importing Modules
You can import a module using the import statement. There are several ways
to import modules:
1.1 Importing the Entire Module
import mymodule

print(mymodule.greet("Alice")) # Output: Hello, Alice!


print(mymodule.add(5, 3)) # Output: 8
1.2 Importing Specific Functions
You can import specific functions from a module using the from keyword:
from mymodule import greet

print(greet("Bob")) # Output: Hello, Bob!


1.3 Importing All Functions
You can import all functions from a module using the asterisk (*), but this is
generally discouraged as it can lead to namespace conflicts:
from mymodule import *

print(add(2, 3)) # Output: 5


1.4 Aliasing a Module
You can give a module a different name using the as keyword, which can
make your code cleaner:
import mymodule as mm

print(mm.greet("Charlie")) # Output: Hello, Charlie!

31
@edgar cc.

2. Packages
A package is a way of organizing related modules into a directory hierarchy. A
package is a directory that contains a special __init__.py file (which can be
empty), indicating that the directory should be treated as a package.
Creating a Package
1. Create a directory for your package, e.g., mypackage/.
2. Inside this directory, add your modules and an __init__.py file.
Directory structure:
mypackage/
__init__.py
module1.py
module2.py
Importing from a Package
You can import modules from a package using the dot (.) notation:
# Assuming mypackage/module1.py contains a function `foo`

from mypackage.module1 import foo

foo()
Example Package Structure
Let's assume module1.py contains:
# mypackage/module1.py

def foo():
return "Function from module1"
And you want to use this function in another script:
from mypackage.module1 import foo

print(foo()) # Output: Function from module1

Modules and packages are powerful tools in Python that help you organize
and manage your code effectively. By breaking your code into modules and
grouping related modules into packages, you can enhance the readability,
maintainability, and reusability of your code. Understanding how to import
and utilize modules and packages is essential for developing robust Python
applications.

32
@edgar cc.

Creating Your Own Modules in Python


Creating your own modules in Python allows you to organize your code into
reusable components. This helps improve code readability and
maintainability. Here’s a step-by-step guide on how to create and use your
own modules.
Step 1: Create a Module
A module is simply a Python file with a .py extension. You can define
functions, classes, and variables in this file.
Example: Creating a Module
1. Create a new file named mymodule.py:
# mymodule.py

def greet(name):
"""Function to greet a person by name."""
return f"Hello, {name}!"

def add(a, b):


"""Function to add two numbers."""
return a + b

def square(number):
"""Function to return the square of a number."""
return number ** 2

Step 2: Use the Module in Another Script


To use the functions defined in your module, you need to import the module
into another Python script.
Example: Using the Module
1. Create a new file named main.py:
# main.py

# Import the entire module


import mymodule

# Use functions from the module


print(mymodule.greet("Alice")) # Output: Hello, Alice!
print(mymodule.add(5, 3)) # Output: 8
print(mymodule.square(4)) # Output: 16
Alternative Import Methods
1. Import Specific Functions
You can also import specific functions from the module:
# main.py

from mymodule import greet, add

print(greet("Bob")) # Output: Hello, Bob!


print(add(10, 5)) # Output: 15

33
@edgar cc.

2. Import with an Alias


Using an alias can make your code cleaner:
# main.py

import mymodule as mm

print(mm.greet("Charlie")) # Output: Hello, Charlie!

Step 3: Directory Structure (Optional)


If you want to organize multiple modules or create a package, you can create
a directory structure.
Example Directory Structure
myproject/
mymodule.py
main.py
Using the Module in a Package
If you have a directory structure that represents a package, you would create
an __init__.py file in the directory:
myproject/
mypackage/
__init__.py
mymodule.py
main.py
You can then import from the package like this:
# main.py

from mypackage.mymodule import greet

print(greet("David")) # Output: Hello, David!

Creating your own modules in Python is a straightforward process that


enhances code organization and reusability. By defining functions, classes,
and variables in separate files, you can keep your code modular and
maintainable. Whether you create simple modules or more complex
packages, understanding how to structure and use them effectively is
essential for developing robust Python applications.

Using Standard Libraries in Python


Python comes with a rich set of standard libraries that provide modules and
functions for various tasks, allowing you to avoid reinventing the wheel.
These libraries cover a wide range of functionalities, from file I/O and system
operations to data manipulation and web services.

34
@edgar cc.

1. Importing Standard Libraries


You can import standard libraries using the import statement. Here are some
commonly used standard libraries:
Example: Importing Libraries
import math
import datetime
import os
import random

2. Common Standard Libraries


2.1 math
The math module provides mathematical functions, constants, and operations.
Example
import math

# Calculate square root


sqrt_value = math.sqrt(16)
print(sqrt_value) # Output: 4.0

# Calculate the value of pi


print(math.pi) # Output: 3.141592653589793

# Calculate sine of an angle (in radians)


angle = math.radians(30) # Convert degrees to radians
print(math.sin(angle)) # Output: 0.49999999999999994
2.2 datetime
The datetime module supplies classes for manipulating dates and times.
Example
import datetime

# Get the current date and time


now = datetime.datetime.now()
print(now) # Output: Current date and time

# Create a specific date


specific_date = datetime.datetime(2023, 10, 2)
print(specific_date) # Output: 2023-10-02 00:00:00

# Format a date
formatted_date = now.strftime("%Y-%m-%d %H:%M:%S")
print(formatted_date) # Output: Current date and time in specified format
2.3 os
The os module provides a way to interact with the operating system, allowing
you to work with files and directories.
Example
import os

# Get the current working directory


current_directory = os.getcwd()

35
@edgar cc.

print(current_directory) # Output: Current working directory

# List files in the current directory


files = os.listdir(current_directory)
print(files) # Output: List of files and directories

# Create a new directory


os.mkdir("new_directory")
2.4 random
The random module implements pseudo-random number generators for
various distributions.
Example
import random

# Generate a random integer between 1 and 10


random_integer = random.randint(1, 10)
print(random_integer)

# Choose a random item from a list


items = ['apple', 'banana', 'cherry']
random_item = random.choice(items)
print(random_item) # Output: Randomly selected item
2.5 json
The json module provides methods for working with JSON data, allowing you
to convert between JSON and Python objects.
Example
import json

# Convert Python object to JSON string


data = {'name': 'Alice', 'age': 30}
json_string = json.dumps(data)
print(json_string) # Output: {"name": "Alice", "age": 30}

# Convert JSON string back to Python object


data_loaded = json.loads(json_string)
print(data_loaded) # Output: {'name': 'Alice', 'age': 30}

Python's standard libraries are a powerful resource that can greatly enhance
your programming productivity. By utilizing these libraries, you can perform a
wide range of tasks without needing to write code from scratch. Familiarizing
yourself with the most commonly used standard libraries will help you
become a more efficient and effective Python programmer.

36
@edgar cc.

TOPIC 7: FILE HANDLING IN PYTHON


File handling in Python allows you to create, read, write, and manipulate files
on your system. This is essential for tasks such as data storage, logging, and
configuration management. Python provides built-in functions and methods
to handle files easily.
1. Opening a File
Before you can read from or write to a file, you need to open it using
the open() function. The basic syntax is:
file_object = open('filename', 'mode')
File Modes
• 'r': Read (default mode). Opens the file for reading.
• 'w': Write. Opens the file for writing (overwrites if the file exists).
• 'a': Append. Opens the file for appending (creates a new file if it
doesn't exist).
• 'b': Binary mode (used with other modes for binary files).
• 't': Text mode (default).

2. Reading from Files


2.1 Reading Entire File
You can read the entire content of a file using the read() method.
with open('example.txt', 'r') as file:
content = file.read()
print(content)
2.2 Reading Line by Line
You can read a file line by line using the readline() method or the for loop.
Using readline()
with open('example.txt', 'r') as file:
line = file.readline() # Reads the first line
while line:
print(line.strip()) # Print line without extra newline
line = file.readline()
Using a for Loop
with open('example.txt', 'r') as file:
for line in file:
print(line.strip())
2.3 Reading All Lines into a List
You can read all lines of a file into a list using the readlines() method.
with open('example.txt', 'r') as file:
lines = file.readlines()
for line in lines:
print(line.strip())

3. Writing to Files
3.1 Writing Text to a File

37
@edgar cc.

You can write to a file using the write() method. If the file exists, it will be
overwritten unless you open it in append mode.
with open('output.txt', 'w') as file:
file.write("Hello, World!\n")
file.write("This is a new line.")
3.2 Appending Text to a File
To append text to an existing file, use the 'a' mode.
with open('output.txt', 'a') as file:
file.write("\nThis line will be appended.")
3.3 Writing Multiple Lines
You can write multiple lines at once using the writelines() method.
lines = ["First line\n", "Second line\n", "Third line\n"]

with open('output.txt', 'w') as file:


file.writelines(lines)

4. Closing a File
It’s important to close a file after you’re done with it to free up system
resources. However, when using the with statement, the file is automatically
closed when the block is exited.
Example of Manual Closing
file = open('example.txt', 'r')
content = file.read()
print(content)
file.close() # Manually closing the file

5. Handling Exceptions
When working with files, it’s a good practice to handle exceptions, especially
for operations like opening files.
try:
with open('non_existent_file.txt', 'r') as file:
content = file.read()
except FileNotFoundError:
print("The file does not exist.")

File handling in Python is straightforward and powerful, enabling you to read


from and write to files easily. By mastering file operations, you can manage
data storage and retrieval effectively in your applications. Using
the with statement ensures that files are properly managed and closed,
reducing the risk of resource leaks.

38
@edgar cc.

Working with CSV and JSON Data in Python


Python provides built-in libraries for handling CSV (Comma-Separated
Values) and JSON (JavaScript Object Notation) data formats. These formats
are widely used for data storage and exchange. Here’s how to work with
them using Python.
1. Working with CSV Data
1.1 Reading CSV Files
Python’s built-in csv module makes it easy to read and write CSV files.
Example: Reading a CSV File
import csv

with open('data.csv', mode='r') as file:


csv_reader = csv.reader(file)
# Skip the header row if necessary
next(csv_reader)

for row in csv_reader:


print(row) # Each row is a list
1.2 Writing to CSV Files
You can also write data to a CSV file using the csv.writer class.
Example: Writing to a CSV File
import csv

data = [
['Name', 'Age', 'City'],
['Alice', 30, 'New York'],
['Bob', 25, 'Los Angeles'],
['Charlie', 35, 'Chicago']
]

with open('output.csv', mode='w', newline='') as file:


csv_writer = csv.writer(file)
csv_writer.writerows(data) # Write multiple rows at once
1.3 Using DictReader and DictWriter
If you prefer working with dictionaries instead of lists, you can
use csv.DictReader and csv.DictWriter.
Example: Reading CSV as Dictionaries
import csv

with open('data.csv', mode='r') as file:


csv_reader = csv.DictReader(file)

for row in csv_reader:


print(row['Name'], row['Age'], row['City']) # Access by column names
Example: Writing Dictionaries to CSV
import csv

39
@edgar cc.

data = [
{'Name': 'Alice', 'Age': 30, 'City': 'New York'},
{'Name': 'Bob', 'Age': 25, 'City': 'Los Angeles'},
{'Name': 'Charlie', 'Age': 35, 'City': 'Chicago'}
]

with open('output.csv', mode='w', newline='') as file:


fieldnames = ['Name', 'Age', 'City']
csv_writer = csv.DictWriter(file, fieldnames=fieldnames)

csv_writer.writeheader() # Write the header


csv_writer.writerows(data) # Write the data

2. Working with JSON Data


Python’s built-in json module allows you to work with JSON data easily.
2.1 Reading JSON Files
You can read JSON data from a file using json.load().
Example: Reading a JSON File
import json

with open('data.json', 'r') as file:


data = json.load(file)
print(data) # Data is now a Python dictionary
2.2 Writing JSON Files
To write JSON data to a file, use json.dump().
Example: Writing to a JSON File
import json

data = {
'employees': [
{'name': 'Alice', 'age': 30, 'city': 'New York'},
{'name': 'Bob', 'age': 25, 'city': 'Los Angeles'},
{'name': 'Charlie', 'age': 35, 'city': 'Chicago'}
]
}

with open('output.json', 'w') as file:


json.dump(data, file, indent=4) # Pretty-print with indentation
2.3 Converting Between JSON and Python Objects
You can easily convert Python objects to JSON strings using json.dumps() and
parse JSON strings back to Python objects using json.loads().
Example: Converting JSON String to Python Object
json_string = '{"name": "Alice", "age": 30, "city": "New York"}'
data = json.loads(json_string)
print(data['name']) # Output: Alice
Example: Converting Python Object to JSON String
data = {'name': 'Bob', 'age': 25, 'city': 'Los Angeles'}
json_string = json.dumps(data)
print(json_string) # Output: {"name": "Bob", "age": 25, "city": "Los Angeles"}

40
@edgar cc.

Working with CSV and JSON data in Python is straightforward thanks to the
built-in csv and json modules. These libraries enable you to easily read from
and write to these common data formats, making it simple to handle data
storage and exchange in your applications. By mastering these techniques,
you can effectively manage data in various programming scenarios.

Exception Handling in File Operations in Python


When working with file operations in Python, it's essential to handle
exceptions to prevent your program from crashing due to unforeseen errors,
such as file not found, permission denied, or other I/O issues. Python
provides a robust mechanism for handling exceptions using
the try, except, else, and finally blocks.
1. Basic Exception Handling
The basic structure of exception handling involves wrapping the file
operations in a try block and catching exceptions with an except block.
Example: Handling File Not Found Exception
try:
with open('non_existent_file.txt', 'r') as file:
content = file.read()
except FileNotFoundError:
print("Error: The file does not exist.")
Example: Handling Multiple Exceptions
You can handle multiple exceptions by specifying them in
separate except blocks or combining them in a tuple.
try:
with open('data.txt', 'r') as file:
content = file.read()
except FileNotFoundError:
print("Error: The file does not exist.")
except PermissionError:
print("Error: You do not have permission to read this file.")
Example: Using a Tuple to Handle Multiple Exceptions
try:
with open('data.txt', 'r') as file:
content = file.read()
except (FileNotFoundError, PermissionError) as e:
print(f"Error: {e}")

2. Using else and finally


2.1 The else Block
The else block can be used to define code that should execute if no
exceptions are raised in the try block.
try:

41
@edgar cc.

with open('data.txt', 'r') as file:


content = file.read()
except FileNotFoundError:
print("Error: The file does not exist.")
else:
print("File read successfully:")
print(content)
2.2 The finally Block
The finally block is used to define code that should run regardless of whether
an exception was raised or not. This is useful for cleanup actions, such as
closing files or releasing resources.
try:
file = open('data.txt', 'r')
content = file.read()
except FileNotFoundError:
print("Error: The file does not exist.")
else:
print("File read successfully:")
print(content)
finally:
if 'file' in locals():
file.close() # Ensure the file is closed if it was opened
print("File closed.")

3. Complete Example
Here’s a complete example of file operations with exception handling:
def read_file(filename):
try:
with open(filename, 'r') as file:
content = file.read()
except FileNotFoundError:
print("Error: The file does not exist.")
except PermissionError:
print("Error: You do not have permission to read this file.")
else:
print("File read successfully:")
print(content)
finally:
print("Execution completed.")

# Example usage
read_file('data.txt')

Exception handling is a crucial aspect of file operations in Python, allowing


you to manage errors gracefully and maintain the stability of your
applications. By using try, except, else, and finally blocks, you can handle
various exceptions that may occur during file operations and ensure that
resources are properly managed. This practice leads to more robust and
user-friendly programs.

42
@edgar cc.

TOPIC 8: OBJECT-ORIENTED PROGRAMMING (OOP)


IN PYTHON
Object-Oriented Programming (OOP) is a programming paradigm that
organizes software design around data, or objects, rather than functions and
logic. Python supports OOP, allowing you to model real-world entities using
classes and objects. Here’s a detailed look at classes and objects in Python.
1. Classes
A class is a blueprint for creating objects. It defines a set of attributes (data)
and methods (functions) that the objects created from the class can use.
1.1 Defining a Class
To define a class, use the class keyword followed by the class name
(conventionally in CamelCase).
Example: Defining a Class
class Dog:
"""A simple class representing a dog."""

def __init__(self, name, age):


"""Initialize the dog's attributes."""
self.name = name # Instance variable for dog's name
self.age = age # Instance variable for dog's age

def bark(self):
"""Make the dog bark."""
return f"{self.name} says woof!"
1.2 The __init__ Method
The __init__ method is a special method called a constructor, which initializes
the object's attributes when an object is created.
2. Objects
An object is an instance of a class. When you create an object, you are
creating a concrete implementation of the class.
2.1 Creating Objects
To create an object, call the class as if it were a function, passing the
required arguments to the __init__ method.
Example: Creating Objects
# Creating instances of the Dog class
dog1 = Dog("Buddy", 3)
dog2 = Dog("Max", 5)

# Accessing attributes and methods


print(dog1.bark()) # Output: Buddy says woof!
print(dog2.age) # Output: 5

43
@edgar cc.

2.2 Accessing Attributes and Methods


You can access an object's attributes using dot notation (object.attribute) and
call its methods similarly (object.method()).
3. Instance Variables and Class Variables
3.1 Instance Variables
Instance variables are variables that are unique to each instance of a class.
Example of Instance Variables
print(dog1.name) # Output: Buddy
print(dog2.name) # Output: Max
3.2 Class Variables
Class variables are shared across all instances of a class. They are defined
within the class but outside any instance methods.
Example: Class Variables
class Dog:
species = "Canine" # Class variable

def __init__(self, name, age):


self.name = name
self.age = age

# Accessing class variable


print(Dog.species) # Output: Canine

dog1 = Dog("Buddy", 3)
dog2 = Dog("Max", 5)

print(dog1.species) # Output: Canine


print(dog2.species) # Output: Canine

4. Summary
• Class: A blueprint for creating objects (e.g., Dog).
• Object: An instance of a class (e.g., dog1, dog2).
• Instance Variables: Attributes unique to each object (e.g., name, age).
• Class Variables: Attributes shared among all instances (e.g., species).
• Methods: Functions defined in the class that operate on instances
(e.g., bark).

Understanding classes and objects is fundamental to mastering Object-


Oriented Programming in Python. This paradigm helps you model real-world
entities, making your code more organized and easier to maintain. With
classes, you can create reusable code structures, encapsulating data and
behavior that relates to those data structures

44
@edgar cc.

Inheritance and Polymorphism in Python


Inheritance and polymorphism are two key concepts in Object-Oriented
Programming (OOP) that enhance code reusability and flexibility. Let's
explore both concepts in Python.
1. Inheritance
Inheritance allows a class (called a child or derived class) to inherit attributes
and methods from another class (called a parent or base class). This
promotes code reuse and establishes a hierarchical relationship between
classes.
1.1 Basic Inheritance
You can define a child class by specifying the parent class in parentheses.
Example: Basic Inheritance
class Animal:
"""A base class for all animals."""

def __init__(self, name):


self.name = name

def speak(self):
return "Some sound"

class Dog(Animal):
"""A class representing a dog, inheriting from Animal."""

def speak(self):
return f"{self.name} says woof!"

class Cat(Animal):
"""A class representing a cat, inheriting from Animal."""

def speak(self):
return f"{self.name} says meow!"
1.2 Creating Instances of Inherited Classes
You can create instances of the child classes just like you do with parent
classes.
dog = Dog("Buddy")
cat = Cat("Whiskers")

print(dog.speak()) # Output: Buddy says woof!


print(cat.speak()) # Output: Whiskers says meow!
1.3 The super() Function
The super() function allows you to call methods from the parent class in the
child class.
Example: Using super()
class Animal:
def __init__(self, name):

45
@edgar cc.

self.name = name

class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name) # Call the parent class's constructor
self.breed = breed

dog = Dog("Buddy", "Golden Retriever")


print(dog.name) # Output: Buddy
print(dog.breed) # Output: Golden Retriever

2. Polymorphism
Polymorphism allows methods to do different things based on the object
calling them. It enables you to use the same method name across different
classes, and the correct method is called based on the object type.
2.1 Method Overriding
When a child class provides a specific implementation of a method that is
already defined in its parent class, it is called method overriding.
Example: Method Overriding
class Animal:
def speak(self):
return "Some sound"

class Dog(Animal):
def speak(self):
return "Woof!"

class Cat(Animal):
def speak(self):
return "Meow!"

# Using polymorphism
def animal_sound(animal):
print(animal.speak())

dog = Dog()
cat = Cat()

animal_sound(dog) # Output: Woof!


animal_sound(cat) # Output: Meow!
2.2 Using a Common Interface
Polymorphism allows you to treat different objects in a uniform way through a
common interface.
Example: Common Interface
animals = [Dog(), Cat()]

for animal in animals:


print(animal.speak()) # Output: Woof! \n Meow!

46
@edgar cc.

Inheritance and polymorphism are powerful features of Object-Oriented


Programming in Python. Inheritance promotes code reuse and establishes
relationships between classes, while polymorphism allows for flexible method
implementation, enabling you to write more generic and maintainable code.
By leveraging these concepts, you can create more organized, efficient, and
scalable applications.

Encapsulation and Data Hiding in Python


Encapsulation and data hiding are fundamental concepts in Object-Oriented
Programming (OOP) that help manage complexity and protect the integrity of
an object's data. Let's explore these concepts in Python.
1. Encapsulation
Encapsulation refers to the bundling of data (attributes) and methods
(functions) that operate on the data into a single unit, typically a class. It
restricts direct access to some of the object's components, which can
prevent the accidental modification of data.
1.1 Defining a Class with Encapsulation
In Python, encapsulation is achieved through the use of access modifiers.
While Python does not enforce strict access control, it provides conventions
to indicate the intended visibility of class attributes and methods.
Example: Encapsulation with Access Modifiers
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner # Public attribute
self.__balance = balance # Private attribute

def deposit(self, amount):


if amount > 0:
self.__balance += amount
print(f"Deposited: {amount}")
else:
print("Deposit amount must be positive.")

def withdraw(self, amount):


if 0 < amount <= self.__balance:
self.__balance -= amount
print(f"Withdrew: {amount}")

47
@edgar cc.

else:
print("Invalid withdrawal amount.")

def get_balance(self):
return self.__balance # Accessing private attribute through a method

# Example usage
account = BankAccount("Alice", 1000)
account.deposit(500) # Deposited: 500
account.withdraw(200) # Withdrew: 200
print(account.get_balance()) # Output: 1300
1.2 Public and Private Attributes
• Public attributes: Accessible from outside the class (e.g., owner).
• Private attributes: Not directly accessible from outside the class
(e.g., __balance). The double underscore prefix (__) indicates that the
attribute is intended to be private.
2. Data Hiding
Data hiding is a principle that restricts access to certain components of an
object. It is closely related to encapsulation and helps protect an object's
internal state from unintended interference and misuse.
2.1 Accessing Private Attributes
While private attributes cannot be accessed directly from outside the class,
you can use getter and setter methods to interact with them.
Example: Using Getters and Setters
class Person:
def __init__(self, name):
self.__name = name # Private attribute

def get_name(self):
return self.__name # Getter method

def set_name(self, name):


if isinstance(name, str) and name:
self.__name = name # Setter method
else:
print("Invalid name.")

# Example usage
person = Person("Alice")
print(person.get_name()) # Output: Alice

person.set_name("Bob")
print(person.get_name()) # Output: Bob

person.set_name("") # Output: Invalid name.


2.2 Advantages of Data Hiding
• Control: You can control how attributes are accessed and modified.
• Validation: You can enforce rules for setting attribute values.

48
@edgar cc.

• Maintainability: Changes to internal implementation can be made


without affecting external code.

Encapsulation and data hiding are essential concepts in Python's Object-


Oriented Programming paradigm. They allow you to bundle data and
methods together, restrict access to certain attributes, and protect the
integrity of an object's state. By using these principles, you can create robust
and maintainable code, ensuring that the internal workings of your classes
are shielded from unintended interference.

49
@edgar cc.

TOPIC 9: ERROR HANDLING AND DEBUGGING IN PYTHON


Error handling and debugging are crucial for developing robust Python
applications. This section covers understanding exceptions, using try, except,
and finally blocks, as well as debugging techniques and tools.
1. Understanding Exceptions
An exception is an event that occurs during the execution of a program that
disrupts its normal flow. Python provides a way to handle these exceptions
so that the program can continue running or terminate gracefully.
Common Built-in Exceptions
• ValueError: Raised when a function receives an argument of the right
type but inappropriate value.
• TypeError: Raised when an operation or function is applied to an object
of inappropriate type.
• IndexError: Raised when trying to access an index that is out of range.
• KeyError: Raised when trying to access a dictionary with a key that
doesn’t exist.
• FileNotFoundError: Raised when trying to open a file that does not exist.

2. Try, Except, Finally Blocks


2.1 Basic Structure
The try block allows you to test a block of code for errors, while
the except block lets you handle those errors.
Example: Basic Try-Except
try:
number = int(input("Enter a number: "))
result = 10 / number
print(f"Result: {result}")
except ValueError:
print("Error: Invalid input. Please enter a valid number.")
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
2.2 Catching Multiple Exceptions
You can catch multiple exceptions by specifying them in
separate except blocks or combining them in a tuple.
Example: Multiple Exceptions
try:
value = int(input("Enter an integer: "))
print(10 / value)
except (ValueError, ZeroDivisionError) as e:
print(f"Error: {e}")
2.3 The Finally Block

50
@edgar cc.

The finally block is used to execute code that should run regardless of
whether an exception occurred or not. This is useful for cleanup actions,
such as closing files or releasing resources.
Example: Using Finally
try:
file = open('data.txt', 'r')
content = file.read()
except FileNotFoundError:
print("Error: The file does not exist.")
else:
print(content)
finally:
if 'file' in locals():
file.close() # Ensure the file is closed
print("File closed.")

3. Debugging Techniques and Tools


Debugging is the process of finding and resolving bugs or defects in your
code. Here are some techniques and tools that can help.
3.1 Print Statements
Using print() statements is a simple but effective way to trace the flow of
execution and inspect variable values.
def calculate_area(radius):
print(f"Calculating area for radius: {radius}")
return 3.14 * radius ** 2

area = calculate_area(5)
print(f"Area: {area}")
3.2 Using Assertions
Assertions are a debugging aid that tests a condition. If the condition
evaluates to False, an AssertionError is raised.
def divide(a, b):
assert b != 0, "Error: Division by zero is not allowed."
return a / b

print(divide(10, 2))
# print(divide(10, 0)) # This will raise an AssertionError
3.3 Logging
The logging module provides a flexible framework for emitting log messages
from Python programs. It is more powerful than using print statements.
Example: Using Logging
import logging

logging.basicConfig(level=logging.DEBUG)

def divide(a, b):


if b == 0:
logging.error("Division by zero attempted")
return None

51
@edgar cc.

return a / b

result = divide(10, 0)
3.4 Using a Debugger
Python includes a built-in debugger called pdb. It allows you to set
breakpoints, step through code, and inspect variable values.
Example: Using pdb
import pdb

def buggy_function():
a = 5
b = 0
pdb.set_trace() # Set a breakpoint
return a / b

buggy_function()
You can run the script and use commands like n (next), c (continue),
and q (quit) to navigate through the code.

Error handling and debugging are essential skills in Python programming.


Understanding exceptions and effectively using try, except, and finally blocks
can help manage errors gracefully. Additionally, employing debugging
techniques such as print statements, assertions, logging, and using
debuggers can significantly enhance your ability to identify and fix issues in
your code. By mastering these concepts, you can create more robust and
reliable applications.

52
@edgar cc.

TOPIC 10: WORKING WITH LIBRARIES IN PYTHON


Python has a rich ecosystem of libraries that extend its capabilities for
various tasks, from data manipulation to visualization. Here’s an overview of
three popular libraries: NumPy, Pandas, and Matplotlib.
NumPy Library in Python
NumPy (Numerical Python) is a powerful library in Python used for numerical
computations and data manipulation. It provides support for large, multi-
dimensional arrays and matrices, along with a collection of mathematical
functions to operate on these data structures. NumPy is widely used in
scientific computing, data analysis, and machine learning.
Key Features of NumPy
1. N-dimensional Arrays: The core feature of NumPy is the ndarray (N-
dimensional array) object, which allows you to create arrays of any
shape and size.
2. Mathematical Functions: NumPy offers a wide variety of mathematical
functions to perform operations like addition, subtraction,
multiplication, and more on arrays.
3. Broadcasting: This powerful feature allows you to perform arithmetic
operations on arrays of different shapes.
4. Linear Algebra: NumPy provides methods for linear algebra operations,
such as matrix multiplication, eigenvalue decomposition, and more.
5. Random Number Generation: NumPy includes functionalities to generate
random numbers for simulations and probabilistic models.
Installation
If you haven't installed NumPy yet, you can do so using pip:
bash
Copy
pip install numpy

Basic Usage
1. Importing NumPy
To use NumPy, you need to import it. The convention is to import it as np.
import numpy as np
2. Creating Arrays
2.1 Creating a 1D Array
array_1d = np.array([1, 2, 3, 4, 5])
print("1D Array:", array_1d)
2.2 Creating a 2D Array
array_2d = np.array([[1, 2, 3], [4, 5, 6]])
print("2D Array:\n", array_2d)

53
@edgar cc.

2.3 Creating Arrays with Specific Values


• Zeros: Creates an array filled with zeros.
zeros_array = np.zeros((2, 3)) # 2x3 array of zeros
print("Zeros Array:\n", zeros_array)
• Ones: Creates an array filled with ones.
ones_array = np.ones((2, 3)) # 2x3 array of ones
print("Ones Array:\n", ones_array)
• Arange: Generates an array with a range of values.
arange_array = np.arange(0, 10, 2) # Start at 0, stop before 10, step by 2
print("Arange Array:", arange_array)
• Linspace: Generates an array with evenly spaced values between a
start and end value.
linspace_array = np.linspace(0, 1, 5) # 5 values between 0 and 1
print("Linspace Array:", linspace_array)
3. Array Operations
3.1 Basic Arithmetic Operations
NumPy allows element-wise arithmetic operations on arrays.
array_a = np.array([1, 2, 3])
array_b = np.array([4, 5, 6])

# Element-wise addition
sum_array = array_a + array_b
print("Sum:", sum_array)

# Element-wise multiplication
product_array = array_a * array_b
print("Product:", product_array)
3.2 Universal Functions (ufuncs)
NumPy provides universal functions to perform element-wise operations.
array = np.array([1, 4, 9])

# Square root
sqrt_array = np.sqrt(array)
print("Square Root:", sqrt_array)

# Exponential
exp_array = np.exp(array)
print("Exponential:", exp_array)
4. Indexing and Slicing
You can access elements and slices of NumPy arrays similarly to lists.
array = np.array([10, 20, 30, 40, 50])

# Accessing elements
print("First Element:", array[0]) # 10
print("Last Element:", array[-1]) # 50

# Slicing
slice_array = array[1:4] # Elements from index 1 to 3
print("Slice:", slice_array) # Output: [20 30 40]

54
@edgar cc.

5. Reshaping Arrays
You can change the shape of an array without changing its data.
array = np.arange(6) # Creates an array: [0, 1, 2, 3, 4, 5]
reshaped_array = array.reshape((2, 3)) # Reshape to 2 rows and 3 columns
print("Reshaped Array:\n", reshaped_array)
6. Linear Algebra
NumPy also provides functions for linear algebra operations.
# Matrix multiplication
matrix_a = np.array([[1, 2], [3, 4]])
matrix_b = np.array([[5, 6], [7, 8]])
product_matrix = np.dot(matrix_a, matrix_b)
print("Matrix Product:\n", product_matrix)

# Determinant
det = np.linalg.det(matrix_a)
print("Determinant:", det)

NumPy is an essential library for numerical computing in Python. Its powerful


array manipulation capabilities, mathematical functions, and performance
optimizations make it a fundamental tool for data scientists, engineers, and
researchers. By mastering NumPy, you can efficiently handle large datasets
and perform complex numerical computations.

Pandas Library in Python


Pandas is a powerful and widely-used library in Python for data manipulation
and analysis. It provides data structures and functions needed to work with
structured data efficiently, making it a favorite tool among data scientists and
analysts.
Key Features of Pandas
1. DataFrames: The primary data structure that allows you to store and
manipulate tabular data (similar to a spreadsheet or SQL table).
2. Series: A one-dimensional labeled array capable of holding any data
type.
3. Data Cleaning: Functions to handle missing data, duplicates, and data
transformation.
4. Data Manipulation: Powerful methods for filtering, grouping, and
aggregating data.
5. Input/Output: Functions to read from and write to various file formats
(CSV, Excel, SQL, etc.).
Installation
To install Pandas, you can use pip:

55
@edgar cc.

pip install pandas

Basic Usage
1. Importing Pandas
You need to import the library before using it. The convention is to import it
as pd.
import pandas as pd
2. Creating DataFrames
2.1 From a Dictionary
data = {
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [30, 25, 35],
'City': ['New York', 'Los Angeles', 'Chicago']
}

df = pd.DataFrame(data)
print("DataFrame:\n", df)
2.2 From a CSV File
You can easily create a DataFrame from a CSV file using the read_csv function.
# df = pd.read_csv('file.csv') # Uncomment to read from a CSV file
3. Inspecting Data
Pandas provides several methods to quickly inspect your data.
print(df.head()) # Displays the first 5 rows
print(df.tail()) # Displays the last 5 rows
print(df.info()) # Displays a concise summary of the DataFrame
print(df.describe()) # Generates descriptive statistics
4. Accessing Data
You can access data in a DataFrame using column names and row indices.
4.1 Accessing a Column
print(df['Name']) # Access a single column
4.2 Accessing Multiple Columns
print(df[['Name', 'Age']]) # Access multiple columns
4.3 Accessing Rows
You can use iloc for position-based indexing or loc for label-based indexing.
print(df.iloc[0]) # Access the first row
print(df.loc[0]) # Access the row with index 0
5. Data Manipulation
5.1 Filtering Data
You can filter rows based on conditions.
filtered_df = df[df['Age'] > 30]
print("Filtered DataFrame:\n", filtered_df)
5.2 Adding a New Column
df['Salary'] = [70000, 80000, 90000]
print("DataFrame with Salary:\n", df)
5.3 Modifying Values
You can update values based on conditions.

56
@edgar cc.

python
Copy
df.loc[df['Name'] == 'Alice', 'Age'] = 31
print("Updated DataFrame:\n", df)
5.4 Dropping Columns
df = df.drop(columns=['Salary'])
print("DataFrame after dropping Salary:\n", df)
6. Grouping and Aggregating Data
Pandas provides powerful groupby functionality for data aggregation.
grouped = df.groupby('City')['Age'].mean() # Calculate average age by city
print("Average Age by City:\n", grouped)
7. Handling Missing Data
Pandas offers methods to handle missing data, such as fillna() and dropna().
# Fill missing values
df['Age'] = df['Age'].fillna(df['Age'].mean())

# Drop rows with any missing values


df = df.dropna()
8. Input/Output Operations
8.1 Reading from CSV
df = pd.read_csv('data.csv') # Read data from a CSV file
8.2 Writing to CSV
df.to_csv('output.csv', index=False) # Write DataFrame to a CSV file

Pandas is an essential library for data manipulation and analysis in Python. Its
DataFrame and Series data structures, along with powerful functions for
filtering, grouping, and aggregating data, make it a vital tool for anyone
working with data. By mastering Pandas, you can efficiently handle large
datasets and perform complex data analyses with ease.

3.Matplotlib in Python
Matplotlib is a powerful plotting library in Python used for creating static,
animated, and interactive visualizations. It provides a flexible framework for
generating a wide range of plots and charts, making it an essential tool for
data visualization in data science, engineering, and research.
Key Features of Matplotlib
1. Versatile Plotting: Supports various types of plots, including line plots,
scatter plots, bar charts, histograms, and more.
2. Customization: Extensive options for customizing plots, including
colors, labels, legends, and styles.

57
@edgar cc.

3. Integration: Works seamlessly with NumPy and Pandas for visualizing


data stored in arrays and DataFrames.
4. Subplots: Easily create multiple plots in a single figure using subplots.
5. Exporting: Ability to save plots in multiple formats such as PNG, PDF,
SVG, and more.
Installation
If you haven't installed Matplotlib yet, you can do so using pip:
pip install matplotlib

Basic Usage
1. Importing Matplotlib
You typically import the pyplot module from Matplotlib, which provides a
MATLAB-like interface for plotting.
import matplotlib.pyplot as plt
2. Creating a Basic Line Plot
Example: Simple Line Plot
import matplotlib.pyplot as plt

# Sample data
x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]

# Create a line plot


plt.plot(x, y, marker='o', linestyle='-')
plt.title("Simple Line Plot")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.grid()
plt.show()
3. Creating a Scatter Plot
Example: Scatter Plot
# Create a scatter plot
plt.scatter(x, y, color='red')
plt.title("Scatter Plot")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.grid()
plt.show()
4. Creating a Bar Chart
Example: Bar Chart
# Sample data for bar chart
categories = ['A', 'B', 'C']
values = [3, 7, 5]

# Create a bar chart


plt.bar(categories, values, color='blue')
plt.title("Bar Chart")
plt.xlabel("Categories")

58
@edgar cc.

plt.ylabel("Values")
plt.show()
5. Creating a Histogram
Example: Histogram
import numpy as np

# Generating random data


data = np.random.randn(1000)

# Create a histogram
plt.hist(data, bins=30, color='green', alpha=0.7)
plt.title("Histogram")
plt.xlabel("Value")
plt.ylabel("Frequency")
plt.show()
6. Customizing Plots
You can customize your plots with various options.
Example: Customized Plot
plt.plot(x, y, marker='o', linestyle='--', color='purple', markersize=8, linewidth=2)
plt.title("Customized Line Plot", fontsize=14)
plt.xlabel("X-axis", fontsize=12)
plt.ylabel("Y-axis", fontsize=12)
plt.grid(color='grey', linestyle='--', linewidth=0.5)
plt.show()
7. Adding Legends
Legends can be added to differentiate between multiple datasets.
Example: Adding Legends
# Sample data
y2 = [1, 4, 6, 8, 10]

plt.plot(x, y, marker='o', label='Dataset 1')


plt.plot(x, y2, marker='x', label='Dataset 2')
plt.title("Line Plot with Legends")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.legend()
plt.show()
8. Creating Subplots
You can create multiple plots in a single figure using subplots.
Example: Subplots
fig, axs = plt.subplots(2, 2, figsize=(10, 8))

# Top-left plot
axs[0, 0].plot(x, y, marker='o')
axs[0, 0].set_title("Top Left Plot")

# Top-right plot
axs[0, 1].bar(categories, values)
axs[0, 1].set_title("Top Right Plot")

# Bottom-left plot

59
@edgar cc.

axs[1, 0].scatter(x, y, color='red')


axs[1, 0].set_title("Bottom Left Plot")

# Bottom-right plot
axs[1, 1].hist(data, bins=30)
axs[1, 1].set_title("Bottom Right Plot")

plt.tight_layout() # Adjusts subplot parameters


plt.show()
9. Saving Plots
You can save your plots to files in various formats.
Example: Saving a Plot
plt.plot(x, y)
plt.title("Line Plot")
plt.savefig("line_plot.png") # Save as PNG
plt.show()

Matplotlib is a versatile and powerful library for data visualization in Python.


Its ability to create a wide variety of plots and extensive customization
options make it an essential tool for anyone working with data. By mastering
Matplotlib, you can effectively communicate your data insights through visual
representations.

Basic Data Manipulation and Visualization in


Python
Data manipulation and visualization are essential skills in data analysis. This
guide will walk you through the basics of data manipulation using Pandas and
visualization using Matplotlib.
1. Setting Up the Environment
First, ensure you have the necessary libraries installed. You can install them
using pip:
bash
Copy
pip install pandas matplotlib

2. Data Manipulation with Pandas


2.1 Importing Pandas
Start by importing the Pandas library.
import pandas as pd
2.2 Creating a DataFrame
You can create a DataFrame from a dictionary, CSV file, or other data
sources.

60
@edgar cc.

Example: Creating a DataFrame from a Dictionary


data = {
'Name': ['Alice', 'Bob', 'Charlie', 'David'],
'Age': [24, 30, 35, 40],
'City': ['New York', 'Los Angeles', 'Chicago', 'Houston']
}

df = pd.DataFrame(data)
print("DataFrame:\n", df)
2.3 Reading Data from a CSV File
To read data from a CSV file, use the read_csv function.
# df = pd.read_csv('file.csv') # Uncomment to read from a CSV file
2.4 Inspecting Data
You can quickly inspect the data in a DataFrame.
print(df.head()) # Displays the first 5 rows
print(df.info()) # Displays a concise summary of the DataFrame
print(df.describe()) # Generates descriptive statistics
2.5 Accessing Data
You can access specific rows and columns using indexing.
# Access a single column
print(df['Name'])

# Access multiple columns


print(df[['Name', 'Age']])

# Access rows by index


print(df.iloc[0]) # First row
print(df.loc[1]) # Row with index 1
2.6 Filtering Data
You can filter rows based on conditions.
filtered_df = df[df['Age'] > 30]
print("Filtered DataFrame:\n", filtered_df)
2.7 Adding a New Column
You can add a new column to the DataFrame.
df['Salary'] = [70000, 80000, 120000, 90000]
print("DataFrame with Salary:\n", df)
2.8 Grouping and Aggregating Data
You can group data and calculate aggregates.
grouped = df.groupby('City')['Age'].mean() # Calculate average age by city
print("Average Age by City:\n", grouped)

3. Data Visualization with Matplotlib


3.1 Importing Matplotlib
Next, import the Matplotlib library.
import matplotlib.pyplot as plt
3.2 Creating a Simple Line Plot
You can create a basic line plot using data from the DataFrame.
# Sample data for plotting

61
@edgar cc.

x = df['Name']
y = df['Salary']

plt.plot(x, y, marker='o', linestyle='-')


plt.title("Salaries by Name")
plt.xlabel("Name")
plt.ylabel("Salary")
plt.grid()
plt.xticks(rotation=45) # Rotate x-axis labels for better visibility
plt.show()
3.3 Creating a Bar Chart
Bar charts are useful for comparing quantities.
plt.bar(x, y, color='blue')
plt.title("Salaries by Name")
plt.xlabel("Name")
plt.ylabel("Salary")
plt.xticks(rotation=45) # Rotate for better visibility
plt.show()
3.4 Creating a Histogram
Histograms are useful for visualizing the distribution of numerical data.
plt.hist(df['Age'], bins=5, color='green', alpha=0.7)
plt.title("Age Distribution")
plt.xlabel("Age")
plt.ylabel("Frequency")
plt.show()
3.5 Customizing Plots
You can customize your plots with titles, labels, colors, and more.
plt.bar(x, y, color='purple')
plt.title("Salaries by Name", fontsize=14)
plt.xlabel("Name", fontsize=12)
plt.ylabel("Salary", fontsize=12)
plt.xticks(rotation=45)
plt.grid(axis='y', linestyle='--', alpha=0.7)
plt.show()

62
@edgar cc.

TOPIC 11: WEB DEVELOPMENT BASICS IN PYTHON


Web development in Python has gained immense popularity due to its
simplicity and the powerful frameworks available. This guide will introduce
you to web frameworks, focusing on Flask and Django, two of the most
widely used frameworks in Python web development.
1. Introduction to Web Frameworks
A web framework is a software framework designed to aid web application
development. It provides a structured way to build web applications by
offering tools and libraries for common tasks, such as routing, templating,
and database interaction.
Why Use a Web Framework?
• Efficiency: Frameworks provide pre-built components, allowing
developers to focus on building features instead of handling low-level
details.
• Security: Frameworks often come with built-in security features to
protect against common vulnerabilities.
• Community Support: Popular frameworks have large communities,
extensive documentation, and a wealth of third-party libraries.
2. Flask
Flask is a lightweight and flexible web framework for Python. It is often
referred to as a "micro" framework because it provides the essential features
to get started without imposing a specific directory structure or
dependencies.
Key Features of Flask
• Minimalistic: Flask provides the essentials, allowing developers to add
only what they need.
• Extensible: You can easily add extensions for additional functionality
(e.g., authentication, database integration).
• Built-in Development Server: Flask comes with a built-in server for easy
testing and development.
Getting Started with Flask
2.1 Installation
You can install Flask using pip:
pip install Flask
2.2 Creating a Simple Flask Application
Here’s a basic example of a Flask application:
from flask import Flask

app = Flask(__name__)

63
@edgar cc.

@app.route('/')
def home():
return "Hello, Flask!"

if __name__ == '__main__':
app.run(debug=True)
2.3 Running the Application
Save the code to a file named app.py and run it:
python app.py
Open a web browser and navigate to http://127.0.0.1:5000/ to see the output.
3. Django
Django is a high-level web framework that encourages rapid development
and clean, pragmatic design. It follows the "batteries-included" philosophy,
meaning it comes with many built-in features.
Key Features of Django
• Full-Featured: Django provides built-in tools for user authentication,
ORM (Object-Relational Mapping), admin interface, and more.
• Scalable: Designed to handle high-traffic applications.
• Security: Includes protections against common security threats, such
as SQL injection and cross-site scripting (XSS).
Getting Started with Django
3.1 Installation
You can install Django using pip:
pip install Django
3.2 Creating a Simple Django Application
Here’s how to create a simple Django project:
1. Create a New Project:
django-admin startproject myproject
cd myproject
2. Create a New App:
python manage.py startapp myapp
3. Define a Simple View:

In myapp/views.py, add the following code:


from django.http import HttpResponse

def home(request):
return HttpResponse("Hello, Django!")
4. Configure URL Routing:

64
@edgar cc.

In myproject/urls.py, include the app's URL:


from django.contrib import admin
from django.urls import path
from myapp import views

urlpatterns = [
path('admin/', admin.site.urls),
path('', views.home, name='home'),
]
5. Run the Development Server:

Use the following command to run the server:


python manage.py runserver
Open a web browser and navigate to http://127.0.0.1:8000/ to see the output.

4. Choosing Between Flask and Django


Flask
• Pros:
•Lightweight and flexible.
• Great for simple applications and APIs.
• Easy to learn and quick to set up.
• Cons:
• As the application grows, you may need to handle more
components manually.
• Less built-in functionality compared to Django.
Django
• Pros:

• Comprehensive framework with many built-in features.


• Well-suited for large projects with complex requirements.
• Strong community support and extensive documentation.
• Cons:

• Can be more complex and heavier than Flask.


• May require a steeper learning curve for beginners.
N/B
• Flask: Ideal for small to medium applications, APIs, or when you want
more control over components and libraries.
• Django: Best suited for larger applications or projects that require built-
in features like user authentication, admin panels, and ORM.

65
@edgar cc.

Both Flask and Django are powerful frameworks for web development in
Python. Your choice between them should depend on your project
requirements, the scale of your application, and your personal preference for
flexibility versus built-in features.
• Choose Flask for lightweight applications or when you want more
control over your stack.
• Choose Django for larger projects requiring robust features and built-
in functionalities.

Building a Simple Web Application in Python


In this guide, we will build a simple web application using Flask, a lightweight
web framework for Python. This application will allow users to submit their
names and display a greeting message.
Prerequisites
Make sure you have Python and Flask installed. You can install Flask using
pip if you haven't done so:
pip install Flask

Step 1: Setting Up the Project Structure


Create a new directory for your project:
mkdir flask_app
cd flask_app

Step 2: Creating the Flask Application


2.1 Create the Main Application File
Create a file named app.py in your project directory:
from flask import Flask, render_template, request, redirect, url_for

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])


def home():
name = ''
if request.method == 'POST':
name = request.form['name']
return redirect(url_for('greet', name=name))
return render_template('home.html')

@app.route('/greet/<name>')
def greet(name):
return render_template('greet.html', name=name)

if __name__ == '__main__':
app.run(debug=True)

66
@edgar cc.

2.2 Create HTML Templates


Flask uses a templating engine called Jinja2 to render HTML. Create a folder
named templates in your project directory:
mkdir templates
2.3 Create the Home Page Template
Inside the templates folder, create a file named home.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Home Page</title>
</head>
<body>
<h1>Welcome to the Greeting App!</h1>
<form method="POST">
<label for="name">Enter your name:</label>
<input type="text" id="name" name="name" required>
<button type="submit">Submit</button>
</form>
</body>
</html>

2.4 Create the Greeting Page Template


Create another file named greet.html inside the templates folder:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Greeting</title>
</head>
<body>
<h1>Hello, {{ name }}!</h1>
<a href="/">Go Back</a>
</body>
</html>

67
@edgar cc.

Step 3: Running the Application


Run your Flask application by executing the following command in your
terminal:
python app.py
You should see output indicating that the server is running, usually
at http://127.0.0.1:5000/.
Step 4: Testing the Application
1. Open your web browser and go to http://127.0.0.1:5000/.
2. You will see the home page with a form to enter your name.
3. Enter your name and click "Submit."
4. You should be redirected to a greeting page displaying your name.
Conclusion
Congratulations! You've built a simple web application using Flask that takes
user input and displays a greeting message. This example demonstrates the
basic structure of a Flask application, including routing, form handling, and
templating.
Next Steps
• Explore Flask Extensions: Consider using extensions like Flask-WTF
for form handling, Flask-SQLAlchemy for database integration, or
Flask-Login for user authentication.
• Deploy Your App: Look into deploying your Flask application using
platforms like Heroku, PythonAnywhere, or AWS.
• Enhance Functionality: Add more features, such as saving user inputs
to a database, handling different routes, or improving the UI with CSS
frameworks like Bootstrap.

68

You might also like