Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
132 views

Python Notes

Python is a powerful, dynamic programming language used for a wide variety of applications. The IPython interpreter provides an enhanced interactive Python environment with features like tab completion and easier access to help documentation. IPython allows users to easily plot and visualize data, load data from files, and save figures in common file formats. It also enables embellishing plots with labels, titles and other attributes as well as creating subplots and error bars.

Uploaded by

Nageswara Rao
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
132 views

Python Notes

Python is a powerful, dynamic programming language used for a wide variety of applications. The IPython interpreter provides an enhanced interactive Python environment with features like tab completion and easier access to help documentation. IPython allows users to easily plot and visualize data, load data from files, and save figures in common file formats. It also enables embellishing plots with labels, titles and other attributes as well as creating subplots and error bars.

Uploaded by

Nageswara Rao
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

Python Course Journal

Python is a general purpose, high level, remarkably powerful dynamic programming language used in a
wide variety of application domain.
Advantages of Python

• Easy to read and learn


• Free and Open Source
• Useful for Scientific Computing
• Powerful interactive interpreter
• Extensive scientific libraries
• Well documented

Day 1 Video Link

Getting Started with IPython

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

Previous commands in Ipython can be accessed by pressing the UP arrow

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

Correction of typing errors

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 incorrect command can be corrected by pressing Control+C


Day 1 Video Link 2

Using Plot Command Interactively

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

Import Error : No module named matplotlib

In such cases matplotlib must be installed.

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.

The following code gives cosine plot

[1] t=linspace(-pi,pi,100)
[2] cosine=cos(t)
[2] plot(t,cosine)

The cosine plot is as shown below

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)

The following figure window appears

[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.

The following code illustrates saving of the figure in .png format

[1] x=linspace(-3*pi, 3*pi, 100)


[2] plot(x,sin(x))
[3] savefig(‘sine.png’)

The plot can be saved in different formats using savefig such as


➢ .pdf – PDF(Portable Document File)
➢ .ps -- PS(post script)
➢ .eps – Encapsulated Post Script(to be used with LATEX documents)

Day 1 Video Link 5

Multiple Plots

Multiple plots can be named using the legend command

[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)’])

The following plot is obtained


