PythonTutorial MCSC 202
PythonTutorial MCSC 202
————————————————————————————————————
1 General Information
• The creator of Python is Guido Van Rossum.
• The name Python is derived from the British television series, Monty Python’s
Flying Circus. About the origin of Python, Van Rossum wrote in 1996:
Over six years ago, in December 1989, I was looking for a hobby program-
ming project that would keep me occupied during the week around Christ-
mas. My office ... would be closed, but I had a home computer, and not
much else on my hands. I decided to write an interpreter for the new script-
ing language I had been thinking about lately: a descendant of ABC that
would appeal to Unix/C hackers. I chose Python as a working title for the
project, being in a slightly irreverent mood (and a big fan of Monty Pythons
Flying Circus - a BBC TV show).
https://www.python.org/downloads/
https://www.continuum.io/downloads
a free python configuration which already contains all the packages needed.
• Python programs are not compiled into machine code, but are run by an
interpreter. The Python interpretor can be downloaded from
http://www.python.org/getit
It normally comes with a nice code editor called Idle (Integrated develop-
ment and learning environment) that allows you to run programs directly
from the machine. In a Linux distribution machine, it is very likely that
Python is already installed.
• Third most popular FOSS programming language than java and C++.
• Long list of applications. Popular for scientific use specially for numeric.
2
Introduction to Python Dr. Dil Gurung, Kathmandu University
• Python is available for all major operating systems (Linux, Unix, Win-
dows, MacOS, and so on). A program written on one system runs without
modification on all systems.
• Python is easier to learn and produces more readable code than most lan-
guage.
Disadvantages
3
Introduction to Python Dr. Dil Gurung, Kathmandu University
4
Introduction to Python Dr. Dil Gurung, Kathmandu University
Operator Description
== Assignment - If the values of two operands are equal,
then the condition becomes true.
!= Not equal to - If values of two operands are not equal,
then condition becomes true.
<> Not equal to - If values of two operands are not equal,
then condition becomes true.
> Greater than - If the value of left operand is greater than
the value of right operand, then condition becomes true.
< Less than - If the value of left operand is less than
the value of right operand, then condition becomes true.
>= Greater and equal to - If the value of left operand is greater than
or equal to the value of right operand, then condition becomes true.
<= Less and equal to - If the value of left operand is less than
or equal to the value of right operand, then condition becomes true.
>>> sqrt(2)
1.4142135623730951
>>> sqrt(2) == 1.4142135623730
False
>>> sqrt(2) == 1.41421356237309
False
>>> sqrt(2) == 1.414213562373095
False
>>> sqrt(2) == 1.4142135623730951
True
print(a)
—————————-
a = 0
for i in range(5):
a -= 2
print(a),
print(a)
The assignment operators are described as given below:
5
Introduction to Python Dr. Dil Gurung, Kathmandu University
>>> a = 3 # Integer
>>> b = 2.5 # Floating point
>>> c = ’3’ # String
>>> print(a > b)
True
>>> print(a == c)
False
>>> print( (a > b) and (a != c) )
True
>>> print( (a > b) or (a == b) )
True
6
Introduction to Python Dr. Dil Gurung, Kathmandu University
>>> 12 not in a
True
All the operators except ** are left associate, that means that the application
of the operators starts from left to right.
1 + 2 + 3*4 + 5
↓
3 + 3*4 + 5
↓ + 5
3 + 12 + 5
↓
15 + 5
↓
20
7
Introduction to Python Dr. Dil Gurung, Kathmandu University
EXERCISES – 1
1. Open a Python shell, enter the following expressions, and observe the re-
sults:
4. For x = 3 + 2j, Enter the following expression and observe the results:
6. The distance traveled by a ball falling in the air is given by the equation
x = x0 + v0 t + 0.5at2 . Use Python to calculate the position of the ball at
time t = 5 second if x0 = 10 m, v0 = 15 m/s, and a = −9.81 m/s2 .
8
Introduction to Python Dr. Dil Gurung, Kathmandu University
EXERCISES – 2
1. Calculate the following, and give your answers to three significant figures
(unless otherwise stated or appropriate) in Exercise 1 to 3.
(a) Basic calculations
i. Calculate 7 ÷ 2
ii. Calculate the remainder of 7 ÷ 4
iii. Calculate 1 ÷ 3. Count the number of decimal decimal places in
the answer.
iv. Test if a third (1./3) is equal to 0.333 using the == syntax. How
many 3s do you need before the answer is True?
v. Test if 0.5 is equal to 0.4999999999999999999999. Why do you
think you get this answer? Try putting less 9s until it becomes
False.
(b) Powers, Roots, Exponentials and Logs Define the variables x =
45, y = 57.2 and n = 7.2, then calculate:
9
Introduction to Python Dr. Dil Gurung, Kathmandu University
2 Core python
The standard data types in Python are
2.1 Variables
A variable represents a value of a given type stored in a fixed memory location.
The value may be changed, but not the type.
The pound sign (#) denotes the beginning of a comment - all characters between
# and the end of the line are ignored by the interpreter.
Following Reserved words can not be used as variable names because they are
used to build - up Python language.
and, as, assert, break, class, continue, def, del, elif, else, except,
False, finally, for, from, global, if, import, in, is, lambda, None,
nonlocal, not, or, pass, raise, return, True, try, with, while, and yield.
2.2 Strings
A string is a sequence of characters enclosed in single or double quotes. Strings
are concatenated with the plus (+) operator, whereas slicing (:) is used to extract
a portion of the string.
2.3 Lists
A list is similar to a tuple, but it is mutable, so that its elements and length can
be changed. A list is identified by enclosing it in brackets.
Example 1:
10
Introduction to Python Dr. Dil Gurung, Kathmandu University
2.4 Tuples
A tuple is a sequence of arbitrary objects separated by commas and enclosed in
parentheses. If the tuple contains a single object, a final comma is required. For
example
>>> a = (45, ) # with the trailing commas is a tuple,
which contains 45 as is only member
>>> print(a)
11
Introduction to Python Dr. Dil Gurung, Kathmandu University
(45,)
Tuples support the same operations as strings; they are also immutable. Here is
an example where the tuple rec contains another tuple (20, 12, 2005).
Any list operation that changes the list will not work for tuples:
Some list methods, like index , are not available for tuples. So why do we need
tuples when lists can do more than tuples?
• Tuples are frequently used in Python software that you certainly will make
use of, so you need to know this data type.
12
Introduction to Python Dr. Dil Gurung, Kathmandu University
Operation Description
a+b concatenation
a ∗ n, n ∗ a make a n copies, n ∈ Z
a [i] indexing
a[i : j] slicing
a[i : j:stride] Extended slicing
x in a, x not in a membership
for x in a: iteration
all(a) return TRUE if all items in a are true
any(a) return TRUE if any term in a is true
len(a) length
min(a) minimum item in a
max(a) maximum item in a
13
Introduction to Python Dr. Dil Gurung, Kathmandu University
EXERCISES – 3
1. Type set the following in your IDE window and run it to understand the
execution.
>>> a = [4,3,0,1,6,8,2,9,0,4,10,1]
Execute the result type setting the following in IDE shell and observe the
result
(a) Indexing
>>> a[0]
4
>>> a[-1]
1
>>> a[3]
1
>>> a[-3]
4
(b) Slicing
>>> a[0:-1] # Strips the last element from the list
[4, 3, 0, 1, 6, 8, 2, 9, 0, 4, 10]
>>> a[:4] # Strips the element from index 4 to last index
[4, 3, 0, 1]
>>> a[4:] # Strips the element from index 0 to 3
[6, 8, 2, 9, 0, 4, 10, 1]
>>> a[:] # Executes the same list a
[4, 3, 0, 1, 6, 8, 2, 9, 0, 4, 10, 1]
>>> a[3:6] # Executes the elements from index 3 to index 5
[1, 6, 8]
(c) Extended slicing
14
Introduction to Python Dr. Dil Gurung, Kathmandu University
>>> a[::2]
[4, 0, 6, 2, 0, 10]
>>> a[::-2]
[1, 4, 9, 8, 1, 3]
>>> a[0:5:2]
[4, 0, 6]
>>> a[5:0:-2]
[8, 1, 3]
>>> a[:5:1]
[4, 3, 0, 1, 6]
>>> a[:5:-1]
[1, 10, 4, 0, 9, 2]
>>> a[5::1]
[8, 2, 9, 0, 4, 10, 1]
>>> a[5::-1]
[8, 6, 1, 0, 3, 4]
>>> a[5:0:-1]
[8, 6, 1, 0, 3]
>>> a[1::3]
[3, 6, 9, 10]
(d) functions
Perform the following for list.
>>> a = [4,3,0,1,6,8,2,9,0,4,10,1]
15
Introduction to Python Dr. Dil Gurung, Kathmandu University
3 Functions
A function is a collection of statements that can be executed wherever and when-
ever we want in the program. In a compute language like Python, the term
function means more than just a mathematical function. Three types of func-
tions are in use:
1. built-in functions
3. lambda functions
range(start, stop)
16
Introduction to Python Dr. Dil Gurung, Kathmandu University
where
start: Starting number of the sequence.
stop: Generate numbers up to, but not including this number.
Note that all parameters must be integer. The following example illustrate the
use of range().
>>> range(5)
[0, 1, 2, 3, 4]
>>> range(1,10)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
print(obj1, obj2, · · · )
that converts obj1, obj2, · · · to strings and prints them on the same line, sepa-
rated by spaces. The new line character 0 \n0 can be used to force a new line.
format method
The form of the format method is
0
{: f m1}{: f m2} · · ·0 .f ormat(arg1, arg2, · · · )
where f m1, f m2, · · · are the format specification for arg1, arg2, · · · , respectively.
Typically used format specifications are
wd Integer
w .de f Floating point notation
w .de d Exponential notation
where w is the width of the field and de is the number of digits after the decimal
point.
The following example illustrate the use of print function with the format
method.
17
Introduction to Python Dr. Dil Gurung, Kathmandu University
18
Introduction to Python Dr. Dil Gurung, Kathmandu University
Example 2 Here is a complete sample program that aims to illustrate the rule
above:
def myfun(n):
sum = n + 1
print sum # sum is a local variable
return sum
1. x = 1 # global variables
def f():
return x # find a global variable with name x
print x
print f()
The out put is
>>> runfile(’/home/dgurung/.spyder2/.temp.py’,
wdir=r’/home/dgurung/.spyder2’)
1
1
x = 1 # global varialbe
def f():
x = 2 # local variable
return x # Python preference variable defined locally
print x
print f()
print x
19
Introduction to Python Dr. Dil Gurung, Kathmandu University
>>> runfile(’/home/dgurung/.spyder2/.temp.py’,
wdir=r’/home/dgurung/.spyder2’)
1
2
1
20
Introduction to Python Dr. Dil Gurung, Kathmandu University
4 Modules
A module is a file containing Python definitions and statements. The file name
is the module with the extension .py appended.
Modules are to import. For examples – numpy, scipy, matplotlib, math etc.
are modules. To list the modules, enter the expression
>>> help()
at the shell prompt. Follow the instructions to browse the modules or directly
type
>>> help(’modules’)
>>> help(’numpy’)
import math
and then access individual functions in the module with the module name
as prefix as in
x = math.sqrt(2)
import math as m
and then access individual functions in the module with the module name
as prefix as in
x = m.sqrt(2)
21
Introduction to Python Dr. Dil Gurung, Kathmandu University
Now we can work with sqrt directly, without the math. prefix. For example
x = sqrt(2)
>>> help(’math’)
dir(module)
>>> dir(math)
[’__doc__’, ’__name__’, ’__package__’, ’acos’, ’acosh’,
’asin’, ’asinh’, ’atan’, ’atan2’, ’atanh’, ’ceil’,
’copysign’, ’cos’, ’cosh’, ’degrees’, ’e’, ’erf’, ’erfc’,
’exp’, ’expm1’, ’fabs’, ’factorial’, ’floor’, ’fmod’,
’frexp’, ’fsum’, ’gamma’, ’hypot’, ’isinf’, ’isnan’,
’ldexp’, ’lgamma’, ’log’, ’log10’, ’log1p’, ’modf’,
’pi’, ’pow’, ’radians’, ’sin’, ’sinh’, ’sqrt’, ’tan’,
’tanh’, ’trunc’]
You can get a short explanation of each function by typing, for instance,
>>> help(math.sqrt)
Help on built-in function sqrt in module math:
sqrt(...)
sqrt(x)
22
Introduction to Python Dr. Dil Gurung, Kathmandu University
23
Introduction to Python Dr. Dil Gurung, Kathmandu University
[1 2 3 4]
>>> a = np.array([1,2,3,4],float)
>>> print a
[ 1. 2. 3. 4.]
>>> b = np.array( [ [1,2],[3,4] ] )
>>> print b
[[1 2]
[3 4]]
>>> b = np.array( [ [1,2],[3,4] ], float )
>>> print b
[[ 1. 2.]
[ 3. 4.]]
which creates a dim1 × dim2 array and fills it with zeros, and
which fills the array with ones. The default type in both cases is float.
There is a function
arange(f rom, to, increment)
which works just like range function, but returns an array rather than a sequence.
24
Introduction to Python Dr. Dil Gurung, Kathmandu University
>>> print a
[[0 0 0]
[0 0 0]
[0 0 0]]
>>> a[0] = [1,2,3] # change a row
>>> a[1,1] = 5 # change an element
>>> a[2, 0:2] = [11,22] # change part of a row
>>> print a
[[ 1 2 3]
[ 0 5 0]
[11 22 0]]
25
Introduction to Python Dr. Dil Gurung, Kathmandu University
import numpy as np
a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
index = [2, 3, 6]
26
Introduction to Python Dr. Dil Gurung, Kathmandu University
x = arange(-2*pi,2*pi,pi/20)
27
Introduction to Python Dr. Dil Gurung, Kathmandu University
The line and marker style are specified by the string characters. Some are
shown in the following table:
Some of the location (loc) codes for placement of the legend are
Number 0 1 2 3 4
Location Best location Upper right Upper left Lower left Lower right
4.3.1 Subplot
The command subplot can be applied to partition the screen so that several small
plots can be placed in one figure.
Syntax:
subplot(m,n,p)
This command divides the current figure into m × n equal sized regions, arranged
in m rows and n columns, and create a set if axes at position p to receive all
plotting commands. The subplots are numbered from left to right end from top
to bottom. For example, the command subplot(2,2,4) would divide the current
figure into four regions arranged in two rows and two columns, and create an axis
in position 4 (the lower left one) to accept new plot data. The following example
will display the use of subplot.
28
Introduction to Python Dr. Dil Gurung, Kathmandu University
x = arange(-2*pi,2*pi,pi/20)
plt.figure()
plt.subplot(2,2,1)
plt.plot(x,sin(x),’o-’,c = ’r’)
plt.xlabel(’x’,fontsize = 16.0, fontweight = ’bold’)
plt.ylabel(’sinx’,fontsize = 16.0, fontweight = ’bold’)
plt.title(’Sine Graph’)
plt.subplot(2,2,4)
plt.plot(x,cos(x),’^-’,lw = 3.0)
plt.xlabel(’x’,fontsize = 16.0, fontweight = ’bold’)
plt.ylabel(’cosx’, fontsize = 16.0, fontweight = ’bold’)
plt.title(’Cosine Graph’)
29
Introduction to Python Dr. Dil Gurung, Kathmandu University
n = 256
x = np.linspace(-3, 3, n)
y = np.linspace(-3, 3, n)
X, Y = np.meshgrid(x, y)
fig = plt.figure()
ax = Axes3D(fig)
X = np.arange(-4, 4, 0.25)
Y = np.arange(-4, 4, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
30
Introduction to Python Dr. Dil Gurung, Kathmandu University
4.3.4 Quiver
Here is the python code for vector field of vector function
F~ = −x~i + y ~j
x = np.linspace(-5,5,10)
y = np.linspace(-3,3,10)
x,y = np.meshgrid(x,y) # returns a meshgrid
plt.quiver(x,y, -x, y) # First two entries give the mesh
# Second two entries define the vector field
plt.xlabel(’$x$’)
plt.ylabel(’$y$’)
plt.show()
31
Introduction to Python Dr. Dil Gurung, Kathmandu University
EXERCISES - 4
(a) Write a python code to plot the line graph of f using 200 points.
(b) Use the color red, marker * , and line width to 2.0
(c) Use the t-axis limit 0 ≤ t ≤ 0.2 and f -axis limit −2.0 ≤ f (t) ≤ 2.0.
(d) Use the x-label, y-label and title with fontsize 16.0 and fontweight
bold.
4. Create a plot of the functions f (x) = e−x/10 sin π x and g(x) = x e−x/3
over the interval [0,10]. Include labels for the x- and y-axes, and a legend
explaining which line is which plot. Save the plot as a .jpg file
2 cos t
5. Let f : [0, T ] → R defined by f (t) = describes a trajectory of a
sin t
circle center at origin.
32
Introduction to Python Dr. Dil Gurung, Kathmandu University
(a) Write a python code to plot the trajectory of γ with 500 points.
(b) Use color green to make the trajectory.
(c) Set the line width to 5.
When r0 = 1, this curve is called Cardioid. Use this definition to plot the
shape of a Limacon for r0 = 0.8, 1.0 and 1.2. Be sure to use enough points
that the curve is closed and appears smooth. Use a legend in center of the
graph to identity which curve is which. Save the plot as a .pdf.
33
Introduction to Python Dr. Dil Gurung, Kathmandu University
5 Conditionals
5.1 The if construct
The if construct has the form
if condition:
block -1 statement
elif condition:
block - 2 statement
elif condition:
block - 3 statement
.... ....
else:
block - n statement
can be used to define the block of statements that are to be executed preferring
condition to be true from top.
34
Introduction to Python Dr. Dil Gurung, Kathmandu University
while condition:
block statement
else:
block statement
can be used to define the block of statements that are to be executed preferring
condition to be true from top.
i = 0
while i < 5:
print i
i += 1
print("while loop done!")
0
1
2
3
4
while loop done!
Solution: The while construct for Python program for factorial is:
35
Introduction to Python Dr. Dil Gurung, Kathmandu University
can be used to define the block of statements that are to be executed in a given
number of times.
for i in range(0,5):
print i
print("for loop done! ")
0
1
2
3
4
for loop done!
36
Introduction to Python Dr. Dil Gurung, Kathmandu University
else:
factr = 1
for k in range(1,n+1):
factr = factr*k
break
for i in range(1,10):
if i == 5:
break
print("i = %d\n" %i)
print("End of Loop!")
for i in range(1,6):
if i == 3:
continue
print("i = %d\n" %i)
print("End of Loop!")
37
Introduction to Python Dr. Dil Gurung, Kathmandu University
i = 1
i = 2
i = 4
i = 5
End of Loop!
Example 11 The following example compiles a list of all numbers between 1 and
99 that are divisible by 9.
print(x)
[9, 18, 27, 36, 45, 54, 63, 72, 81, 90, 99]
Example 12 The following example compiles a list of all first n odd numbers,
and their sum.
38
Introduction to Python Dr. Dil Gurung, Kathmandu University
EXERCISES – 5
8. Define a function
−x + 1,
x≤0
f (x) = x sin(x) + 1, x ∈ [0, 3 π]
−(x − 3 π) + 1, otherwise
Write a python code to plot the graph of this function on the interval
[−5, 20].
39