Lecture notes on Introduction to Python programming final
Lecture notes on Introduction to Python programming final
LECTURE NOTES
UNIT NAME: Python Programming
PREPARED BY: Edgar Addero
1
@edgar cc.
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.
3
@edgar cc.
4
@edgar cc.
5
@edgar cc.
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.
# 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'>
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+):
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)
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.
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)
11
@edgar cc.
12
@edgar cc.
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: "))
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.
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.
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
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.
# Access an element
print(fruits[1]) # Output: banana
# Add an element
fruits.append("orange")
18
@edgar cc.
# Remove an element
fruits.remove("apple")
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.
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.
# Access a value
print(person["name"]) # Output: Alice
# Update a value
person["age"] = 31
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}
22
@edgar cc.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1 | set2 # {1, 2, 3, 4, 5}
• Intersection: Returns elements common to both sets.
# Add an element
my_set.add(6)
# Remove an element
my_set.remove(3)
# Check membership
print(2 in my_set) # Output: True
# 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)
24
@edgar cc.
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.
def access_global():
print(global_var)
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}.")
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.
27
@edgar cc.
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}")
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
28
@edgar cc.
This capability enhances the modularity and readability of your code, making
it easier to maintain and expand.
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]
30
@edgar cc.
def greet(name):
return f"Hello, {name}!"
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`
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
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.
def greet(name):
"""Function to greet a person by name."""
return f"Hello, {name}!"
def square(number):
"""Function to return the square of a number."""
return number ** 2
33
@edgar cc.
import mymodule as mm
34
@edgar cc.
# 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
35
@edgar cc.
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.
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"]
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.")
38
@edgar cc.
data = [
['Name', 'Age', 'City'],
['Alice', 30, 'New York'],
['Bob', 25, 'Los Angeles'],
['Charlie', 35, 'Chicago']
]
39
@edgar cc.
data = [
{'Name': 'Alice', 'Age': 30, 'City': 'New York'},
{'Name': 'Bob', 'Age': 25, 'City': 'Los Angeles'},
{'Name': 'Charlie', 'Age': 35, 'City': 'Chicago'}
]
data = {
'employees': [
{'name': 'Alice', 'age': 30, 'city': 'New York'},
{'name': 'Bob', 'age': 25, 'city': 'Los Angeles'},
{'name': 'Charlie', 'age': 35, 'city': 'Chicago'}
]
}
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.
41
@edgar cc.
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')
42
@edgar cc.
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)
43
@edgar cc.
dog1 = Dog("Buddy", 3)
dog2 = Dog("Max", 5)
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).
44
@edgar cc.
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")
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
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()
46
@edgar cc.
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
# Example usage
person = Person("Alice")
print(person.get_name()) # Output: Alice
person.set_name("Bob")
print(person.get_name()) # Output: Bob
48
@edgar cc.
49
@edgar cc.
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.")
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)
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.
52
@edgar cc.
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.
# 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)
55
@edgar cc.
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())
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.
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]
58
@edgar cc.
plt.ylabel("Values")
plt.show()
5. Creating a Histogram
Example: Histogram
import numpy as np
# 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]
# 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.
# Bottom-right plot
axs[1, 1].hist(data, bins=30)
axs[1, 1].set_title("Bottom Right Plot")
60
@edgar cc.
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'])
61
@edgar cc.
x = df['Name']
y = df['Salary']
62
@edgar cc.
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:
def home(request):
return HttpResponse("Hello, Django!")
4. Configure URL Routing:
64
@edgar cc.
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.home, name='home'),
]
5. Run the Development Server:
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.
app = Flask(__name__)
@app.route('/greet/<name>')
def greet(name):
return render_template('greet.html', name=name)
if __name__ == '__main__':
app.run(debug=True)
66
@edgar cc.
67
@edgar cc.
68