0% found this document useful (0 votes)
99 views

PythonTutorial MCSC 202

Guido Van Rossum created Python in the late 1980s. Python is an object-oriented, scripting language that is free, open-source, and runs on many platforms. It is commonly used for scientific computing due to its extensive math and scientific libraries. Python code is interpreted at runtime rather than compiled, making development faster than lower-level languages like C/C++.

Uploaded by

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

PythonTutorial MCSC 202

Guido Van Rossum created Python in the late 1980s. Python is an object-oriented, scripting language that is free, open-source, and runs on many platforms. It is commonly used for scientific computing due to its extensive math and scientific libraries. Python code is interpreted at runtime rather than compiled, making development faster than lower-level languages like C/C++.

Uploaded by

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

Introduction to Python

————————————————————————————————————

1 General Information
• The creator of Python is Guido Van Rossum.

• Python is an object-oriented language that was developed in the late 1980s


as a scripting language, and its implementation was started in December
1989 by Guido Van Rossum worked in a project at the CWI, called Amoeba,
a distributed operating system, in Netherland.

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

• Python programs can be developed in much shorter time than equivalent


Fortran or C programs.

• Python may be viewed as an emerging language, because it is still being


developed and refined. In its current state, it is an excellent language for
developing engineering problems.

• The installation is trivial - just download Python (current version 3.5.0)


from the official web page:
0
A good book intend for Python programmer is: A Primer on Scientific Programming with
Python by Hans Peter Langtangen, Springer Verlag, 2014.
Introduction to Python Dr. Dil Gurung, Kathmandu University

https://www.python.org/downloads/

You can install anaconda

https://www.continuum.io/downloads

a free python configuration which already contains all the packages needed.

numpy, scipy, matplotlib, ipython, notebook

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

1.1 Why Python ?


• It is a Free Open Source Software (FOSS). MATLAB is not FOSS.

• Third most popular FOSS programming language than java and C++.

Figure 1: Python logo

• Much faster to write working python code.

• Cross plate form language.

• Long list of applications. Popular for scientific use specially for numeric.

1.2 Release date for the major and minor versions


• Python 1.0: January 1994

– Python 1.5 - December 31, 1997


– Python 1.6 - September 5, 2000

• Python 2.0: October 16, 2000

2
Introduction to Python Dr. Dil Gurung, Kathmandu University

– Python 2.1 - April 17, 2001


– Python 2.2 - December 21, 2001
– Python 2.3 - July 29, 2003
– Python 2.4 - November 30, 2004
– Python 2.5 - September 19, 2006
– Python 2.6 - October 1, 2008
– Python 2.7 - July 3, 2010

• Python 3.0: December 3, 2008

– Python 3.1 - June 27, 2009


– Python 3.2 - February 20, 2011
– Python 3.3 - September 29, 2012
– Python 3.4 - March 16, 2014
– Python 3.5 - September 13, 2015
– Python 3.6 - December 23, 2016

1.3 Advantages and Disadvantages


Advantages

• Python is an open-source software, which means that it is free.

• It is included in most Linux distributions.

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

• Python and its extensions are easy to install.

Disadvantages

• Selection of an IDE (Integrated Development Environment). An IDE is


a software application that provides comprehensive facilities to computer
programmers for software development.
Some IDEs are – Anjuta (Naba Kumar), IDLE (Guido Van Rossum et al.
- Cross platform. This IDE is a built-in installation in Python), Pycharm
(Jet Brains), Spyder (Carlos Cordoba - Cross platform), Thonny (Aivar
Annamaa), Wing (Wingware) etc.

• It is not as easy to implement as commercial software MATLAB.

3
Introduction to Python Dr. Dil Gurung, Kathmandu University

1.4 Python basic operators


1.4.1 Arithmetic operators
Operator Description Example
+ Addition >>> 2+3
5
− Subtraction >>> 2-3
-1
∗ Multiplication >>> 2*3
6
∗∗ Exponentiation >>> 2**3
8
pow(x, y) Exponentiation >>> pow(2,3)
8
/ Division >>> 8/2
4
// Floor Division >>> 9//5
1
% Modulus >>> 9 % 5
4
>>> s = ’Hello ’ # A string variable
>>> t = ’World’ # A string variable
>>> print(3*s) # Repetition
Hello Hello Hello
>>> print(s + ’ ’ + t) # Concatenation
Hello World
>>> print(s + [1, 2]) # Append elements
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot concatenate ’str’ and ’list’ objects
>>> print(s + ’Suvesh’) # Append elements
Hello Suvesh
>>> a = [1,2,3,4] # List
>>> b = [5,6,7] # List
>>> print(a + b) # Concatenation of list
[1, 2, 3, 4, 5, 6, 7]
>>> print(a + ’b’) # Concatenation of list and string
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "str") to list
>>> s = "Hello" # String
>>> u = (1,2,3,4) # tuple
>>> print(s + u)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot concatenate ’str’ and ’tuple’ objects