[1] x=linspace(-5,5,100)
[2] plot(x,4*(x*x)
[3] plot(x,(2*x)+3)
[4] legend([r’$y=4(x^2)$’, r’$y=2x+3$’]) – Equations need to be embedded in $ to get in the equation
format
The following plot appears

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

Subplot command takes three arguments


subplot(Number of rows, Vertical number usually taken as 1, serial number of plot)

syntax: subplot(numRows, numCols, plotNum)

The following code gives subplots

[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

Additional Features of IPython

[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)

[3] plot (x,x*sin(x))


[4] xlabel(“$x$”)
[5] ylabel(‘$f(x)$”)
[6] title(“$x and xsin(x)$”)

The labelled plot is as shown below

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

[9] %save plot_script.py 3 4-7

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.

[10] %run -i plot_script.py


[11] show()

The plot can be seen


Day 2 Video Link 3

Loading data from files

Read data from files, which contain data in


➢ Single Column format
➢ Multiple columns separated by spaces or other delimiters

Reading a file primes.txt which contains prime numbers listed in a column

[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, ‘.’)

The required plot is shown as below

[5] delta_L=[0.08,0.09, 0.07, 0.05, 0.06, 0.00, 0.06, 0.06, 0.01]


[6] delta_T=[0.04, 0.08, 0.03, 0.05, 0.03, 003, 0.04, 0.07, 0.08]
[7] errorbar(I, tsquare, xerr=delta_I, yerr=delta_t, fmt=’bo’)

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

Plotting Scatter Plot


In a scatter plot, the data is displayed as a collection of points. Each point determines its position on the x
and y axes. The syntax is scatter(x,y) where x is a sequence of data and y is a sequence of data having
same length as that of x.

[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’)

The following plot is obtained

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

Plot a log-log chart of y=5x3 for x from 1-20

[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

Syntax: pie(values, labels = labels)


Values-the data to be plotted
Labels-the label for each wedge in the pie chart

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)

The following plot is obtained

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

Getting Started with Lists

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 = []

Accessing List using Index

A list can be accessed by the corresponding index


Variable = [item1, item2, item3]
Index 0 1 2
Negative Indices -3 -2 -1

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

Exercise 1 Remove the fourth element from the list doublelist


2 Remove ‘and’ from the list doublelist
In[32] doublelist = [‘a’, [‘b’, ‘c’, ‘d’], ‘and’, 5, 6, 7, 8]
In[33] del doublelist[3]
Out[33] [‘a’,[‘b’, ‘c’, ‘d’], 5, 6, 7, 8]
In[34] doublelist.remove(‘and’)
Out[34] [‘a’,[‘b’, ‘c’, ‘d’], 5, 6, 7, 8]
Day 3 Video Link 3

Using for loop

For<loop variable> in sequence:


<statement 1>
<statement 2>
……
……
<statement n>

For statement iterates over the members of a sequence in order, executing the bock each time

Open the text editor and type the code as shown

Numbers= [4, 9, 16, 25, 36]


For num in Numbers:
Print(“sqrt of”, num, “is”, num**0.5)
Print(“This is outside for loop”)

Save the file as sqrt_num_list.py and run in the console window. The output appears as follows
range() function

Generates a list of integers

Syntax : range([start,] stop[,step]

For example range(1,20,2)-Generates integers from 1 to 19 with step of 2


range(20)-generates integers from 0 to 19

Exercise : Find out the cube of all the numbers from 1 to 10

Type the code in the python interpreter

for i in range(1,11):
print(I,”Cube is”, i**3)

The following output appears


Day 4 Video Link 1

Parsing Data

Split a string using a delimiter


Remove the leading, trailing and all whitespaces in a string
Convert between different built-in datatypes

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[2]: str1 = “Welcome to Aishwarya and Akshaya”


In[3]: str1.split()
Out[3] [‘Welcome’, ‘to’, ‘Aishwarya’, ‘Akshaya’]

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’]

Exercise: Split x using space as argument. Is it same as splitting without an argument?

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’]

The same outputis obtained with spacing or without spacing.

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.

In[8]: str1 = “Welcome to Aishwarya and Akshaya”


In[9]: b = str1.split( )
Out[9]: [Welcome’, ‘to’, ‘Aishwarya’, ‘Akshaya’]
In[10]: c=str1.split(‘ ‘)
Out[10]: [Welcome’, ‘to’, ‘ ‘, ‘ ‘, ‘Aishwarya’, ‘Akshaya’]

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[11]: unstripped = “ Hello World “


In[12]: unstripped.strip( )
Out[12]: ‘Hello World

Converting strings in to floats and integers

In[13]: mark_str = “1.25”


In[14]: mark = flaot(mark_str)
In[15]: type(mark_str)
Out[15]:String
In[16]: type(mark)
Out[16]:float

Mathematical operations can also be done

Exercise What happens if int(“1.25”) in the terminal?

In[17] int(“1.25”)
ValueError: Invalid literal for int() with base 10: ‘1.25’

An string cannot be converted into integer directly.

In[18]: dcml_str = “1.25”


In[19] flt = float(dcml_str)
In[20]: flt
Out[21] 1.25

In[21]: number = int(flt)


In[22]: number
Out[22]: 1

Using data file to pass the data


Day 4 Video Link 2

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.

prathibh@prathibha:~$ sudo apt-get install python3-pip


prathibh@prathibha:~$ sudo pip3 install numpy==1.13.3

Installation of Numpy package is done successfully

loadtxt( )

To get the data as an array, use the loadtxt( ) function. For loadtxt ( ) function, import numpy library first

[1] import numpy as np


[2] L=np.loadtxt(“student_record_txt”, usecols=(3,4,5,6,7), delimiter=’;’)
In[3] L
Out[3]:
Array([[53., 36., 28., 16., 44.,],
[58., 37., 35., 23., 43.,],
[53., 36., 28., 16., 44.,],
[58., 37., 35., 23., 43.,],
…….
. …….
[58., 37., 35., 23., 43.,],
[58., 37., 35., 23., 43.,],
In[4] L.shape
Out[4]: (185667, 5)
Day 6 Video Link 1

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

Write a program to print the squares of all the odd numbers

[1] i=1
[2] while i<10:
print(i*i)
i+=2
The output is obtained as
1
9
25
49
81

The same program in for loop

[3] for n in range(1,10,2)


print(n*n)

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

[6] for n in range(2,10,2):


print(n*n)
The square of the numbers are printed.

The pass in the for loop does not allow to print any statements
[7] for n in range(2,10,2):
pass

The use of break statement is as shown in the following code

[8] for letter in ‘python’:


if letter = = ‘h’:
Break
Print(‘Current Letter :’, letter)

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

[9] for n in range(1,10,2):


If n % 3 ==0:
continue
print (n*n)
The output is as shown below
1
25
49
Day 6 Video Link 2

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.

[1] primes = [2, 3, 7, 11, 13, 17, 19, 23, 29]


[2] primes[4:8]
Out[2] 11, 13, 17, 19]

Write a program to obtain the prime numbers below 10

In [3] primes[0:4]
Out[3] [2, 3, 5, 7]

Use of step value in slicing

Write a program to find all the odd numbers below 10 from the given numbers

In [4] num = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]


In [5] num[1:10:2]
Out[5] [1, 3, 5, 7, 9]
In [6] num[:10] --- If the start element is not specified, the first element is taken as starting
Out[6] [0,1,2,3,4,5,6,7,8,9] –Returns all the numbers below 10.
In[7] num[10:] --Returns the elements starting from 10 upto last if no element is specified
Out[7] [10, 11, 12, 13]
In[8] num[::2]
Out[8] [0, 2, 4, 6, 8, 10, 12]

Start and End values can also be negative.

Obtain all the multiples of 3 from the list num

In[9] num[::3]
Out[9] [0, 3, 6, 9, 12]

Sorting numbers in a list

In python sorting of numbers is done.

In[10] a=[ 5, 1, 6, 7, 7, 10]


In [11] a.sort()
In[12] a
Out[12] [1,5, 6, 7, 7, 10]

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]

