Python Tutorial
Standard Libraries:
This page can be downloaded as interactive jupyter notebook
An additional quiz about the contents of this tutorial, can be downloaded here (with solutions)
In this chapter, you will learn to use Libraries
(Some useful and applicable libraries) in python.
Library:
The library contains built-in modules (written in C) that provide access to system functionality such as file I/O that would otherwise be inaccessible to Python programmers, as well as modules written in Python that provide standardized solutions for many problems that occur in everyday programming.(docs.python.org)
Import modules:
In python, we can import any module easily using this simple script,
import numpy
When the program execute this line, the program will add module numpy
as numpy. Then we can use this module in rest of our code. Also we can summarize the name of the module by mentioning it by as
.
For example:
import numpy as np
Then, it is accessible only by np
.
datetime:
This module works with times and dates. Let’s learn more this module by following examples.
Example: Let’s run the codes below to get current time and date.
# import module at first
import datetime
# create a `datetime` object containing current time and date using `now()`
current_datetime = datetime.datetime.now()
# print the rsult
print(current_datetime)
# Get current date
today_date = datetime.date.today()
print(today_date)
# Represent a date
my_birthday = datetime.date(1998, 5, 22)
print(my_birthday)
- Also, we can import only class
date
from the module.
# Represent a date
from datetime import date
Today = date(2019,11,30)
print(Today)
# Print year, month and day seperately
from datetime import date
Today = date.today()
print('Year: ',Today.year)
print('Month: ',Today.month)
print('Day: ',Today.day)
# print Hour, Minute, Second and Microsecond
from datetime import time
Time = time(10,26,41,365)
print('Hour: ',Time.hour)
print('Minute: ',Time.minute)
print('Second: ',Time.second)
print('Microsecond: ',Time.microsecond)
Get date from timestamp
In python, we can generate date
from a timestamp.
Timestamp: A timestamp is the number of seconds between a date and first of January 1970 at UTC.
Example: Let’s run the code below to generate a date object from timestamp.
# Import class from module
from datetime import date
# Generate the date from timestamp
my_timestamp = date.fromtimestamp(1234567890)
print('My date is: ',my_timestamp)
Mathematics
In python, we can have access to the underlying C library functions via math
module.
Example:
# Import module
import math
a = math.sin(math.pi)
b = math.log2(1024)
print('a = ',a)
print('b = ',b)
Random:
It is a module which provides tools to make random variables.
Example: Providing random variable.
# Import module
import random
# random float number
N1 = random.random()
print('The float random number is: ',N1)
# random integer number choose from range of 10
N2 = random.randrange(10)
print('The integer random number in range of 10 is: ',N2)
# random sampling of 10 numbers in range of 1000, without replacement
N3 = random.sample(range(1000),10)
print('The random sample numbers are: ',N3)
Statistics:
It is a module which calculates basic statistic properties of numeric data. (Such as: mean, median, variance and etc.)
Example: Computation of statistical properties.
# Import module
import statistics
my_data = [5, 7, 6.3, 1.2, 8, 1, 4.5, 5.9]
# computation of properties
Mean = statistics.mean(my_data)
print('The mean value of the data is: ',Mean)
Median = statistics.median(my_data)
print('The median value of the data is: ',Median)
Variance = statistics.variance(my_data)
print('The variance of the data is: ',Variance)
Internet Access
In python, we can use module urllib.request
to retrieve data from URLs and module smtplib
to send email.
Also, there are several modules for accessing the internet.
Example: Send an email.
import smtplib
server = smtplib.SMTP('localhost')
server.sendmail('sender@example.org', 'receiver@example.org',
"""To: receiver@example.org
From: sender@example.org
This is just an example.
""")
server.quit()
Note: This example needs a real mail server running in localhost.
Example: Retrieve data from URL.
from urllib.request import urlopen
with urlopen('http://example.txt') as response:
for line in response:
if 'Name' in line:
print(line)
Note: This example needs a real data url to run.
Data Compression
Python has some usefull modules for archiving and compression formats such as, zlib
, gzip
, zipfile
and tarfile
.
Example: Compressing data.
import zlib
line = b'Python tutorial Python tutorial Python tutorial Python tutorial'
print('Length of the text: ',len(line))
com_line = zlib.compress(line)
print('Length of the text after compression: ',len(com_line))
decom_line = zlib.decompress(com_line)
print('Length of the text after decompression: ',len(decom_line))
dir() Function
dir()
is a built-in function in python to list all functions or variable names in a module.
Example: List all function names in datetime
module.
import datetime
List = dir(datetime)
print(List)
RegEx
Regular Expression (RegEx) forms a search pattern in a sequence of characters. We can use RegEx
to check if a string contains a specific search pattern.
In python, Regular Expression is accessible by calling a built-in package re
.
import re
This module offers some functions to search a string for finding a match. The following table represent these functions.
No. | Function | Functionality |
---|---|---|
1 | findall | It returns all matches as a list |
2 | search | It returns a Match object if there is a match anywhere in the string |
3 | split | It returns a list where the string has been split at each match |
4 | sub | It replaces match or matches with a string |
- Search the string to find out if it starts and ends with specific string.
Example: Search the input string to find out if it starts with “I” and ends with “Hannover”.
import re
input_txt = 'I am studying in Leibniz University Hannover'
a = re.search("^I.*Hannover$",input_txt)
print('Result of search a: ',a)
b = re.search("^The.*Hannover$",input_txt)
print('Result of search b: ',b)
- Metacharacters: They are characters with special functionality.
The following table shows some Metacharacters.
No. | Character | Functionality | Example |
---|---|---|---|
1 | [] | Takes a set of characters | “[a-m]” |
2 | {} | Specified number of occurrences | “al{2}” |
3 | () | It captures and groups | ”()” |
4 | \ | It signals a special sequence | “\d” |
5 | + | One or more occurrences | “aix+” |
6 | * | Zero or more occurrences | “aix*” |
7 | . | For any character in a line | “py..on” |
8 | ^ | Starts with | “^word” |
9 | dollar sign | Ends with | “word$” |
RegEx functions
Here we have some functions of this module.
findall()
This function returns all matches as a list.
Example: Find and print all matches of string in
in input string.
import re
input_str = "I am studying in Leibniz University Hannover"
out_lst = re.findall("in",input_str)
print(out_lst)
search()
This function takes a string as input, then searches the string to find a match. And returns a match object if there is a match. If there is more than one match, it returns only the first occurrence.
Example: Let’s run the code below to find out how this function works. Try to change the search string to see different result.
import re
input_str = "I am studying in Leibniz University Hannover"
p = re.search("Leibniz", input_str)
print(p)
split()
It returns a list where the string has been split.
Example: Let’s run code below to see the result of split.
import re
input_str = "I am studying in Leibniz University Hannover"
out_str = re.split("\s", input_str)
print(out_str)
print('Print only first word: ',out_str[0])
sub()
It takes a string as choice, then replaces the matches with the string choice.
Example: Replace all space in the input text with comma.
import re
input_str = "I am studying in Leibniz University Hannover"
out_str = re.sub("\s", ",", input_str)
print(out_str)
Match Object
It is an object which contains information about the search and the result. It returns None
value instead of the Mach Object
, if there is not any match.
The match object has methods and properties used to get information and the result of the search. Three of these properties are represented below:
.string
: It returns the string passed into the function..span()
: It returns the start and end position of the match as a tuple..group()
: It returns the part of the string where there was a match.
Example: Search string Hann
in the input string to get a Match Object as a result, and print it out.
import re
input_str = "I am studying in Leibniz University Hannover"
Result = re.search("Hann", input_str)
print(Result)
- Print the position of the match occurrence.
print(Result.span())
- Print the string passed into the function.
print(Result.string)
- Print the part of the string where there was a match.
print(Result.group())
Following code-cell removes In[]
/ Out[]
prompts left to code cells.
%%HTML
<style>div.prompt {display:none}</style>
Author: | Mohsen Soleymanighezelgechi |
Last modified: | 12.12.2019 |