4
Introduction to Python Dr. Dil Gurung, Kathmandu University

1.4.2 Comparison operators

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

1.4.3 Assignment operators


Type set in Python IDE window and run the program.
a = 0
for i in range(5):
a += 2
print(a)

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

Operator Description Example


= Assigns values from right side c = a + b assigns value
operands to left side operand of a + b into c
+= It adds right operand to the left operand c+ = a is equivalent to
and assign the result to left operand c=c+a
−= It subtracts right operand from the left operand c− = a is equivalent to
and assign the result to left operand c=c−a
∗= It multiplies right operand with the left operand c∗ = a is equivalent to
and assign the result to left operand c=c∗a
∗∗ = Performs exponential (power) calculation on c ∗ ∗ = a is equivalent to
operators and assign value to the left operand c = c ∗ ∗a
/= It divides left operand with the right operand c/ = a is equivalent to
and assign the result to left operand c = c/a
// = It performs floor division on operators c// = a is equivalent to
and assign value to the left operand c = c//a
%= It takes modulus using two operands c% = a is equivalent to
and assign the result to left operand c = c%a

1.4.4 Logical operators


Operator Description
and Logical AND operator
or Logical OR operator
not Logical NOT operator

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

1.4.5 Membership operators


Operator Description
in is a member
not in is not a member

>>> a = [1, 10, 15, 19, 20, 22]


>>> 10 in a
True
>>> 12 in a
False

6
Introduction to Python Dr. Dil Gurung, Kathmandu University

>>> 12 not in a
True

1.4.6 Python operators precedence


Highest → ∗∗ ∗ / % // + − >> << <= <> >= == ! = = %=
/= // = −= += ∗= ∗∗ = Lowest →

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:

(a) 6 (g) 6/0 (m) 2*2e-2


(b) 6*2 (h) 24%5 (n) (2e + 14/15)
(c) 6**2 (i) 3.14*3**2 (o) (2e + 14)/15
(d) 6**2**2 (j) 3//2*5.0 (p) exp(1)
(e) 6/12 (k) 3/2*5 (q) >>> 3 + 4*\
(f) 6//12 (l) 2*2e+2 ... 2**5

2. Let x = 8 and y = 2. Write the values of the following expressions:

(a) x + y ∗ 3 (c) x ∗ ∗y (e) x/12.0


(b) (x + y) ∗ 3 (d) x%y (f) x//6

3. Let x = 2.354. Write the values of the following expressions.

(a) round(x) (d) floor(x) (g) abs(x)


(b) int(x) (e) ceil(x) (h) type(x)
(c) sign(x) (f) sqrt(x) (i) e**x

4. For x = 3 + 2j, Enter the following expression and observe the results:

(a) real(x) (b) imag(x) (c) abs(x)

Python considers j as an imaginary unit.

5. Enter the following expressions, and observe the results:

(a) sin(pi/2) (c) sin(radians(90))


(b) sin(90) (d) sin(degrees(pi/2))

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 .

7. Exponential and Logarithm The mathematical quantities ex , ln x and


log x are calculated with exp(x), log(x) and log 10(x) respectively. Calculate
the following quantities.

• e2 , eπ 163
, ln(e2 ), log 10(e2 ) and log 10(105 )
ln 17
• The solution of the equation 3x = 17 is x = . Calculate this x
ln 3
using Python.

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:

i. x+y v. y 3 . Check this vii. ln x


ii. y÷x gives the same re- viii. ln10 (y)
iii. x3 − y n sult as y × y × y ix. ln2 (y + x)
√ −n+1
iv. y vi. e x. complex(x, y)

(c) Trigonometric functions Treating x and y as angles in degrees con-