Python also provides the reverse of the list

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

Slice a string and get substrings out of them


Reverse a String
Replace characters in a string
Convert a string to upper case or lower case

String slicing

String slicing allows to obtain substrings

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

In[3] week_name = [“sun”, “mon”, “tue”, “thu”, “fri”, “sat”]


In[4] s = “Saturday” – Need to check whether the first three characters exist in the list week_name
In [5] s[0:3]
Out[5] ’sat’
In[6] s[0:3] in week_name – checking whether the substring is present in week_name
Out[6] True

Obtain the substring excluding the last characters from the string s=”Saturday”

In [7] s[1:-1]
Out[7] ‘aturda’

Reversing a String

Checking whether the given string is a palindrome or not

In[8] s1=’liril’
In[9] s1==s1[::-1]
Out[9] True - Indicates that the given string is Palandrome

Convert a string to upper case or lower case

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

In[11] s2.lower() = = s2.lower()[::-1]


Out[11] True

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)

The output is as follows

SATURDAY True
python FALSE
Sunday True

Replacing a string

In[15] email= “info[at]fossee[dot]in


In[16] email_at =email.replace(“[at]”, “@”)
print(email_at)
The output info@fossee[dot]in is printed

In[17] email_proper = email_at.replace(“[dot]”,”.”)


Print(email_proper)
The output infor@fossee.in is printed

In[18] email_list = [prathibhamails@gmail.com, chalam.goriparthi@gmail.com,


aishwarya5408@gmail.com]
In[19] email_str=”,”.join(email_list)
In[20] print(email_str)

The different Emails are combined in to one string and output is obtained as follows

prathibhamails@gmail.com, chalam.goriparthi@gmail.com, aishwarya5408@gmail.com

Change the separator to semicolon from comma in the email_str

[21] email_str = email_str.replace(“.”,”;”)


print(email_str)

The output of different Emails separated bby semicolon is printed as below

prathibhamails@gmail.com; chalam.goriparthi@gmail.com; aishwarya5408@gmail.com


Day 6 Video Link 4

Getting started with Tuples

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[1] t= (1, 2.5, “hello”, -4, “world”, 1.24, 5)


