Python Notes
Python Notes
Python is a general purpose, high level, remarkably powerful dynamic programming language used in a
wide variety of application domain.
Advantages of Python
What is IPython?
IPython is an enhanced interactive Python interpreter. It provides features like tab-completion and easier
access to help
Ipython interpreter can be opened by typing Control+Alt+t simultaneously. The interpreter opens and at
the command prompt type ipython3 as shown below
The IPython interpreter can be quit by pressing Control+D key simultaneously near the prompt.
Different operations can be done by typing at the command prompt as shown below
Ipython does auto completion of the commands which is known as tab completion
To use the IPython help, type the command followed by ? and the interpreter returns the documentation
about the command
The command round(number[, ndigits]) -> number is used to round a number to a given precision in
decimal digits. This returns an int when called with one argument, otherwise the same type as the number.
ndigits may ne negative also
The typing errors can be corrected by getting a prompt with dots, which is continuation prompt of
IPython which appears when the previous line is incomplete. The command can be completed by closed
parenthesis
The pylab package should be intitiated at the command prompt by typing %pylab.
Pylab is a convenient Python module which provides plotting functionality and has mathematical as well
as scientific functions. Pylab uses matplotlib at backend. An error may occur sometimes that says
The linspace command returns evenly spaced numbers over a specified interval. Returns ‘num’ evenly
spaced samles, calculated over the interval [‘start’, ‘stop’]. The endpoint of the interval can be optionally
executed.
[1] t=linspace(-pi,pi,100)
[2] cosine=cos(t)
[2] plot(t,cosine)
At the bottom of the figure window, different buttons are present in which the save button can be usedto
save the plot in any of the image file formats. To the left of the button is the slider button through which
margins can be specified. To the left of the slider button is the zoom button.The button to the left is used
to move the axis of the plot. The next two buttons to the left of the zoom are back and forward buttons
which are used to refer to the previous plots. The last one is the home referring to the initial plot.
To clear the plot clf() function should be used. This avoids overlapping of new plots to over older plots.
Day 1 Video Link 3
Embellishing a Plot
The attributes of the plot such as color, line style, line width can be modified. Title and labels of x-y axes
can be added through arguments in the plot. The following code
[1] x=linspace(-2,4,20)
[2] plot(x, sin(x), ‘r’)
[3] plot(x, cos(x), linewidth=2)
[1] x=linspace(-2,4,20)
[2] plot(x,-x*x+4x-5, ‘r’, linewidth=2)
[3] title(r“Parabolic function $-x*x+4x-5$”) --- The ‘r’ in the title treats as raw string
[4] xlabel(r”$x$”)
[5] ylabel(r”SyS”)
[6] annotate(“local maxima”, xy=(2,-1)) ---- Used to obtain local maxima. It’s a tuple containing x and y
Coordinates.
[7] xlim(-4,5)
[8] ylim(-15,2)
The following figure window appears on line by line execution of the above code
Day 1 Video Link 4
Saving Plots
Plots can be saved by using savefig(fname) which takes only one argument which is the filename.
Multiple Plots
[1] x=linspace(0,50,10)
[2] plot(x, sin(x))
[3] y=linspace(0,50,500)
[4] plot(y,sin(y))
[5] legend([‘sin(x)’,’sin(y)’])
Plot can be obtained separately using figure() command with the following code
[1] x=linspace(0,50,500)
[2] figure(1)
[3] plot(x,sin(x),’b’)
[4] title(‘sin(x)’)
[5] savefig(‘sine.png’)
[6] figure(2)
[7] plot(x,cos(x),’r’)
[8] title(‘cos(x)’)
[9] savefig(‘Cosine.png’)
Day 2 Video Link 1
Subplots
Subplots can be used to obtain two different plots in the same figure window. The following code is used
to illustrate the use of subplots
[1] x=linspace(0,50,500)
[2] plot(x, cos(x))
[3] y=linspace(0,5,100)
[4] plot(y,y**2)
On running the above code, two plots are obtained which have the same axis, so overlaid plots cannot be
drawn. In such cases subplots can be drawn
[1] clf()
[2] x=linspace(0,50,500)
[3] plot(x,cos(x))
[4] subplot(2,1,1)
[5] plot(x,sin(x))
[6] subplot(2,1,2)
The following figure window with two plots is obtained using subplot
Day 2 Video Link 2
[1] x = linspace(-*pi,2*pi,100)
[2] plot(x,xsin(x))
This gives an error since xsin(x) is not recognized and it should be given as x*sin(x)
The history of the typed command can be retrieved using the %history. When %history is type at the
command prompt, what ever is executed is stored as history
[7]: %history
%pylab
x = linspace(-*pi,2*pi,100)
plot(x,xsin(x))
plot (x,x*sin(x))
xlabel(“$x$”)
ylabel(‘$f(x)$”)
title(“$x and xsin(x)$”)
%history
The command at the fifth line of the code can be accessed using
[8] %history 5
xlabel(“$x$”) - is Displayed on execution of the code %history 5
The command %history -n 4-6 displays the code form the lines 4 to 6. The ‘n’ in %history is an optional
command and it can be omitted. The commands in the %history can be saved
On giving the above command the following code is saved to plot_script.py omitting line number 3 and
saving from line numbers 4 to 7
x = linspace(-*pi,2*pi,100)
plot (x,x*sin(x))
xlabel(“$x$”)
ylabel(‘$f(x)$”)
title(“$x and xsin(x)$”)
To run the file as python script use the command %run -i plot_script.py
Here ‘i’ runs the program in the test editor. The script is run but plot is not seen becoz we are running a
script that is not in the interactive mode.
[1] %pylab
[2] cat primes.txt
The prime numbers are displayed at the terminal
[3] primes=loadtxt(“primes.txt”)
The prime numbers are stored in the file primes.
[4] print(primes)
The prime numbers are printed ending with a period becoz all the numbers are floats
[5] cat pendulum.txt
This file contains two columns in which the first column contains the length of the pendulum and the
second column contains the time period
[6] pend=loadtxt(“pendulum.txt”)
Loadtxt loads both the columns equally in to the variable pend
[7] print(pend)
The variable pend has two sequences containing two columns in the file
[8] L,t=loadtxt(‘pendulum.txt”,unpack=True)
[9] print(L)
L contains the data of the first column of pendulum.txt
[10] print(t)
T contains the data in the second column of the pendulum.txt
Upack=True has the two column in to two separate sequences
The data separated by semicolon in pendulum_semicolon.txt can be read using the comman
[11] cat pendulum_semicolon.txt
[12] L,t = loadtxt(“pendulum_semicolon.txt”, unpack=True,delimiter=’;’)
[13] print(L)
This prints the sequence in L.
Day 2 Video Link 4
Plotting Data
To plot data, a list need to be defined. Element wise squaring of the list must also be done.
[1] I=[0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]
[2] t=[0.69, 0.90, 1.19, 1.30, 1.47, 1.58, 1.77, 1.83, 1.94]
[3] tsquare=square(t)
[4] plot(I, tsquare, ‘.’)
Errorbar plots an error graph. Plot x versus y with error deltas in yerr and xerr. Vertical errorbars are
plotted if yerr is not None. Horizontal error bars are plotted if xerr is not none. x,y,xerr, yerr can all be
scalars, which plots a. The error bar for the above code is shown below.
Day 2 Video Link 5
[1] %pylab
[2] cat company-a-data.txt -The first column represent the years and the second column represents the profit
[3] year,profit = loadtxt(‘company-a-txt’, unpack=True)
[4] scatter(year, profit, color=’r’, marker=’d’)
Log-Log Graph
A log-log plot is a two dimensional graph of numerical data. It uses logarithmic scales on both axes.
Graph appears as straight line due to non-liner scaling
Syntax : loglog(x,y)
Where x is a sequence of data and y is also a sequence od data having same length as x
[1] x=linspace(1,20,100)
[2] y=5*x**3
[3] clf()
[4] loglog(x,y)
The following plot is obtained
Day 3 Video Link 1
Plotting Charts
Pie chart
A pie chart is a circular chart divided into sectors, to illustrate numerical proportion
Plot a pie chart representing the company profit percentage. Use the data from the file company-a-data.txt
[1] %pylab
[2] cat company-a-data.txt -The first column represent the years and the second column represents the profit
[3] year,profit = loadtxt(‘company-a-txt’, unpack=True)
[4] clf()
[5] pie(profits, year)
Bar chart
A bar chart is a chart with rectangular bars, with lengths proportional to the values that they represent
Syntax : bar(x,y)
x-sequence of data
y-sequence of datd, the same length of x
Plot a pie chart representing the company profit percentage. Use the data from the file company-a-data.txt
[1] %pylab
[2] cat company-a-data.txt -The first column represent the years and the second column represents the profit
[3] year,profit = loadtxt(‘company-a-txt’, unpack=True)
[4] clf()
[5] bar(profits, year, fill=False, hatch=’/’)
Day 3 Video Link 2
A List can store a sequence of elements. All elements need not be of the same type
Variable must either start with an alphabet or an underscore. They cannot start with numbers and cannot
be the same as Python keywords.
Few examples of key words are : for, if, else, elif, while, in, def, or, and
A variable name cannot have spaces or punctuation characters or any arithmetic characters.
[1] %pylab
[2] mylist = [‘spam’, ‘eggs’, 100, 1.234]
[3] type(mylist) – Returns ldata type of the variable mylist
[4] num_list= [1,2]
[5] x = [‘a’,’b’]
[6] myemptylist = []
Syntax : variable[index]
In [7] mylist[0]
Out[7] Returns ‘spam’
In [8] mylist[-1]
Out[8] 1.234
List can also be created inside a List. This property makes list heterogeneous data structures
Syntax:
Variable = [list1][list2]
[9] doublelist = [‘a’, [‘b’, ‘c’, ‘d’], ‘and’, 5, 6, 7, 8]
In [10] doublelist[1]
out[10][‘b’, ‘c’, ‘d’]
In [11] doublelist[1][0]
Out[11] ‘b’
In [12] doublelist[2]
Out[12] and
In [13] doublelist[-5]
Out[13] and
In [14] doublelist[1][2]
Out[14] d
The len() function is used to check the number of elements in the list
Syntax: len(variable)
In [15] mylist = [‘spam’, ‘eggs’, 100, 1.234]
In [16] len(mylist)
Out[16] 4
Elements can be appended to the list by using append function. This function will add the element to the
end of the list
Syntax : variable.append(element)
In [17] mylist.append(‘sharp’)
In [18] mylist.append(6)
In [19] mylist
Out[19] mylist = [‘spam’, ‘eggs’, 100, 1.234, ‘sharp’, 6]
Elements can also be removed from lists. One is by using the index with del keyword
Syntax del variable[index]
The other way is removing element by value using remove function
Syntax: variable.remove(element)
In [20] mylist
Out [20] ‘spam’, ‘eggs’, 100, 1.234, ‘sharp’, 6]
In [21] del mylist[1]
In[22] mylist
Out[22] [‘spam’, 100, 1.234, ‘sharp’, 6]
In[23] mylist.remove(100)
In[24] mylist
Out[24] [‘spam’, 1.234, ‘sharp’, 6]
In[25] mylist.append(‘spam’)
In[26] mylist
Out[26] [‘spam’, 1.234, ‘sharp’, 6, ‘spam’]
In[27] mylist.remove(‘spam’)
In[28] mylist
Out[28] [1.234, ‘sharp’, 6, ‘spam’] – Only the first ‘spam’ is remoed becoz the fnction remoe removes
only the first occurrence of the element in the sequence
In[29] k=[1,2,1,3]
In [30] k.remove(k[2])
In [31] k
Out[31][2,1,3] – the first occurrence of the element is deleted
For statement iterates over the members of a sequence in order, executing the bock each time
Save the file as sqrt_num_list.py and run in the console window. The output appears as follows
range() function
for i in range(1,11):
print(I,”Cube is”, i**3)
Parsing Data
Parsing the data is reading the data in text form. It is converted in to a form which can be used for
computations.
split() function
split( ) function breaks up a larger string into smaller strings using a defined separator. If no argument is
specified, then whitespace is used as default separator
Syntax : str.split(argument)
Split( ) function parses a string and returns an array of tokens. This is called string tokenizing.
In[4]: x = “19-06-1983;05-04-2008;30-11-2019”
In[5]: split(‘;’)
Out[5] [‘19-06-1983’;’05-04-2008’;’30-11-2019’]
In[6]: b = x.split( )
Out[6] [‘19-06-1983’;’05-04-2008’;’30-11-2019’]
In[7]: c = x.split(‘ ‘)
Out[7]: [‘19-06-1983’;’05-04-2008’;’30-11-2019’]
Splitting the string without argument will split the string separated by any number of spaces. Giving space
as an argument will split the sentence specifically on single whitespace.
It can be observed that there are two white spaces in the output
The white spaces at the beginning and the end of the string can be removed by unstripped.strip()
In[17] int(“1.25”)
ValueError: Invalid literal for int() with base 10: ‘1.25’
Statistics
Doing statistical operations in Python, finding the sum of a set of numbers and to calculate the mean,
median and standard deviation.
Numpy(Numerical Python)
It is a library consisting of precompiled functions for mathematical and numerical routines. NumPy has to
be installed separately.
loadtxt( )
To get the data as an array, use the loadtxt( ) function. For loadtxt ( ) function, import numpy library first
Loops
While loop
Syntax : while<condition>:
#True block statements
#update condition variable
#statements after while loop
The code inside the while loop should be indented four spaces to the right
[1] i=1
[2] while i<10:
print(i*i)
i+=2
The output is obtained as
1
9
25
49
81
The output is obtained as the same and only two lines of code are sufficient using for loop.
Write a while loop to print the squares of all the even numbers below 10
[4] i=2
[5] while i<10
print(i*i)
i+=2
The output is as follows
4
16
36
64
Write a for loop to print the squares of all the even numbers below 10
The pass in the for loop does not allow to print any statements
[7] for n in range(2,10,2):
pass
The for loop iterates and when the letter ‘h’ is encountered the loop breaks and the output is as follows
Current Letter : p
Current Letter : y
Current Letter : t
Manipulating Lists
Slicing of lists can be done using the command Slicing. The syntax is p[start:stop]
It returns all the elements of p between start and stop. The element with the stop index value will not be
included.
In [3] primes[0:4]
Out[3] [2, 3, 5, 7]
Write a program to find all the odd numbers below 10 from the given numbers
In[9] num[::3]
Out[9] [0, 3, 6, 9, 12]
Python provides a built in sorted() function. Sorted() sorts the list which is passed as an argument to it. It
returns a new sorted list.
In [13] a=[ 5, 1, 6, 7, 7, 10]
In [14] sa=sorted(a)
In[15] sa
Out[15] [1, 5, 6, 7, 7, 10]
In[16] r=[1, 2, 3, 4, 5]
In[17] r.reverse()
In[18] r
Out[18] [5, 4, 3, 2, 1]
In[19] ra=r[::-1]
In[20] ra
Out[20] [5, 4, 3, 2, 1]
Day 6 Video Link 3
Manipulating Strings
String slicing
Syntax: string_name[start:stop]
String_name[start:step:stop]
In[1] data=”python”
In[2] print(data[0:3]) –The string is obtained from the index 0 to 2 and doesnot include 3
Out[2] pyt
Obtain the substring excluding the last characters from the string s=”Saturday”
In [7] s[1:-1]
Out[7] ‘aturda’
Reversing a String
In[8] s1=’liril’
In[9] s1==s1[::-1]
Out[9] True - Indicates that the given string is Palandrome
If the string is given as Liril the comparison would written false so all the characters in the given string
should be in the upper case or in the lower case.
In[9] s2=’Liril’
In[10] s2.upper()
Out[10] ‘LIRIL’ – The string in s2 remains unchanged and the new string is copied in to a new variable
Check if each element in the following list is present in the list week_name
[“SATURDAY’, ‘python’, “Sunday”]
In[14] for day in [‘SATURDAY’,’python’, ‘Sunday’]:
print(day, day.lower()[:3] in week_name)
SATURDAY True
python FALSE
Sunday True
Replacing a string
The different Emails are combined in to one string and output is obtained as follows
Tuple is a collection of elements similar to a list. Tuple uses parentheses, whereas list uses square
brackets. Elements of a tuple cannot be changed once they are assigned where as elements in a list can be
changed
Examples of Tuples
➢ (1, 2.5) and 1, 2.5 are same
➢ (1, ) and 1, are same
➢ ((1,),) and (1,), are same
In[3] t[3]
Out[3] -4
In[4] t[1:5:2]
Out[4] (2.5, -4)
In[5] t[2]=”hello”
This indicates that the elements of the tuple cannot be changed after it is created which is known as
Immutability. Iteration of tuples can be done
In[6] for x in t:
print(x)
1
2.5
Hello
-4
World
1.24
5
In[7] a=5
In[8] b=7
In[9] temp=a
In[10] a=b
In[1] b=temp
Now check for the values of a and b
In[12] a
Out[12] 7
In[13] b
Out[13] 5
This is in the traditional approach. It can be done in Python in a different way for different data types
In[14] a=2.5
In[15] b=”hello”
In[16] a,b=b,a – The values of b,a are packed in to a tuple, then it is unpacked in to variables a,b
In[17] a
Out[17] “hello”
In[18] b
Out[18] 2.5
This is possible because of the immutability of tuples. This is called packing and unpacking of tuples.
Immutability of tuples ensures that the values are not changed during packing and unpacking
Day 6 Video Link 5
Dictionaries
Create dictionaries, add and delete from dictionaries, retrieve data from dictionaries, check for presence
of keys and iterate over elements.
Dictionary is an unordered collection of items which has key:value pairs. Dictionary is used to look up for
a specific key and retrieve the corresponding value.
Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any
data type. But the keys must be of immutable data type such as strings, numbers or tuples
In[1] empty{}
In[2] student = {‘name’:’raj’, ‘age’:16, ‘gender’:’male’, ‘class’:10}
In[3] student
{‘name’:’raj’, ‘age’:16, ‘gender’:’male’, ‘class’:10}
Accessing Elements
➢ Syntax : dictionary_name[key]
In[4] print(student[‘name’])
Raj
In[5] print(student[‘class’])
10
If a value is accessed using a wrong key, an error occurs
In[6] print(student[‘height’])
KeyEror : height
This is becoz the interpreter doesnot find the height of the student in the dictionary.
Checking for a key can be done using in. The method in will return True if the key is found in the
dictionary It will return false if key is not present. The presence of keys in dictionaries can only be
checked and not values.
Keys of a dictionary are not ordered. Hence, slicing and striding are not valid o dictionaries.
In[16] student.values()
Out[16] dict_alues([‘male’, 6.2, ‘raj’, 11])
In[17] student.items()
Out[17] dict_itms([‘gender’, ‘male’), (‘height’, ‘6.2’), (‘name’, ‘raj’), (‘class’, 11)])
This returns the list of tuples of keys value pairs of the dictionary student
The order of the list returned by keys, values and items cannot be predicted. In dictionary, they are not in
the order in which we inserted them.
Exercise:Print the keys and values of the dictionary student one by one
Gender male
Height 6.2
Name raj
Class 11
Day 7 Video Link 1
A function is a portion of the code within a larger program that performs a specific task. Functions are
useful in reusing the code and eliminate code redundancy. They are also used to organize our code into
manageable blocks.
In[2] f(2)
Out[2] 4
In[3] f(2.5)
Out[3] 6.25
In[5] greet()
No function arguments
Docsstrings are triple quoted comments entered just after function definition. It implies what the function
does
In[7] avg?
Signature: avg(a, b)
Docstring: avg takes two numbers as input and returns the average
In[8] avg(3,5)
Out[8] 4.0
Exercise Write a function circle which returns the area and perimeter of a circle with given radius r
In[10] a,p=circle(6)
In[11] print(a,p)
113.039999 37.68
Day 7 Video Link 2
Default Arguments
When a function is called without a value for an argument, its default value is used if available, otherwise
it will give an error.
In[5] welcome(“Hello”)
Hello World 23
Exercise Redefine the function welcome, by interchanging its argument. Place the name argument withits
default value of “World” before the greet argument
In[6] def welcome(name=”World”, greet):
Print (greet, name)
SyntaxError: non-default argument follows default argument
Exercise
Redefine the function welcome with a default value of “Hello” to the greet argument. Then call the
function without arguments.
No need to remember the order of arguments while calling functions by passing keyword
arguments. Instead, name of the argument can be used to pass a value to it.
In[14] def marks(*first, second, third): The asterisk restricts the function to accept keyword as argument
print(“first: %d second: %d and third: %d
%(first, second, third))
Arbitrary Arguments
The number of arguments that will be passed in to a function are always not known in advance. Use an
asterisk(*) before an argument name to denote arbitrary number of positional arguments
In[19]: family(“Aishu”, “Akshu”) -Here the function is called with multiple arguments
Aishu Akshu
In[20]: family(“Prathi”, “Aishu”, “Akshu”) Ay number of arguments can be taken
Prathi Aishu Akshu
Built-in functions
What is importing?
Writing Own Python Modules
Understand _ _ name==”_ _main_ _” idiom
Python Modules
Python modules can be written to bundle functions. These functions can be made used by importing to
other scripts.
The above python module has the function to compute gcd of two numbers
if gcd(40, 12) = = 4:
print(“Everything is OK”)
else:
print(“The GCD function is wrong”)
The above code is the test case for gcd. Save the code using gcd_script.py. Open the consle window and
enter the following command
This gcd function ca be used in some other scripts. This is possible since every python function can be
used as a module.
Importing a module
The system locations are searched as below. This indicates that system searches for a python module
when it encounters an import statement. The standard modules are filled in python sys otherwise they are
located in /usr/lib/python3.4/.
Test code should only be executed when python script is run independently. To execute the test code
when the module is imported to other scripts, use _ _name_ _ variable
if gcd(40, 12) = = 4:
print(“Everything is OK”)
else:
print(“The GCD function is wrong”)
Save the above file in text editor and run the file in the console window
Open another terminal and import gcd_script.py. The test code is not executed
The test code is not executed. The _ _ name _ _vriable is local to every script. It is run only when name_
_variable is equal to main
if gcd(40, 12) = = 4:
print(“Everything is OK”)
else:
print(“The GCD function is wrong”)
check_relative_prime(11,3)
In this example gcd_script is imported from gcd_script and is used in the above code without the test code
being executed.
Python Script
In[2] 1/0
ZeroDivisionError: division by zero
Exception Handling
try:
statement1
statement2
except exception name:
exception handling statement(s)
else:
statement(s) when no exception after statement(s)
In the above syntax, first the statements in try are executed. If they do not cause any exception, the except
class is executed if the exception name matches and the execution continues after the try statements. The
code in the else block is executed if the code in the try block does not raise an exception.
In[2] try:
num=int(a)
except ValueError
print(“Wrong input”)
Wrong input
In[4] try:
num=int(b)
except ValueError
print(“Wrong input”)
else:
print(“No exception”)
No exception
In the above code else statement is executed if the try block does not have an exception.
def test():
prod = 1
for i in range(0,10):
prod*=i/(i-5)
print(prod)
In[6]: %debug
>/home/prathibha/example/mymodule.py(4)test()
2 prod=1
3 for i in range(0,10):
4 prod*=i/(i-5)
5 print(prod)
Python shows an error in the line and ipdb appears at the prompt which the ipython debugger mode.
Using this code here, the variables in the previous block can be accessed.
ipdb>i
5
On typing i at the debugger prompt it returns 5 which indicates that an error occurred at i=5.