vert them to radians and calculate the following:
i. sin(x)
ii. cos 2(y − x)
iii. cos 2(x) + sin 2(x). Is this the answer that your expect? Why?
iv. sin 2(y) − 2 sin(y) cos(y). Is this the answer that your expect?
Why?
2. Simple Python Programs
(a) Temperature conversion The temperature conversion relation be-
tween Celsius (C) and Fahrenheit (F ) is given by
9
F = C + 32
5
Make a program for computing temperature in Fahrenheit for a given
temperature in Celsius. Name of program file: c2f.py.
(b) Compute the growth of money in a bank Let p be a banks interest
rate in percent per year. An initial amount A has then grown to
 p n
A 1+
100
after n years. Make a program for computing how much money 1000
euros have grown to after three years with 5 percent interest rate.
Name of program file: interest.py.

9
Introduction to Python Dr. Dil Gurung, Kathmandu University

2 Core python
The standard data types in Python are

numbers, string, list, tuple, dictionary

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.

>>> a = 3 # a is integer type


>>> print(a)
3
>>> a = 3.0 # a is float type
>>> print(a)
3.0

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.

>>> string1 = ’Hello’


>>> string2 = ’World’
>>> string3 = string1 + ’ ’ + string2 # concatenation
>>> print(string3)
Hello World
>>> print(string3[0:5]) # Slicing - End index 5 is not included
Hello

A string is an immutable object - its individual characters cannot be modified


with an assignment, and it has a fixed length.

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

>>> list = [’Mathematics’, ’Physics’, ’Chemistry’, ’Biology’] # Creat a list


>>> print(list)
[’Mathematics’, ’Physics’, ’Chemistry’, ’Biology’]
>>> list.append(’Computer Engineering’) # append Computer Engineering to list
>>> list
[’Mathematics’, ’Physics’, ’Chemistry’, ’Biology’, ’Computer Engineering’]
>>> list.insert(3, ’Mechanical Engineering’ ) # insert Mechanical Engineering
in index 3
>>> print(list)
[’Mathematics’, ’Physics’, ’Chemistry’, ’Mechanical Engineering’,
’Biology’, ’Computer Engineering’]
>>> print(len(list)) # length of list
6
>>> list[3:4] = [’Civil Eng’,’Geomatic Eng’] # Modify selected elements
>>> print(list)
[’Mathematics’, ’Physics’, ’Chemistry’, ’Civil Eng’, ’Geomatic Eng’,
’Biology’, ’Computer Engineering’]
>>> del(list[4]) # Delet element in index 4
>>> print(list)
[’Mathematics’, ’Physics’, ’Chemistry’, ’Civil Eng’, ’Biology’,
’Computer Engineering’]
Example 2: Matrix can be represented as nested lists, with each row being an
element of the list. Here is a 3 × 3 matrix A in the form of a list:
>>> A = [ [1,2,3],\
... [4,5,6],\
... [7,8,10] ]
>>> print(A[1]) # Print second row element
[4, 5, 6]
>>> print(A[1][2]) # Print third element of first second row
6
>>> print(det(A)) # To find determinant of A
-3.0
>>> print(inv(A)) # To find inverse of non-singular matrix A
[[-0.66666667 -1.33333333 1. ]
[-0.66666667 3.66666667 -2. ]
[ 1. -2. 1. ]]
It is very convenient to employ array objects provided by numpy module.

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

>>> rec = ( ’Gurung’, ’Suvesh’ , (20, 12, 2005) ) # This is a tuple


>>> rec
(’Gurung’, ’Suvesh’, (20, 12, 2005))
>>> lastname, firstname, birthdate = rec # unpack the tuple
>>> print(firstname)
Suvesh
>>> birthyear = birthdate[2]
>>> print(birthyear)
2005
>>> birthmonth = birthdate[1]
>>> print(birthmonth)
12
>>> name = rec[1] + ’ ’ + rec[0]
>>> print(name)
Suvesh Gurung
>>> print(rec[0:2])
(’Gurung’, ’Suvesh’)

Any list operation that changes the list will not work for tuples:

>>> rec[1] = ’Dil’


Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: ’tuple’ object does not support item assignment
>>> rec.append(0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: ’tuple’ object has no attribute ’append’
>>> del rec[1]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: ’tuple’ object doesn’t support item deletion

Some list methods, like index , are not available for tuples. So why do we need
tuples when lists can do more than tuples?

• Tuples protect against accidental changes of their contents.

• Code based on tuples is faster than code based on lists.

• 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

Operations on sequences (Applied to strings, lists and tuples)

Let a and b be any two sequences (strings, lists or tuples).

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.

>>> str = "Kathmandu University"


>>> print str
>>> print str[0]
>>> str[0:11]
>>> print str[0:11]
>>> print str[2:12]
>>> print str[2:]
>>> print str * 2
>>> print str + "Dhulikhel"
>>> print str + " " +"Dhulikhel"
>>> print str + 4

2. For the list

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

a.append(object) -- append object to end


a.count(value) -> integer -- return number of occurrences of value
del a[index] -- delete index element
a.extend(iterable) -- extend list by appending elements from
the iterable
a.index(value, [start, [stop]]) -> integer -- return first index of value.
Raises ValueError if the value is not present.
a.insert(index, object) -- insert object before index
a.pop([index]) -> item -- remove and return item at index
a.remove(value) -- remove first occurrence of value.
Raises ValueError if the value is not present.
a.reverse() -- reverse *IN PLACE*

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

2. User defined functions

3. lambda functions

3.1 built-in function


The Python interpreter has a number of functions and types built into it that are
always available. They are listed here in alphabetical order.

3.1.1 input function


The Python syntax is
input(prompt)
The following example illustrate the use of Input function.

r = input(’ Enter radius of a circle: ’)


Area = 3.14*r**2
print Area

3.1.2 range function


The built-in range function in Python is very useful to generate sequences of
numbers in the form of a list. Out put can be displayed with the range function.

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]

3.1.3 print function


Out put can be displayed with the print function

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.

MATLAB like print function


The following example illustrate the use of print function like MATLAB print
function.

r = input(’ Enter radius of a circle: ’)


Area = 3.14*r**2
print(’The area of the circle of radius %.1f is %.1f
square unit.’ %(r,Area))

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.

r = input(’ Enter radius of a circle: ’)


Area = 3.14*r**2
print(’The area of the circle of radius {:2.1f} is {:4.1f}
square unit.’. format(r,Area))

17
Introduction to Python Dr. Dil Gurung, Kathmandu University

3.2 User defined function


The structure of user defined Python function is
def name(arg1, arg2, ...):
statements
return return_values
The def line with the function name and arguments is often referred to as the
function header, while the indented statements constitute the function body.
If the return statement or return values are omitted, the function returns
the null object.
Example 1 The temperature conversion between Celsius degrees C to the corre-
sponding Fahrenheit degrees F is given by
9
F = C + 32
5
The Python code looks like:
>>> def F(C):
... F = 9.0/5*C + 32
... return F
...
>>> F(0)
32.0
If we omit the return, then out put looks like
>>> def F(C):
... F = 9.0/5*C + 32
...
>>> F(0)
>>> print F(0)
None

3.2.1 Local and global variables


Variables assigned in a function, including the arguments are called the local
variables to the function. The variables defined out side the function body and
function headers are called global variables. Let us look the following example
for the idea of local and global variables.
C = 37 # Global variable
def F(C):
F = 9.0/5*C + 32 # Here F, C local variable
return F

C = input("Enter the Celsius degree: ")


print(’%.1f %10.1f’ %(F(C),C) )
The out put of the program is

18
Introduction to Python Dr. Dil Gurung, Kathmandu University

>>> runfile(’/home/dgurung/.spyder2/.temp.py’, wdir=r’/home/dgurung/.spyder2’)


Enter the Celsius degree: 37
98.6 37.0

How Python looks up variables


The more general rule, when you have several variables with same name, is that
Python first tries to look up the variable name among the local variables, then
there is a search among global variables, and finally among built-in Python func-
tions.

Example 2 Here is a complete sample program that aims to illustrate the rule
above:

print sum # Sum is a built-in Python function


sum = 500 # rebind the name sum to an int
print sum # sum is a global variable

def myfun(n):
sum = n + 1
print sum # sum is a local variable
return sum

sum = myfun(2) + 1 # new value is global variable sum


print sum

Example 3 Some more examples:

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

2. But when written code as

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

Then out put is

>>> runfile(’/home/dgurung/.spyder2/.temp.py’,
wdir=r’/home/dgurung/.spyder2’)
1
2
1

3.3 lambda function


The syntax of lambda function is

f_name = lambda arg1, arg2, ... : expression

The temperature conversion from Celsius degrees F to Fahrenheit degrees