In[2] t
Out[2] (1, 2.5, ‘hello’, -4, ‘world’, 1.24, 5)

In[3] t[3]
Out[3] -4

In[4] t[1:5:2]
Out[4] (2.5, -4)

In[5] t[2]=”hello”

TypeError: ‘tuple object does nt support item assignment

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)

This prints each element of the tuple as follows

1
2.5
Hello
-4
World
1.24
5

Exercise : Given a =5 and b=7, swap the values of a and b

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

The values of a and b are swapped.

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

The value of a dictionary ace be accessed using a corresponding key

➢ 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.

Add or Delete an Element in the Dictionary.

Adding a element to the Dicitonary

In[7] student[‘height’] = 6.2


In[8] student
{‘name’:’raj’, ‘age’:16, ‘gender’:’male’, ‘height’=6.2, ‘class’:10}
The element height is added to the dictionary

The value of the elements in the dictionary can also be changed

In[9] student[‘class’] = ‘11’


In[10] student
{‘name’:’raj’, ‘age’:16, ‘gender’:’male’, ‘height’= 6.2, ‘class’:11}
Deleting an element in the dictionary

In[11] del student[‘age’]


In[12] student
{‘name’:’raj’, ‘gender’:’male’, ‘class’:10}

Checking whether a key is preset 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[12] student={‘name’:’raj’, ‘age’:16, ‘gender’:’male’, ‘height’= 6.2, ‘class’:11}


In[13] ‘school’ in student
Out[13] False

In[14] ‘name’ in student


Out[14] True

Retrieve Keys ad Values

Keys() is used for getting a list of the keys


Values() is used for getting a list of values
In[15] student.keys()
Out[15] dict_keys([‘gender’, ‘height’, ‘name’, ‘class’])

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

Student=’name’:’raj’, ‘age’:16, ‘gender’:’male’, ‘class’:11

In[18] for key, val in student.items():


Print (key, val)

Gender male
Height 6.2
Name raj
Class 11
Day 7 Video Link 1

Getting Started with Functions

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.

➢ Syntax def function_name(parameters):


“”docstring””
statement(s)
return[expression]

Writing a function for mathematical function f(x) = x2

In[1] def f(x) :


return x*x

In[2] f(2)
Out[2] 4

In[3] f(2.5)
Out[3] 6.25

Function without arguments

In[4] def greet():


Print(“No function arguments”)

In[5] greet()
No function arguments

Commenting in the Code

Documenting/commenting code is good practice.

Docsstrings are triple quoted comments entered just after function definition. It implies what the function
does

In[6] def avg(a,b):


“””avg takes two numbers as input and returns the average”””
Return(a+b)/2.0

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[9] def circle( r):


“””returs area and perimeter of a circle, given radius r”””
Pi=3.14
area = pi * r * r
perimeter = 2 * pi * r
return area, perimeter

In[10] a,p=circle(6)
In[11] print(a,p)
113.039999 37.68
Day 7 Video Link 2

Additional Features of Functions

Assign default values to arguments, when defining functions


Define and call functions with keyword arguments
Define and call functions with arbitrary arguments
Learn some of the built in functions available in Python standard library

Default Arguments

Function arguments can have default values in Python

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[1] def welcome(greet, name=”World”);


print (greet, name)

In[2] welcome(“Hi, “Aishu”)


Hi Aishu
The expected welcome message is displayed

Function with one Argument

In[3] welcome(“Hello”) – Here one parameter “Hello” is passed as a default argument


Hello World

In[4]: def welcome(greet, age=23, name=”World”):


print(greet, name, age)

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.

In[7]: def welcome(greet=”Hello”, name=”World”);


Print(greet, name)

In[8]: welcome() Without passing any arguments


Hello World
Keyword 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[9]: def marks(first, second, third):


print(“first: %d second: %d and third: %d
%(first, second, third))
In[10] marks(34, 23, 45)
First: 34 second: 23 and third:45

In[11] marks(34, 23, third=45)


First: 34 second: 23 and third: 45

In[12] marks(34, second=23, 45)


syntaxError: non-keyword arg after keyword arg –The keywords should be specified at the end.

