0% found this document useful (0 votes)
14 views21 pages

Python Lesson 6 Classes, Objects, Dictionaries, Modules, Libraries, and Graphing Techniques

Python Lesson

Uploaded by

Xuan Zheng Lim
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views21 pages

Python Lesson 6 Classes, Objects, Dictionaries, Modules, Libraries, and Graphing Techniques

Python Lesson

Uploaded by

Xuan Zheng Lim
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 21

Dictionaries, Modules,

Commands, Libraries, and


Examples
Dr. Saima Nisar
PhD (IT), MS (IT), BBA (Hons.)
Learning Objectives:
• Classes and Objects
• Python Dictionaries
• Import and use Modules
• Python Libraries
• Plot Graphs with Matplotlib
• Apply Machine Learning with Scikit-learn
What is a Class?
• A class is a blueprint for creating objects (instances).

• It defines a set of attributes (variables) and methods


(functions) that the objects created from the class can
have.
What is a Object?
• An object is an instance of a class.
• Each object contains data (attributes) and behavior
(methods).
• Objects allow you to store data and perform actions
based on that data.
Class and Object
# Define a simple class called Dog
class Dog:
# A method to make the dog bark
def bark(self):
print("Woof!")

# Create an object (a dog)


my_dog = Dog()

# Make the dog bark


my_dog.bark()
What is a Dictionary?
• A dictionary is a data type that works with keys and
values instead of indexes. Each value stored in a
dictionary can be accessed using a key, which can
be any type of object.

# Creating a dictionary with keys and values


phonebook = {
"John": 938477566,
"Jack": 938377264,
"Jill": 947662781
}
# Accessing a value using a key
print(phonebook["John"]) # Output: 938477566
Iterating Over Dictionaries
• In Python, you can iterate over key-value pairs in
a dictionary using the .items() method, which
returns each pair as a tuple.
• The key is the first element, and the value is the
second element.

for name, number in phonebook.items():


print(f'Phone number of {name} is {number}')
Iterating Over Dictionaries
How it works:
phonebook.items() returns a list of tuples where
each tuple contains a key-value pair.
Example: ("John", 938477566).

The loop assigns:


• name to the key (e.g., "John")
• number to the value (e.g., 938477566)

Output is formatted using an f-string to print a


custom message:
• Phone number of {name} is {number}
Removing Values from a Dictionary

To remove items from a dictionary specified key, use


either one of the following notations:

del phonebook['John’]
phonebook.pop('John’)

Both methods will remove the key 'John' and its


associated value from the dictionary.
What is a Module?
• In programming, a module is a single file (with a .py
extension) that contains Python code, such as functions,
classes, and variables, and is designed to provide specific
functionality.

• Each module is a different file, making the code more


organized and easier to manage. You can edit each
module separately.
• Example:
math: Provides mathematical functions like square roots.
datetime: Handles date and time manipulation.
Python Commands

• The keyword.kwlist command actually prints out


all the reserved keywords in Python, not all
commands.
• Keywords are specific reserved words that have
special meaning in Python (like if, for, while,
class, etc.).

import keyword
Print(keyword.kwlist)
Python Libraries

• Python Libraries are collections of modules that


provide useful functions and eliminate the need for
writing code from scratch.
• There are over 137,000 python libraries present
today.
• Python libraries play a vital role in developing
machine learning, data science, data visualization,
image and data manipulation applications and more.
• Examples: NumPy, Pandas, Matplotlib, Scikit-learn
Key Python Libraries
Python Libraries

• Python libraries provide reusable code for tasks


such as data analysis, machine learning, and more.
Common libraries include NumPy, Pandas, and
Matplotlib.

python -m pip install numpy


python -m pip install scipy
python -m pip install
matplotlib
python -m pip install
pandas
Example: Graphing with Matplotlib

Example of using Matplotlib to plot a simple graph.

import numpy as np
import matplotlib.pyplot as plt
# Create 1000 evenly spaced values from 0 to 100
t = np.linspace(0, 100, 1000)
# Plot t vs t^2 (quadratic function)
plt.plot(t, t**2)
# Display the plot
plt.show()
Example: Graphing with Matplotlib
1.import numpy as np:
This imports the NumPy library and assigns it the alias np for
ease of use. NumPy is widely used for working with arrays and
numerical data.

2.import matplotlib.pyplot as plt:


This imports the Matplotlib library’s pyplot module as plt.
Matplotlib is commonly used for plotting graphs and visualizing
data.

3.t = np.linspace(0, 100, 1000):


 The np.linspace() function generates an array of 1,000 evenly
spaced numbers between 0 and 100.
 t will store this array of values, which will be used as the x-axis
values for the graph.
Example: Graphing with Matplotlib

4.plt.plot(t, t**2):
 plt.plot() is the function that plots a graph.
 t is the array of x-values (from 0 to 100).
 t**2 is the array of y-values, where each value of t
is squared. So, the graph will plot the square of t
on the y-axis.

5.plt.show():
 This displays the graph to the user. Without calling
this, the graph won't appear.
Example: Machine Learning with
Scikit-learn
Here is an example of using Scikit-learn for machine
learning.
The Iris dataset is one of the most famous datasets
used in machine learning. Adding a brief description
could help clarify this for beginners.

from sklearn import datasets


iris = datasets.load_iris()
print(iris.data[:5])
Example: Machine Learning with
Scikit-learn
1.From sklearn import datasets :
This imports the datasets module from scikit-learn, a library that
provides a collection of machine learning datasets and functions
to load them

2.Iris = datasets.load_iris():
This line loads the Iris dataset, which contains information about
150 iris flowers, categorized into 3 species: Setosa, Versicolor,
and Virginica.
The dataset includes 4 features for each flower:

Sepal length Sepal width


Petal length Petal width

These features are stored in iris.data, and the species (labels)


are stored in iris.target.
Example: Machine Learning with
Scikit-learn
3. print(iris.data[:5]):
 This prints the first 5 rows of the dataset, showing the feature
values (sepal and petal measurements) for the first 5 flowers.
 The output will be a NumPy array containing the
measurements for each flower.
Thank you

You might also like