F in lambda function is

>>> F = lambda C: 9.0/5*C + 32


>>> F(0)
32.0

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

Enter any module name to get more help. For example

>>> help(’numpy’)

4.1 Mathematics Modules


Most mathematical functions are not built into core Python, but are available by
loading the math module and cmath module. There are three ways of accessing
the functions in a module.

4.1.1 math Module


1. The standard way to import a module, say math, is to write

import math

and then access individual functions in the module with the module name
as prefix as in

x = math.sqrt(2)

This can also be done as

import math as m

and then access individual functions in the module with the module name
as prefix as in

x = m.sqrt(2)

2. There is an alternative import syntax that allows us to skip the module


name prefix. This alternative syntax has the form from module import
function. A specific example is

from math import sqrt

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)

More than one function can be imported:

from math import sqrt, exp, log, sin

3. Sometimes one just write

from math import *

to import all functions in the math module.

To see the descriptions of all functions in math module, type

>>> help(’math’)

Only the contents of a module can be printed by calling

dir(module)

Here is how to obtain a list of the functions in the math 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)

Return the square root of x.

22
Introduction to Python Dr. Dil Gurung, Kathmandu University

4.1.2 cmath Module


The cmath module provides many of the functions found in the math module,
but these functions accepts complex numbers. The functions in the module are

>>> import cmath


>>> dir(cmath)
[’__doc__’, ’__name__’, ’__package__’, ’acos’, ’acosh’,
’asin’, ’asinh’, ’atan’, ’atanh’, ’cos’, ’cosh’, ’e’,
’exp’, ’isinf’, ’isnan’, ’log’, ’log10’, ’phase’, ’pi’,
’polar’, ’rect’, ’sin’, ’sinh’, ’sqrt’, ’tan’, ’tanh’]

Here are examples of complex arithmetic:

>>> from cmath import sin


>>> x = 2.1 - 4.3j
>>> y = 1.2 + 0.5j
>>> z = 0.5
>>> print(x/y)
(0.218934911243-3.67455621302j)
>>> print x + y
(3.3-3.8j)
>>> print(sin(x))
(31.8150323744+18.6001018624j)
>>> print(sin(z))
(0.479425538604+0j)

4.2 numpy Module


The numpy module is not a part of the standard Python release. It must be
installed separately. This module is specially used for numerical operations. The
scipy module is also used for numerical operations. The complete set of functions
in numpy is obtained as

>>> import numpy


>>> dir(numpy)

4.2.1 Creating an array


The module numpy introduce array objects that are similar to lists, but can be
manipulated by numerous functions contained in the module. The size of an
array is immutable, and no empty elements are allowed.
Array can be created in several ways. One of them is to use the array function
to turn a list into an array:
array(list, type)
Following are examples of creating an array.

>>> import numpy as np


>>> a = np.array([1,2,3,4])
>>> print a

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

Other available functions are

zeros((dim1, dim2), type)

which creates a dim1 × dim2 array and fills it with zeros, and

ones((dim1, dim2), type)

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.

>>> import numpy as np


>>> print(np.arange(2,10,2))
[2 4 6 8]
>>> print(np.arange(2.0,10.0,2.0))
[ 2. 4. 6. 8.]
>>> print(np.zeros(3))
[ 0. 0. 0.]
>>> print(np.zeros(3),int)
(array([ 0., 0., 0.]), <type ’int’>)
>>> print(np.zeros((3),int))
[0 0 0]
>>> print(np.ones((2,2)))
[[ 1. 1.]
[ 1. 1.]]

4.2.2 Accessing and changing array elements


If a is a 2 or more dimensional array, then a[i : j] accesses the element in row
i and column j, whereas a[i] refers to row i. The elements of an array can be
changed by assignment as follows:

>>> import numpy as np


>>> a = np.zeros( (3,3), int )

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

4.2.3 Operations on arrays


Arithmetic operators work differently on arrays than they do on tuples and lists.
In array the operation is applied to each element in the array. Here are examples:

>>> import numpy as np


>>> a = np.array([1,2,3,4],floats)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name ’floats’ is not defined
>>> a = np.array([1,2,3,4],float)
>>> print a/2
[ 0.5 1. 1.5 2. ]
>>> print a - 1.5
[-0.5 0.5 1.5 2.5]
>>> print (a - 1.5)
[-0.5 0.5 1.5 2.5]
>>> print (np.sqrt(a))
[ 1. 1.41421356 1.73205081 2. ]
>>> print (np.sqrt(a[1]))
1.41421356237

