Python Libraries PDF
Python Libraries PDF
• Numpy
• Matplotlib
• Tkinter
• More on web development
Lists
A list is the Python equivalent of an array, but is resizeable and can contain
elements of different types:
Loops: You can loop over the elements of a list like this:
animals = ['cat', 'dog', 'monkey']
for animal in animals:
print(animal)
# Prints "cat", "dog", "monkey", each on its own line.
Dictionaries
A dictionary stores (key, value) pairs, similar to a Map in Java or an object in
Javascript. You can use it like this:
Sets
A set is an unordered collection of distinct elements. As a simple example,
consider the following:
Loops: Iterating over a set has the same syntax as iterating over a list; however
since sets are unordered, you cannot make assumptions about the order in which
you visit the elements of the set:
Tuples
A tuple is an (immutable) ordered list of values. A tuple is in many ways similar to
a list; one of the most important differences is that tuples can be used as keys in
dictionaries and as elements of sets, while lists cannot. Here is a trivial example:
NumPy
Numpy is the core library for scientific computing in Python. It provides a high-
performance multidimensional array object, and tools for working with these
arrays. https://numpy.org/devdocs/user/quickstart.html
Arrays
A numpy array is a grid of values, all of the same type, and is indexed by a tuple
of nonnegative integers.
The number of dimensions is the rank of the array; the shape of an array is a tuple
of integers giving the size of the array along each dimension.
We can initialize numpy arrays from nested Python lists, and access elements
using square brackets:
import numpy as np
import numpy as np
# [ 0.68744134 0.87236687]]"
Array indexing
Slicing: Similar to Python lists, numpy arrays can be sliced. Since arrays may be
multidimensional, you must specify a slice for each dimension of the array:
import numpy as np
# Use slicing to pull out the subarray consisting of the first 2 rows
# and columns 1 and 2; b is the following array of shape (2, 2):
# [[2 3]
# [6 7]]
b = a[:2, 1:3]
Exercise:
1)Write a NumPy program to test whether any of the elements of a given array is
non-zero.
2) Write a NumPy program to create an array with the values 1, 7, 13, 105 and
determine the size of the memory occupied by the array.
3) Write a NumPy program to create an array of the integers from 30 to70
Ioana Dogaru – Tehnologii de Programare Internet
Matplotlib
Matplotlib is a plotting library. In this section give a brief introduction to
the matplotlib.pyplot module, which provides a plotting system similar to that of
MATLAB.
Plotting
The most important function in matplotlib is plot , which allows you to plot 2D
data. Here is a simple example:
import numpy as np
import matplotlib.pyplot as plt
With just a little bit of extra work we can easily plot multiple lines at once, and add
a title, legend, and axis labels:
Ioana Dogaru – Tehnologii de Programare Internet
import numpy as np
import matplotlib.pyplot as plt
Subplots
You can plot different things in the same figure using the subplot function. Here
is an example:
import numpy as np
import matplotlib.pyplot as plt
y_sin = np.sin(x)
y_cos = np.cos(x)
# Set the second subplot as active, and make the second plot.
plt.subplot(2, 1, 2)
plt.plot(x, y_cos)
plt.title('Cosine')
Exercise: Write a Python program to draw a line with suitable label in the x axis,
y axis and a title.
Ioana Dogaru – Tehnologii de Programare Internet
Sample data:
Programming languages: Java, Python, PHP, JavaScript, C#, C++
Popularity: 22.2, 17.6, 8.8, 8, 7.7, 6.7
Tkinter
Python has a lot of GUI frameworks, but Tkinter is the only framework that’s
built into the Python standard library. Tkinter has several strengths. It’s cross-
platform, so the same code works on Windows, macOS, and Linux. Visual
elements are rendered using native operating system elements, so
applications built with Tkinter look like they belong on the platform where
they’re run.
import tkinter as tk
Now that you have a window, you can add a widget. Use the tk.Label class to add
some text to a window. Create a Label widget with the text "Hello, Tkinter" and
assign it to a variable called greeting. There are several ways to add widgets to a
window. Right now, you can use the Label widget’s .pack() method
import tkinter as tk
window = tk.Tk()
greeting = tk.Label(text="Hello, Tkinter")
Ioana Dogaru – Tehnologii de Programare Internet
greeting.pack()
window.mainloop()
Widget
Class Description
Label A widget used to display text on the screen
Button A button that can contain text and can perform an action when clicked
Entry A text entry widget that allows only a single line of text
Text A text entry widget that allows multiline text entry
Frame A rectangular region used to group related widgets or provide padding between
widgets
import tkinter as tk
window = tk.Tk()
greeting = tk.Label(
text="Hello, Tkinter",
foreground="white", # Set the text color to white
background="black" # Set the background color to black
)
greeting.pack()
window.mainloop()
• "red"
• "orange"
• "yellow"
• "green"
• "blue"
• "purple"
• label = tk.Label(text="Hello, Tkinter", fg="white", bg="black")
Ioana Dogaru – Tehnologii de Programare Internet
import tkinter as tk
window = tk.Tk()
greeting = tk.Label(text="Hello, Tkinter", fg="red", bg="blue")
greeting.pack()
window.mainloop()
Tkinter Buttons
The Button widget is a standard Tkinter widget, which is used for various kinds of
buttons. A button is a widget which is designed for the user to interact with, i.e. if
the button is pressed by mouse click some action might be started. They can also
contain text and images like labels. While labels can display text in various fonts, a
button can only display text in a single font. The text of a button can span more than
one line.
A Python function or method can be associated with a button. This function or
method will be executed, if the button is pressed in some way.
The following script defines two buttons: one to quit the application and another one
for the action, i.e. printing the text "Tkinter is easy to use!" on the terminal.
import tkinter as tk
def write_slogan():
print("Tkinter is easy to use!")
root = tk.Tk()
frame = tk.Frame(root)
frame.pack()
button = tk.Button(frame,
Ioana Dogaru – Tehnologii de Programare Internet
text="QUIT",
fg="red",
command=quit)
button.pack(side=tk.LEFT)
slogan = tk.Button(frame,
text="Hello",
command=write_slogan)
slogan.pack(side=tk.LEFT)
root.mainloop()
import tkinter as tk
Ioana Dogaru – Tehnologii de Programare Internet
counter = 0
def counter_label(label):
counter = 0
def count():
global counter
counter += 1
label.config(text=str(counter))
label.after(1000, count)
count()
root = tk.Tk()
root.title("Counting Seconds")
label = tk.Label(root, fg="dark green")
label.pack()
counter_label(label)
button = tk.Button(root, text='Stop', width=25, command=root.destroy)
button.pack()
root.mainloop()
Ioana Dogaru – Tehnologii de Programare Internet
Slider
A slider is a Tkinter object with which a user can set a value by moving an indicator.
Sliders can be vertically or horizontally arranged. A slider is created with the Scale
method().
Using the Scale widget creates a graphical object, which allows the user to select a
numerical value by moving a knob along a scale of a range of values. The minimum
and maximum values can be set as parameters, as well as the resolution. We can also
determine if we want the slider vertically or horizontally positioned. A Scale widget is
a good alternative to an Entry widget, if the user is supposed to put in a number from
a finite range, i.e. a bounded numerical value.
import tkinter as tk
window = tk.Tk()
window.title('My Window')
window.geometry('500x300')
def print_selection(v):
l.config(text='you have selected ' + v)
window.mainloop()
Ioana Dogaru – Tehnologii de Programare Internet
Exercise:
1) Write a Python GUI program to create a Listbox bar widgets using tkinter
module like in the following picture: (Use listbox.insert)
2) Write a Python GUI program to create three single line text-box to accept a
value from the user using tkinter module.
Ioana Dogaru – Tehnologii de Programare Internet
port → A number that generally indicates which application you are contacting
when you make a socket connection to a server. As an example, web traffic usually
uses port 80 while email traffic uses port 25.
import socket
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysock.connect(('data.pr4e.org', 80))
cmd = 'GET http://data.pr4e.org/romeo.txt HTTP/1.0\r\n\r\n'.encode()
mysock.send(cmd)
while True:
data = mysock.recv(512)
Ioana Dogaru – Tehnologii de Programare Internet
if len(data) < 1:
break
print(data.decode(),end='')
mysock.close()
HTTP/1.1 200 OK
Date: Fri, 02 Oct 2020 07:13:02 GMT
Server: Apache/2.4.18 (Ubuntu)
Last-Modified: Sat, 13 May 2017 11:22:22 GMT
Accept-Ranges: bytes
Cache-Control: max-age=0, no-cache, no-store, must-revalidate
Pragma: no-cache
Expires: Wed, 11 Jan 1984 05:00:00 GMT
Connection: close
Content-Type: text/plain
Content-Length: 167
Once we send that blank line, we write a loop that receives data in 512-character
chunks from the socket and prints the data out until there is no more data to read
(i.e., the recv() returns an empty string).
Ioana Dogaru – Tehnologii de Programare Internet
Sockets can be used to communicate with a web server or with a mail server or
many other kinds of servers. All that is needed is to find the document which
describes the protocol and write the code to send and receive the data according
to the protocol.
One of the requirements for using the HTTP protocol is the need to send and
receive data as bytes objects, instead of strings. In the preceding example, the
encode() and decode() methods convert strings into bytes objects and back again.
We can use a similar program to retrieve an image across using HTTP. Instead
of copying the data to the screen as the program runs, we accumulate the data in
a string, trim off the headers, and then save the image data to a file as follows:
# Code: http://www.py4e.com/code3/urljpeg.py
import socket
HOST = 'data.pr4e.org'
PORT = 80
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysock.connect((HOST, PORT))
mysock.sendall(b'GET http://data.pr4e.org/cover3.jpg HTTP/1.0\r\n\r\n')
count = 0
picture = b""
while True:
data = mysock.recv(5120)
if len(data) < 1: break
#time.sleep(0.25)
count = count + len(data)
print(len(data), count)
picture = picture + data
mysock.close()
# Look for the end of the header (2 CRLF)
pos = picture.find(b"\r\n\r\n")
print('Header length', pos)
print(picture[:pos].decode())
# Skip past the header and save the picture data
picture = picture[pos+4:]
fhand = open("stuff.jpg", "wb")
fhand.write(picture)
Ioana Dogaru – Tehnologii de Programare Internet
fhand.close()
You can see that for this url, the Content-Type header indicates that body of the
document is an image (image/jpeg). Once the program completes, you can view
the image data by opening the file stuff.jpg in an image viewer.
Ioana Dogaru – Tehnologii de Programare Internet
While we can manually send and receive data over HTTP using the socket library,
there is a much simpler way to perform this common task in Python by using the
urllib library.
Using urllib, you can treat a web page much like a file. You simply indicate which
web page you would like to retrieve and urllib handles all of the HTTP protocol and
header details.
The equivalent code to read the romeo.txt file from the web using urllib is as
follows:
import urllib.request
fhand = urllib.request.urlopen('http://data.pr4e.org/romeo.txt')
# Code: http://www.py4e.com/code3/urllib1.py
Once the web page has been opened with urllib.urlopen, we can treat it like a file
and read through it using a for loop.
When the program runs, we only see the output of the contents of the file.
The headers are still sent, but the urllib code consumes the headers and only
returns the data to us.
As an example, we can write a program to retrieve the data for romeo.txt and
compute the frequency of each word in the file as follows:
Again, once we have opened the web page, we can read it like a local file.
# Code: http://www.py4e.com/code3/urlwords.py
Exercise: Change the socket program to prompt the user for the URL so it can
read any web page. You can use split('/') to break the URL into its component parts
so you can extract the host name for the socket connect call. Add error checking
using try and except to handle the condition where the user enters an improperly
formatted or non-existent URL.
References:
https://cs231n.github.io/python-numpy-tutorial/
https://www.py4e.com/
https://realpython.com/python-sockets/