In[13] marks(second=34, first=32, third=45) – Keywords can be passed in any order


first: 23 second: 34 and third: 45

Learn to define a function to take only key word arguments

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))

In[15] marks(second=34, first=23, third=45)


first: 23 second: 34 and third:45

Calling function without keyword arguments

In[16] : def marks(first, second, third):


print(“first: %d second: %d and third: %d
%(first, second, third))
In[17]: marks(45, 34, 23)
TypeError: marks() takes 0 positional arguments but 3 were given

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[18]: def family(*names):


print(names)

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

Defining a function that receives arbitrary number of arguments

In[21]: def person(**attributes): ** Allows to pass zero or more arguments


print(attributes)

In[22]: person(name=”John”, ‘age’=34, ‘height’=182)


{‘name’:’John’, ‘age’:34, ‘height’: 182}

In[22]: person(name=”John”, ‘age’=34, ‘height’=182, ‘gender’=male)


{‘name’:’John’, ‘age’:34, ‘height’: 182, ‘gender’=male}

The function prints a dictionary of keyword arguments with values.

Built-in functions

Python also provides built in functions, some are


➢ abs( )
➢ any( )
➢ dir( )
➢ help( )

Day 7 Video Link 4

Writing Python Scripts

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.

Open a text editor and type the following code

def gcd(a, b):


while b:
a,b = b, a%b
return a

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

In[1]: %run gcd_script.py


Everything is OK

It means the test case if gcd(40, 12) = = 4: is true

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

In[2]: import sys


In[3]: sys.path

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/.

The module present in the current directory can be imported using

In[4]: import gcd_script


Everything is OK

The above output is obtained if the module is in the current directory.

In[5]: print(“gcd of 187and 391 is”, gcd_script.gcd(187, 391))


Gcd of 187 and 391 is 17

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

def gcd(a, b):


while b:
a,b = b, a%b
return a

if _ _ name _ _ = = “_ _main_ _”:

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

In[6]: %run gcd_script.py


Everything is OK
In[7]: import gcd_script
In[8] exit

Open another terminal and import gcd_script.py. The test code is not executed

In[1]: import gcd_script

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 _ _ name _ _ = = “_ _main_ _”:

if gcd(40, 12) = = 4:
print(“Everything is OK”)
else:
print(“The GCD function is wrong”)

The above code is executed only when it is run as python script.

In[2]: from gcd_script import gcd


def check relative prime(a,b):
if gcd(a,b) = =1:
pint(“Yes, %d and %d are relatively prime”,%(a,b))
else:
print(“No, %d and %d are not relatively prime” %(a,b))

check_relative_prime(11,3)

Yes, 11 and 3 are relatively rpime

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

Every python file can be run in two ways:


➢ As an independent stand-alone script or
➢ As a python module which can be imported by other scripts or module
Day 7 Video Link 7

Handling Errors and Exception

Errors and Exceptions

In python there are two kinds or errors


➢ Syntax errors-Occurred due to incorrect usages and these are detected by parser
Example if True print(“done”)-Syntax error occurs since colon is missing after True
➢ Exceptions—Error that occurs during program execution. Python generates an exception that can
➢ Be handled, which avoids the program to crash
Example 1/0-Results in ZeroDivision Error exception

In[1]: if True print(“done”)


SyntaxError: invalid syntax

In[2] 1/0
ZeroDivisionError: division by zero

Python throws an exception that it is not possible to divide by zero

Exception is a special case of error reported by the programming language

In[3]: a =input(“Enter an integer:”)


Enter an integer:ac

In[4]: num = int(a)


ValueError: invalid literal for int( ) with base 10: ac

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.

The following code illustrates exception handling

In[1]: a =input(“Enter an integer:”)


Enter an integer:ac

In[2] try:
num=int(a)
except ValueError
print(“Wrong input”)
Wrong input

In[3]: b= input(“Enter an integer:”)


Enter an integer:23

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.

Open the text editor and type the following code

def test():
prod = 1
for i in range(0,10):
prod*=i/(i-5)
print(prod)

Run this code in IPython

In[5]: from mymodule import test


test( )

ZeroDivisionError: division by zero

To find the error type %debug

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.

You might also like