4.2.4 Array functions


There are numerous functions in numpy that perform array operations and other
useful tasks. Here are few examples:

>>> import numpy as np


>>> A = np.array([ [1,2,3],[4,5,6],[7,8,10] ] )
>>> print(np.diagonal(A)) # Principal diagonal
[ 1 5 10]
>>> print(np.diagonal(A,1)) # First upper subdiagonal
[2 6]
>>> print(np.diagonal(A,-1)) # First lower subdiagonal
[4 8]
>>> print(np.trace(A)) # Sum of diagonal elements
16

25
Introduction to Python Dr. Dil Gurung, Kathmandu University

>>> print(np.argmin(A,axis=0)) # Indices of smallest column elements


[0 0 0]
>>> B = A
>>> print(A*B) # Componentwise multiplication
[[ 1 4 9]
[ 16 25 36]
[ 49 64 100]]
>>> print(np.dot(A,B)) # Matrix multiplication
[[ 30 36 45]
[ 66 81 102]
[109 134 169]]
>>> print(np.linalg.det(A)) # Determinant of A
-3.0
>>> print(np.linalg.inv(A)) # Inverse of A
[[-0.66666667 -1.33333333 1. ]
[-0.66666667 3.66666667 -2. ]
[ 1. -2. 1. ]]
>>> print(A+B)
[[ 2 4 6]
[ 8 10 12]
[14 16 20]]
>>> A[1,1] = 100 # Change an element
>>> print(A)
[[ 1 2 3]
[ 4 100 6]
[ 7 8 10]]
>>> A[2, 0:2] = [-20 -10] # Change part of a row
>>> print(A)
[[ 1 2 3]
[ 4 100 6]
[-30 -30 10]]

Array being immutable, need a specific approach to delete part of an array.


For Example

import numpy as np

a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
index = [2, 3, 6]

new_a = np.delete(a, index)

print(new_a) # Prints ‘[1, 2, 5, 6, 8, 9]‘

4.2.5 Linear algebra Module


The numpy module comes with a linear algebra module called linalg that contains
routine tasks such as matrix inversion and solution of simultaneous equations. For
example:

26
Introduction to Python Dr. Dil Gurung, Kathmandu University

>>> from numpy import array


>>> from numpy.linalg import inv,solve
>>> A = array([ [ 1,2,3],\
... [4,5,6],\
... [7,8,10] ] )
>>> b = array([0,1,-1])
>>> print(inv(A)) # inverse of A
[[-0.66666667 -1.33333333 1. ]
[-0.66666667 3.66666667 -2. ]
[ 1. -2. 1. ]]
>>> print(solve(A,b) ) # Solve AX = b
[-2.33333333 5.66666667 -3. ]

4.3 Plotting with matplotlib.pyplot


The module matplotlib.pyplot is a collection of 2D plotting functions that provide
Python with MATLAB-style functionality. Here are some examples:
from numpy import arange,sin,cos,pi
import matplotlib.pyplot as plt

x = arange(-2*pi,2*pi,pi/20)

plt.plot(x,sin(x),’o-’,x,cos(x),’^-’) # Plot with specified


# line and marker style
plt.xlabel(’x’) # Add to label x-axis
plt.legend((’sine’,’cosine’),loc = 0 ) # Add legend in location at 0
plt.grid(True) # Add coordinate grid
plt.title(’Sine-Cosine’,fontsize = 16.0, fontweight = ’bold’)
# Title of figure

plt.show() # Show plot on screen


Plot command can write separately for each functions, like
from numpy import arange,sin,cos,pi
import matplotlib.pyplot as plt
x = arange(-2*pi,2*pi,pi/20)

plt.plot(x,sin(x),’o-’) # Plot with specified


# line and marker style
plt.plot(x,cos(x),’^-’,lw = 3.0) # linewidth = 3
plt.xlabel(’x’) # Add to label x-axis
plt.legend((’sine’,’cosine’),loc = 1 ) # Add legend in loc = 1
plt.grid(True) # Add coordinate grid
plt.title(’Sine-Cosine’,fontsize = 16.0, fontweight = ’bold’)
# Title of figure
plt.savefig(’testplot.png’,format = ’png’)
# Save plot in png for future use
plt.show() # Show plot on screen

27
Introduction to Python Dr. Dil Gurung, Kathmandu University

Running the second program produces the following figure.

The line and marker style are specified by the string characters. Some are
shown in the following table:

Symbol ‘-’ ‘–’ ‘-.’ ‘:’ ‘o’


Style Solid line Dashed line Dash-dot line Dotted line Circle marker
Symbol ‘ˆ’ ‘s’ ‘h’ ‘x’
Style Triangle marker Square marker Hexagonal marker x-marker

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.

from numpy import arange,sin,cos,pi


import matplotlib.pyplot as plt

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

plt.grid(True) # Add coordinate grid


plt.show() # Show plot on screen
Running the program produces the following figure.

4.3.2 Contour plot


Here is the Python code for contour plot of the function
 x  2 2
f (x) = 1 − + x + y5 5
e−x −y
2
import numpy as np
import matplotlib.pyplot as plt

def f(x, y):


return (1 - x / 2 + x ** 5 + y ** 3) * np.exp(-x ** 2 -y ** 2)

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)

plt.contourf(X, Y, f(X, Y), 8, alpha=.75, cmap=’jet’)


C = plt.contour(X, Y, f(X, Y), 8, colors=’black’, linewidth=.5)
The figure looks like:

4.3.3 Surface plot


Here is the Python code for contour plot of the function
f (x) = sin(x2 + y 2 )
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D

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)

ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=’hot’)


The surface plot looks like:

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

import matplotlib.pyplot as plt


import numpy as np
plt.close(’all’)
plt.figure(figsize=(6,4.5))

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

The plot looks like:

31
Introduction to Python Dr. Dil Gurung, Kathmandu University

EXERCISES - 4

1. Create a plot of the following chemistry data:

(a) Data set is:


Time(Decade) 0 1 2 3 4 5 6
CO2 Concentration(ppm) 250 265 272 260 300 320 389
Temperature (0 C) 14.1 15.5 16.3 18.1 17.3 19.1 20.2
(b) Create a line graph of CO2 versus time.
(c) Re-draw the graph with blue dashed line.
(d) Add a title and axis titles to the plot.
(e) Repeat (b), (c), and (d) for temperature versus time.

2. The distance travelled by a ball falling in the air is given by x(t) = x0 +


v0 t + 0.5 g t2 . Use Python code to plot x versus t for 0 ≤ t ≤ 3 when
x0 = 10 m, v0 = 15 m/s and g = −9.81 m/s2 . Write the text ball in the
figure window.

3. Define a curve f : [0, 0.2] → R defined by

f (t) = sin(20π t) + sin(60π t)

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

(a) Type the import numpy as np and import matplotlib.pyplot as plt in


Python Editor shell, and Write a python code to plot the trajectory
of f for T = 2π with 200 points.
(b) Use color green to make the trajectory.
(c) Set the line width to 3.
(d) Use plt.axis(’equal’)
(e) Show the center point with red color having marker *.
(f) Rewrite the above python code for user defined arbitrary radius of the
circle.
 
2 t cos t
6. Let γ : [0, 30] → R defined by γ(t) =
t sin t

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.

7. The shape of a Limacon can be defined parametrically as

r = r0 + cos θ, x = r cos θ, y = r sin θ

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.

8. Harmonic oscillator with damping α is

ẍ + α ẋ + x = 0, α > 0, x(0) = x0 , ẋ(0) = x1

We write in first order


    
ẏ1 0 1 y1
=
ẏ2 −1 −α y2

Thus, obtain the vector field (x, v) 7→ (v, −x − α v).

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.

Example 4 (Assigning letter grade) Suppose that we are writing a program


that reads in a numerical grade and assigns a letter grade to it according to the
following table. Write an if construct that will assign the grades as described.

Numeric grade Letter grade


grade > 95 A
86 < grade ≤ 95 B
76 < grade ≤ 86 C
66 < grade ≤ 76 D
0 < grade ≤ 66 F

Solution: The Python program of if construct follows as:

(a) One possible structure using elif clauses is:

grade = input(’Enter the numeric marks: ’)


if grade > 95:
print (’The grade is A. ’)
elif grade > 86:
print (’The grade is B. ’)
elif grade > 76:
print (’The grade is C. ’)
elif grade > 66:
print (’The grade is D. ’)
else:
print (’The grade is F. ’)

(b) One possible structure using nested if clauses is:

grade = input(’Enter the numeric marks: ’)


if grade > 95:

34
Introduction to Python Dr. Dil Gurung, Kathmandu University

print (’The grade is A. ’)


else:
if grade > 86:
print (’The grade is B. ’)
else:
if grade > 76:
print (’The gradd is C. ’)
else:
if grade > 66:
print (’The grade is D. ’)
else:
print(’The grade is F. ’)

5.2 The while loop


A while loop is a block of statements that repeats the statement as long as the
logical expression is true.

The general form of while loop is:

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.

Example 5 The following is the use of while loop.

i = 0
while i < 5:
print i
i += 1
print("while loop done!")

The out put we obtain as

0
1
2
3
4
while loop done!

Example 6 Write a Python program for the factorial of a positive integer n


using while loop.

Solution: The while construct for Python program for factorial is:

35
Introduction to Python Dr. Dil Gurung, Kathmandu University

n = input("Enter an integer: ")


if n<0:
print("Integer must be non-negative: ")
elif n == 0:
print("The factorial of %d is %d" %(n,1))
else:
factr = 1
k = 1
while k<=n:
factr = factr*k
k += 1
print("The factorial of %d is %d" %(n,factr))

5.3 The for loop


A for loop is a block of statements that executes the statement for a specified
number of times.

The general form of for loop is:

for TARGET in SEQUENCE:


block statement

can be used to define the block of statements that are to be executed in a given
number of times.

Example 7 The following is the use of for loop.

for i in range(0,5):
print i
print("for loop done! ")

The out put we obtain as

0
1
2
3
4
for loop done!

Example 8 Write a Python program for the factorial of a positive integer n


using for loop.

n = input("Enter an integer: ")


if n<0:
print("Integer must be non-negative: ")
elif n == 0:
print("The factorial of %d is %d" %(n,1))

36
Introduction to Python Dr. Dil Gurung, Kathmandu University

else:
factr = 1
for k in range(1,n+1):
factr = factr*k

print("The factorial of %d is %d" %(n,factr))

5.4 break statement


Any loop can be terminated by using

break

statement. Outside a loop, it does not work.

Example 9 An example of break statement within a loop.

for i in range(1,10):
if i == 5:
break
print("i = %d\n" %i)

print("End of Loop!")

The print out from the program is:


i = 1
i = 2
i = 3
i = 4
End of Loop!

5.5 continue statement


The
continue
statement allows us to skip a portion of an iterative loop. If the interpreter
encounters the continue statement, it immediately returns to the beginning of
the loop without executing the statements that follow continue.

Example 10 An example of continue statement within a loop.

for i in range(1,6):
if i == 3:
continue
print("i = %d\n" %i)

print("End of Loop!")

The print out from the program is:

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.

x = [] # create empty list


for i in range(1,100):
if i%9 != 0:
continue # if not divisible by 9, skip rest of loop
x.append(i) # append i to the list

print(x)

The print out from the program is:

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

from numpy import sum


n = input("Enter the number: ")
x = []
for i in range(1,2*n): # The last odd number is
# given by 2n-1
if i%2 == 0:
continue
x.append(i)
print(x) # List the first n odd numbers
print("The sum of the first %d odd integers is %d " %(n,sum(x)) )

The print out from the program for n = 15 is

Enter the number: 15


[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29]
The sum of the first 15 odd integers is 225

38
Introduction to Python Dr. Dil Gurung, Kathmandu University

EXERCISES – 5

1. Write a program that print out days of a week as

Sunday Monday Tuesday Wednesday Thursday Friday Saturday

2. Write a program for the sum of first n natural numbers.

3. Write a program for the sum of first n odd positive integers.

4. Write a program for the sum of first n even positive integers.

5. Write a program to evaluate the value of the function y(x) = x2 − 3x + 2


for all values of x between −1 and 3 with step size 0.1. Use for loop to
perform the calculation. Plot the resulting function using a 3-point-thick
dashed red line.

6. Write a program that evaluates the power series of


N
X xk
(a) exp(x) =
k=0
N
N
X
k x2k+1
(b) sin(x) = (−1)
k=0
(2k + 1)!

for given x and N .

7. Fibonacci sequence is recursively defined as



0,
 if n = 0
Fn = 1, if n = 1

Fn−1 + Fn−2 , if n > 1

Write a python program to generate the Fibonacci sequence.

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

You might also like