0% found this document useful (0 votes)
22 views131 pages

Python Scientific Programming Basics

The document outlines a Python programming course for B.Sc-B.Ed students, covering scientific programming basics, numerical Python (Numpy), and data handling. It details the evaluation system, including mid-term and end-semester exams, continuous assessment, and attendance requirements. Recommended books and various programming concepts such as installation, writing and running programs, variables, data types, and arithmetic operations are also discussed.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views131 pages

Python Scientific Programming Basics

The document outlines a Python programming course for B.Sc-B.Ed students, covering scientific programming basics, numerical Python (Numpy), and data handling. It details the evaluation system, including mid-term and end-semester exams, continuous assessment, and attendance requirements. Recommended books and various programming concepts such as installation, writing and running programs, variables, data types, and arithmetic operations are also discussed.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Programming: IT-I (EDIT0201)

[Link] (ITEP), Second Semester

Dr. Arvind Kumar


kumara@[Link]

Department of Physics, NIT Jalandhar


Contents of Course
Basics of Scientific Programming

Numerical Python (Numpy)

Data Handling Using Python

A. K (NIT Jalandhar) kumara@[Link] 2 / 25


Evaluation system
Total marks : 100
Mid term examination: 30 marks

End Semester Examination: 50 marks

Continuous assessment: 20 marks


▶ Quiz : 10 marks
▶ Assignment: 5 marks
▶ Class interaction and participation : 5 marks

Minimum 30% marks required in end semester exam (15 marks out of
50) . Overall 40% from 100 marks.

Attendance : Minimum 75% (otherwise not allowed for end semester


exam)
A. K (NIT Jalandhar) kumara@[Link] 3 / 25
Book Recommended:
“Learning Scientific Programming with Python” Christian Hills,
Cambridge (2nd Edition)

“Scientific Computing in Python”, Abhijit Kar Gupta, Techno World


(3rd Edition)

A. K (NIT Jalandhar) kumara@[Link] 4 / 25


Section I
Basics of Scientific Programming
Lecture 1

A. K (NIT Jalandhar) kumara@[Link] 5 / 25


About Python
By Guido van Rossum in 1989

High level programming language: user friendly and independent


of computer hardware architecture

Case sensitive

Free and have many useful libraries for scientific calculations

Version: Python 3 (Version 3.12.3= A.B.C.)

A is for major version, B is minor and C is micro version

Speed of execution is small compared to other compiled


programming languages such as C, Fortran. But rarely matter.

A. K (NIT Jalandhar) kumara@[Link] 6 / 25


Installation
Install Anaconda distribution
[Link]

Anaconda : Include Python, Spyder, Jupyter, NumPy, SciPy and


Matplotlib (last three are libraries)

Source codes available


NumPy: [Link]
SciPy: [Link]
Matplotlib: [Link]
IPython: [Link]
Jupyter Notebook and JupyterLab: [Link]

A. K (NIT Jalandhar) kumara@[Link] 7 / 25


Writing and Running of Python program
Python shell or IDLE (more advance shell)

Open IDLE (Integrated Development and Learning Environment)

Python 3.12.4 (tags/v3.12.4:8e8a4ba, Jun 6 2024, 19:30:16) [MSC


v.1940 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more
information.
>>>

A. K (NIT Jalandhar) kumara@[Link] 8 / 25


First program

Write a program to print the statement: Hello world !


Code

>>> print(’hello world’) #Input statement

Output

hello world

Note:In code above # is used for comment purpose

A. K (NIT Jalandhar) kumara@[Link] 9 / 25


Program 2
Program to calculate the height of ball thrown straight up in the air
y = v0 t − 0.5gt 2
Note: Take care of indentation while writing programs in Python.
Code

# Program to calculate the height of ball


v0 = 5 #initial velocity
g = 9.8 # Acc. due to gravity
t = 0.6 # time at which height required
y = v0*t - 0.5*g*t**2 # formula to calculate height, * is used
for multiplication and ** is for power
print(y) # printing result

Output

1.236
A. K (NIT Jalandhar) kumara@[Link] 10 / 25
Program 3: Use of Library function
Calculate the following
y
θ = tan−1
x
Probably we might be writing following code
Code

x = 10.0 # Horizonal distance


y = 10.0 # Vertical distance
angle = atan(y/x) # In radians
angle_deg = (angle/pi)*180 # Convert to degree
print(angle) # Print result

A. K (NIT Jalandhar) kumara@[Link] 11 / 25


Error in previous code, shown in spyder
Note last line specially

runfile(’F:/NITJ_August_2022_onwards/Teaching_22
/computation_2022/Python_2022_PPTs/
Programs/Chapter_1_Linge/angle_wrong_library1.py’,
wdir=’F:/NITJ_August_2022_onwards/
Teaching_22/computation_2022/
Python_2022_PPTs/Programs/Chapter_1_Linge’)
Traceback (most recent call last):

File "F:\NITJ_August_2022_onwards\Teaching_22
\computation_2022\Python_2022_PPTs
\Programs\Chapter_1_Linge
\angle_wrong_library1.py", line 9, in <module>
angle = atan(y/x) # In radians

NameError: name ’atan’ is not defined

A. K (NIT Jalandhar) kumara@[Link] 12 / 25


Import function
Mathematical functions such as atan, pi are grouped together in
Library module called math
Need to Import these to program using statement

from math import atan, pi

Correct Code

from math import atan,pi


x = 10.0 # Horizonal distance
y = 10.0 # Vertical distance
angle = atan(y/x) # In radians
angle_deg = (angle/pi)*180 # Convert to degree
print(angle_deg) # Print result

A. K (NIT Jalandhar) kumara@[Link] 13 / 25


Variables
Values are stored in variable names, which can be used for later
calculations.
Example: Calculate energy of electron for given momentum

from math import sqrt


c =3e8; #speed of light
m = 9.13e-31; # rest mass of electron
J_MeV = 1.6e-13; # conversion factor Joule to MeV
E1 = (m*c**2) ;
E1_MeV = E1/J_MeV; # In MeV units
p = 0;
E2 = sqrt( (p*c)**2 +m**2*c**4);
E2_MeV = E2/J_MeV; # In MeV units
print(’Rest mass energy =’, E1_MeV,’MeV’)
print(’Energy at given meomentum =’, E1_MeV,’MeV’)

A. K (NIT Jalandhar) kumara@[Link] 14 / 25


Variables
Variable names are case sensitive.
For example: Force, force, FORCE are three different variable
names

Need not to declare variables: Python is dynamically typed


language

Name should not start with digit

Cannot be a reserved keyword, e.g., if, else, while, for, lambda


etc.
Normally keywords are highlighted in color during their use in the
program and it is easy to avoid error.

Cannot be name of built-in constant names, e.g., True, False,


None
A. K (NIT Jalandhar) kumara@[Link] 15 / 25
Variables
Underscore ( ) can be used. Useful for writing large variable
name.

Special characters and symbols for mathematical calculations


cannot be used in the names of variables

Built-in function names (e.g. abs, round etc) should not be used
as variable name. If used, then these will not be available for the
purpose they intend to use.

Always give meaningful variable name. Also avoid long names.


For example: Use ‘force’ instead of ‘f’ as variable name to store
value of force in the variable name

A. K (NIT Jalandhar) kumara@[Link] 16 / 25


Data type: Numbers
Integer
Type int
Any magnitude (may be limited by memory of computer)
Examples: 1, -5, 2308424242
Can be separated by underscore for clarity
23_084_24_242

Integer arithmetic is exact

A. K (NIT Jalandhar) kumara@[Link] 17 / 25


Data type: Numbers
Floating
Type float

Real number, limited with precision (double precision, 15-16


decimal places)

Numbers with decimal are considered as floating

Use of e or E for Scientific notations


1.67263e-7 for 1.67263 × 10−7

Real arithmetic not exact but good enough for most scientific
calculations

A. K (NIT Jalandhar) kumara@[Link] 18 / 25


Data type: Numbers
Floating
Try following in Python shell
Floating data

>>> .00099
0.00099
>>> .0001
0.0001
>>> .00001
1e-05

Note the display of numbers in above example. Numbers smaller


than .0001 are displayed in scientific notation.

Pair of digits can be separated with underscores


A. K (NIT Jalandhar) kumara@[Link] 19 / 25
Data type: Numbers
Floating
Python employs double precision floatig point numbers and use
64 bits in total.

Reals in following range can be stored

±4.9 × 10−324 to ± 1.8 × 10308

Numbers above 1.8 × 10308 result in overflow error and below


this 4.9 × 10−324 will cause underflow

Ex: Verify above in python.

Number of significant figures in double precision is 15 or 16


decimal digits.
A. K (NIT Jalandhar) kumara@[Link] 20 / 25
Data type: Numbers
Complex
Type complex

Add real to imaginary


>>> 2+1.2j
(2+1.2j)

Note the use of ‘j’ for complex numbers

Separate real and imaginary in call to complex


>>> complex(2,1.2)
(2+1.2j)

Stop here and take some examples directly on Python shell

A. K (NIT Jalandhar) kumara@[Link] 21 / 25


Numbers
Number of one type can be converted into number of another type
Examples:
>>> float(3)
3.0
>>> int(4.3)
4
>>> complex(3)
(3+0j)
>>> int(3+4j)
Traceback (most recent call last):
File "<pyshell#19>", line 1, in <module>
int(3+4j)
TypeError: can’t convert complex to int
>>> TypeError: can’t convert complex to int
SyntaxError: EOL while scanning string literal
>>> complex(0,3)
3j

A. K (NIT Jalandhar) kumara@[Link] 22 / 25


Numbers
int round towards zero

Examples:
>>> int(-2.3)
-2
>>> int(-2.9)
-2
>>> int(2.3)
2

A. K (NIT Jalandhar) kumara@[Link] 23 / 25


Program: Example of plotting
Calculate the height y of ball thrown straight up in
the air and plot y as a function of time t:

y = v0 t − 0.5gt 2

Use linspace function from numpy library.

linspace function is used to create equally spaced


floating point number in some interval [a,b]

A. K (NIT Jalandhar) kumara@[Link] 24 / 25


Program: Example of plotting
Code

# Understanding plotting in Python


import numpy as np
import [Link] as plt
v0 = 5 #initial velocity
g = 9.8 # Acc. due to gravity
t = [Link](0,1,1001) # time at which height required
y = v0*t - 0.5*g*t**2 # formula to calculate height
[Link](t,y) # printing result
[Link](’t(s)’) # x label in plot
[Link](’y(m)’) # y label in plot
[Link]() # To display figure

A. K (NIT Jalandhar) kumara@[Link] 25 / 25


Section I
Basics of Scientific Programming (Python)
Lecture 1.2

Book recommended for first section:


“Learning Scientific Programming with Python” Christian Hills,
Cambridge (2nd Edition)

A. K (NIT Jalandhar) kumara@[Link] 1 / 21


Arithmetic operators
Symbol Role
+ Addition
- Substraction
* Multplication
/ Floating point division
// Integer point division
% Modulus
** Exponentiation
Floating point division always give floating result even though both
operands are integer.

A. K (NIT Jalandhar) kumara@[Link] 2 / 21


Examples of Arithmetic operations
>>> 2+3
5
>>> 2-4
-2
>>> 4*3
12

A. K (NIT Jalandhar) kumara@[Link] 3 / 21


Examples of Arithmetic operations

>>> 4/3
1.3333333333333333
>>> 4//3
1
>>> 2.7//2
1.0
>>> 5%3
2
>>> 5%3.0
2.0
>>>
>>> 2**3
8

A. K (NIT Jalandhar) kumara@[Link] 4 / 21


Operator precedence
Operators Precedency
** highest precedence
*, /, //, %
+, - Lowest

Precedence rules are overridden by parentheses.


Operators of equal precedence are evaluated left to right with
exception of exponentiation. It is evaluated right to left.

A. K (NIT Jalandhar) kumara@[Link] 5 / 21


Example for precedence
>>> 6/2/3
1.0
>>> 6/(2/3)
9.0
>>> 4*3+3
15
>>> 4*(3+3)
24
>>> 2**2**3
256
>>> 2**(2**3)
256
>>> (2**2)**3
64

A. K (NIT Jalandhar) kumara@[Link] 6 / 21


Methods and Attributes of Numbers
<object>.<attribute>
Example: real and imag are attributes for complex objects
>>> (4 + 5j).real
4.0
>>> (4 + 5j).imag
5.0

Callable functions: Note use of ().


>>> (4 + 5j).conjugate()
(4-5j)

Callable functions are methods.

A. K (NIT Jalandhar) kumara@[Link] 7 / 21


Mathematical Functions
abs and round are built-in functions available by default in Python
Use of abs function
>>> abs(-5.2)
5.2
>>> abs(-2)
2
>>> abs(3 + 4j)
5.0

A. K (NIT Jalandhar) kumara@[Link] 8 / 21


Mathematical Functions
Use of round function
>>> round(-9.62)
-10
>>> round(7.5)
8
>>> round(4.5)
4
>>> round(3.141592653589793 , 3)
3.142
>>> round(96485.33289, -2)
96500.0

Other functions need to import using import statement

A. K (NIT Jalandhar) kumara@[Link] 9 / 21


Use of Library function
Calculate following
y
θ = tan−1
x
Probably we might be writing following code
Code

x = 10.0 # Horizonal distance


y = 10.0 # Vertical distance
angle = atan(y/x) # In radians
angle_deg = (angle/pi)*180 # Convert to degree
print(angle) # Print result

A. K (NIT Jalandhar) kumara@[Link] 10 / 21


Error in previous code, shown in spyder
Note last line specially

runfile(’F:/NITJ_August_2022_onwards/Teaching_22
/computation_2022/Python_2022_PPTs/
Programs/Chapter_1_Linge/angle_wrong_library1.py’,
wdir=’F:/NITJ_August_2022_onwards/
Teaching_22/computation_2022/
Python_2022_PPTs/Programs/Chapter_1_Linge’)
Traceback (most recent call last):

File "F:\NITJ_August_2022_onwards\Teaching_22
\computation_2022\Python_2022_PPTs
\Programs\Chapter_1_Linge
\angle_wrong_library1.py", line 9, in <module>
angle = atan(y/x) # In radians

NameError: name ’atan’ is not defined

A. K (NIT Jalandhar) kumara@[Link] 11 / 21


Import function
Mathematical functions such as atan, pi are grouped together in
Library module called math
Need to Import these to program using statement

from math import atan, pi

Correct Code

from math import atan,pi


x = 10.0 # Horizonal distance
y = 10.0 # Vertical distance
angle = atan(y/x) # In radians
angle_deg = (angle/pi)*180 # Convert to degree
print(angle_deg) # Print result

A. K (NIT Jalandhar) kumara@[Link] 12 / 21


Alternative way
See following way of importing and note use of prefix math in
functions which are imported:

Code

import math
x = 10.0 # Horizonal distance
y = 10.0 # Vertical distance
angle = [Link](y/x) # In radians. Also note [Link]
angle_deg = (angle/[Link])*180 # Convert to degree
print(angle_deg) # Print result

A. K (NIT Jalandhar) kumara@[Link] 13 / 21


Importing all functions from a given library
Importing all functions from a given library:
from math import *
In general: from Library_name import *

Code

from math import *


x = 10.0 # Horizonal distance
y = 10.0 # Vertical distance
angle = atan(y/x) # In radians
angle_deg = (angle/pi)*180 # Convert to degree
print(angle_deg) # Print result

A. K (NIT Jalandhar) kumara@[Link] 14 / 21


No prefix cause conflicts
When importing a function which present in different
libraries/pacakages, no use of prefix cause conflicts.
Following calculate exponential of three numbers using numpy library

Code

from numpy import exp


x = exp([0, 1, 2])
print(x)

Result

[1. 2.71828183 7.3890561 ]

A. K (NIT Jalandhar) kumara@[Link] 15 / 21


No Prefix conflict
If in our program both numpy and math are used and code is written
as below

Code

from numpy import exp


from math import *
x = exp([0, 1, 2])
print(x)

Result

TypeError: must be real number, not list

In calculations, exp function of math library used which accept single


number not array.
A. K (NIT Jalandhar) kumara@[Link] 16 / 21
Use prefix
Put appropriate prefix before function

Code

import numpy
import math
x = [Link]([0, 1, 2])
y = [Link](0)
print(x)
print(y)

Result

[1. 2.71828183 7.3890561 ]


1.0

A. K (NIT Jalandhar) kumara@[Link] 17 / 21


Import with name change
Names can be changed as follows:
Code

import numpy as np
import math as m
x = [Link]([1,2, 3])
y = [Link](0)
print(x)
print(y)

Importing plotting library

import [Link] as plt

matplotlib is a package which contain pyplot module and this module


is named plt

A. K (NIT Jalandhar) kumara@[Link] 18 / 21


Import modules
import math (for real and integer)
import cmath (for complex)

[Link](x)
[Link](x)
[Link](x)
[Link](x)
[Link](x)
[Link](x)
[Link](x)
[Link](x)

A. K (NIT Jalandhar) kumara@[Link] 19 / 21


Import modules

>>> import math


>>> [Link](-1.5)
0.22313016014842982
>>> [Link](0)
1.0
>>> [Link](16)
4.0

A. K (NIT Jalandhar) kumara@[Link] 20 / 21


Example
Example

>>> a = 4.503
>>> b = 2.377
>>> c = 3.902
>>> s = (a + b + c) / 2
>>> area = [Link](s * (s - a) * (s - b) * (s - c))
>>>print(area)

A. K (NIT Jalandhar) kumara@[Link] 21 / 21


Section I
Basics of Scientific Programming (Python)
Lecture 1.3

Book recommended for first section:


“Learning Scientific Programming with Python” Christian Hills,
Cambridge (2nd Edition)

A. K (NIT Jalandhar) kumara@[Link] 1 / 16


Comparisons Operators
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
The result of comparison is boolean object: True or False.
Examples:
>>> 4==5
False
>>>
3.0==3
True

When real and integers are compared, integer is first converted to


real, then comparison is done.
A. K (NIT Jalandhar) kumara@[Link] 2 / 16
isclose function
Comparing floating point numbers may lead to unexpected
results
For example:
a = 0.01
b = 0.1**2
a==b
False

Number .01 and 0.1**2 are stored as binary number with


different representation
Function isclose is useful to check the equivalence of two floating
point numbers within some tolerance.

A. K (NIT Jalandhar) kumara@[Link] 3 / 16


isclose function
Examples of isclose function
[Link](.01,0.1**2)
True

rel_tol argument is used to set relative tolerance. Default value


is 1.e-9
Example:
[Link](.01,0.1**2,rel_tol=10e-30)
False

Exercise: What about comparison with zero? What will be result


of the following?
[Link](0,1.0e-12)
[Link](0,1.e-12,abs_tol = 1.0e-10)

A. K (NIT Jalandhar) kumara@[Link] 4 / 16


Logic Operators
and, not, or
are logic operators
Comparison operators are used with logic operators
9 > 4 and -4>=0
False

3>2 or 1!=2
True

Comparison operators are evaluated first, then logical operators.


For logical operators, order of precedence is : not, and, or
Precedence overridden by parentheses
>>> not 7.5<0.9
True
>>> not 7.5<0.9 or 4 == 5
True
>>> not (7.5<0.9 or 4 ==4)
False
A. K (NIT Jalandhar) kumara@[Link] 5 / 16
Boolean Equivalents and Conditional Assignment
Python can convert an object to bool type
Object 0 evaluated to False and any non-zero value is True
>>> a = 0
>>> a or 4>3 # False or True
True

>>> not a+1 # not True,


False
>>>

In above, addition has higheer precedence then the logic operator


not
bool constructor
>>> bool(-2)
True
>>> bool(0)
False
A. K (NIT Jalandhar) kumara@[Link] 6 / 16
Boolean Equivalents and Conditional Assignment
and and or operators return one of their operands, not just bool
equivalents
Logic expressions are evaluated left to right
Logic expressions involving and and or operators are short
circuited which means second expression is evaluated if necessary
to decide the truth value of whole expression
>>> a=0
>>> a-2 or a
-2

>>> 4>3 and a-2


-2

>>> 4>3 and a


0

A. K (NIT Jalandhar) kumara@[Link] 7 / 16


Immutability and Identity
Objects assigned to variables are stored in memory
Using id operator one can check the memory location
>>> a = 9
>>> id(a)
1411260285424
>>> b = a
>>> id(b)
1411260285424
>>> a = 4
>>> id(a)
1411260285264
>>> id(b)
1411260285424

A. K (NIT Jalandhar) kumara@[Link] 8 / 16


Immutability and Identity
Using is operator one can check the identity of two variables
>>> d = 3
>>> c = d
>>> c is d
True
>>> f = 4
>>> f is d
False
>>> f = 3
>>> f is d
True

Exercise:
a = 10
id(a) = ?
a=a+1
id(a) = ?
A. K (NIT Jalandhar) kumara@[Link] 9 / 16
Strings
type is str
Enclose text to be stored as string inside single or double quotes.
For example:
>>> A = ’Hello World’

>>> type(A)
<class ’str’>

>>> A = "Men’s freind"

Strings can be concatenated:


>>> ’Phy’+’sics’ # using + operator
’Physics’

>>> ’Phys’’sics’ # place strings next to each other


’Physsics’

A. K (NIT Jalandhar) kumara@[Link] 10 / 16


Strings

>>> A = ’Electron belongs to the family of leptons and ...’

To break long strings into more than one line use / or parenthesis
>>> A = ’Electron belongs to the family\
of leptons and ...’

A =’Electron belongs to the family of leptons and ... ’

Function str is used to convert an object into string type. For


example:
>>> A = str(30)

’30’

A. K (NIT Jalandhar) kumara@[Link] 11 / 16


Indexing and Slicing Strings
First character in a string of n characters has index 0 and last has
index n − 1
>>> A = ’Force’

>>> A[0]

’F’

>>> A[4]

’e’

>>> A[5]

Traceback (most recent call last):


File "<pyshell#62>", line 1, in <module>
A[5]
IndexError: string index out of range
A. K (NIT Jalandhar) kumara@[Link] 12 / 16
Formatted printing
String’s format method can be used to insert objects in print
statement with formatting
Consider following
>>> v1 = 10
>>> print(’v1 is {}’.format(v1)) # formatting used
v1 is 10

>>> print(’v1 is’,v1)


v1 is 10

{} acts as placeholder

A. K (NIT Jalandhar) kumara@[Link] 13 / 16


More than one variable using format
Consider following
>>> v1 = 20 ; v2 = 3
>>> print(’v1 is {} and v2 is {}’.format(v1,v2)) #
formatting used
v1 is 20 and v2 is 3

>>> print(’v1 is’,v1,’and v2 is’,v2)


v1 is 20 and v2 is 3

Take care of order in argument of format


>>> print(’v1 is {} and v2 is {}’.format(v2,v1))
v1 is 3 and v2 is 20

Better to name the arguments


>>> print(’v1 is {vel1} and v2 is {vel2}’.format(vel2 =
v2,vel1 = v1))
v1 is 20 and v2 is 3
A. K (NIT Jalandhar) kumara@[Link] 14 / 16
Print on multiple lines
Long line can be splitted to multiple lines
>>> print(’v1 is {vel1} \n v2 is {vel2}’.format(vel2 =
v2,vel1 = v1))
v1 is 20
v2 is 3 # note the space
>>> print(’v1 is {vel1} \nv2 is {vel2}’.format(vel2 =
v2,vel1 = v1))
v1 is 20
v2 is 3

In above note the space in first case before v2

A. K (NIT Jalandhar) kumara@[Link] 15 / 16


Formatting
Consider printing of following:
r = 12.89742 # real number
k = 32 # integer
h = ’hello’ # string

print(r,k,h)
print(’r={:.3f}, k={:d},h = {:s}’.format(r,k,h))
print(’r = {:9.2e}, k = {:5d}, h = {:s}’.format(r,k,h))

12.89742 32 hello # Output of first print


r=12.897, k=32,h = hello # Output of 2nd print
r = 1.29e+01, k = 32, h = hello # Output of 3rd print

In above f is for float, d is for integer, s is for string, e for


scientific notation

A. K (NIT Jalandhar) kumara@[Link] 16 / 16


Section I
Basics of Scientific Programming (Python)
Lecture 1.4

Book recommended for first section:


“Learning Scientific Programming with Python” Christian Hills,
Cambridge (2nd Edition)

A. K (NIT Jalandhar) kumara@[Link] 1 / 14


List
Data structure for holding ordered list of objects
List is an ordered mutable array of objects
In list objects are separated by commas and written between square
brackets
Examples
>>> A = [1, ’force’, 20, 2.12];
A
[1, ’force’, 20, 2.12]

>>> B = [1, ’a’, 2,3,4, True]


B
[1, ’a’, 2, 3, 4, True]

>>> D = [1, ’a’, [2,3,4], True]


D
[1, ’a’, [2, 3, 4], True]

A. K (NIT Jalandhar) kumara@[Link] 2 / 14


List
Empty list:
>>> F = []
>>> F = list()

An item from a list can be retrieved by indexing


>>> A = [1, ’force’, 20, 2.12];

In: A[2]
Out: 20

In: A[0]
Out: 1

In: A[5]
Traceback (most recent call last):
File "<pyshell#29>", line 1, in <module>
A[5]
IndexError: list index out of range
A. K (NIT Jalandhar) kumara@[Link] 3 / 14
Lists
Consider following having list within list:
A = [1,5,7,[3,’force’,8],9,12]

In: A[3]
Out: [3, ’force’, 8]

In: A[3][1]
Out: ’force’

In [31]: A[3][1][2]
Out[31]: ’r’

A. K (NIT Jalandhar) kumara@[Link] 4 / 14


Lists
Use of in function to look for whether given element exist in a list
or not:
Examples:
G = [’Math’, ’Physics’, ’ED’, 3.14, 20]

3.14 in G
True

’ED’ in G
True

2 in G
False

A. K (NIT Jalandhar) kumara@[Link] 5 / 14


Lists and Mutability
Lists are mutable which means they can be altered

>>> A = [1, ’force’, 20, 2.12];

In: A[2]

Out: 20

In: A[2] = ’Newton’

In: A

Out: [1, ’force’, ’Newton’, 2.12]

A. K (NIT Jalandhar) kumara@[Link] 6 / 14


Lists and Mutability
Recall integers are not mutable

>>> a = 20;

>>> G = [1, ’force’, 20, a];

>>> G

[1, ’force’, 20, 20]


>>> a=2;

>>> G

[1, ’force’, 20, 20]

A. K (NIT Jalandhar) kumara@[Link] 7 / 14


Slicing in lists
listname[first:last:step]
Example:
>>> T = [0,1.0, 2.0, 3, 4 , 5, 6.0, ]

>>> type(T)

<class ’list’>
>>> len(T)
7
>>> T[1:4]

[1.0, 2.0, 3]
>>> T[::2]

[0, 2.0, 4, 6.0]


>>> T[:4:2]

[0, 2.0]
A. K (NIT Jalandhar) kumara@[Link] 8 / 14
Slicing in lists
listname[first:last:step]
Example:
>>> T = [0,1.0, 2.0, 3, 4 , 5, 6.0, ]

In: T[-1]
Out: 6.0

In: T[::-1]
Out: [6.0, 5, 4, 3, 2.0, 1.0, 0]

In: T[5:1:-2]
Out: [5, 3]

Note: Indexing and slicing can be done with strings also. But
strings are not mutable.

A. K (NIT Jalandhar) kumara@[Link] 9 / 14


List Methods
Different methods exit which can be used with lists
append: Append elements at end of list
>>> L = [10, 20, 30, 40];

>>> [Link](50)

>>> L

[10, 20, 30, 40, 50]

>>> K = []; # empty list

>>> [Link](5)
>>> K

[5]

A. K (NIT Jalandhar) kumara@[Link] 10 / 14


Lists methods
Examples of other methods in list are:
▶ extend: extend list with elements from other list
▶ index: return index of element (lowest)
▶ insert(index, element): Insert element at given index
▶ pop()
▶ reverse(): Reverse the list in place
▶ remove(element): Remove the first occurrence of element
▶ sort(): Sort the list in place
▶ copy(): Return copy of list
▶ count(element): Number of elements
▶ sorted
Exercise: Try all above with suitable example.

A. K (NIT Jalandhar) kumara@[Link] 11 / 14


Tuples
An immutable list. Items are placed between parenthesis.
Examples:
>>> T = (1,4,’Science’)

>>> type(T)

<class ’tuple’>

Tuples can be indexed and sliced, but cannot be used with


methods like append, extend etc
>>> T[0]

1
>>> T[1:2:1]

(4,)

A. K (NIT Jalandhar) kumara@[Link] 12 / 14


Tuples

>>> T
(1, 4, ’Science’)
>>> T[2]

’Science’
>>> T[0:2]

(1, 4)

>>> T[2] = 3

Ans.: ?

Empty tuple: T = ()
Tuple with single element: T = (element,)

A. K (NIT Jalandhar) kumara@[Link] 13 / 14


Tuples
>>> M = 3
>>> type(M)

<class ’int’>
>>> M = 2,4,9 # no use of parenthesis
>>> type(M)

<class ’tuple’>
>>> M
(2, 4, 9)
>>> a,b,c = 1,4,6

>>> c
6
>>> type(c)

<class ’int’>.

A. K (NIT Jalandhar) kumara@[Link] 14 / 14


Section I
Basics of Scientific Programming (Python)
Lecture 1.5

Book recommended for first section:


“Learning Scientific Programming with Python” Christian Hills,
Cambridge (2nd Edition)

A. K (NIT Jalandhar) kumara@[Link] 1 / 10


Iterable objects
Strings, lists and tuples are examples of data structures which are
iterable: Can be taken one at a time

A. K (NIT Jalandhar) kumara@[Link] 2 / 10


For loop
Used to pick items one by one
General syntax:

for item in iterable object


Example:
Code:

A = [1,2,6,9,12]; # List is deefined


for i in A: # use of for loop to print list
print(i)

Output will be:


1
2
6
9
12

A. K (NIT Jalandhar) kumara@[Link] 3 / 10


Iterable objects
Note the use of : in for loop
Each line in the block after colon must be indented by same amount
of white space. Four spaces recommended.

A. K (NIT Jalandhar) kumara@[Link] 4 / 10


Range
Range constructor is useful in referring to items which form sequence
Each item is placed by a constant value known as stride
General syntax:

range([a0=0],n,[stride=1])
If initial value is not given it is taken as 0.
Stride is optional and if not given, it is taken as 1
Object created by range is not a list
Examples:
>>> S = range(4)

>>> S
range(0, 4)

>>> S[1]

1
A. K (NIT Jalandhar) kumara@[Link] 5 / 10
Iterable objects

K = range(1,4)
C = range(0,6,2)
F = range(8,1,-2)

Use of range for iteration in loop:


for i in range(5):
print(i)

Output:
0
1
2
3
4

A. K (NIT Jalandhar) kumara@[Link] 6 / 10


Iterable objects
Exercise: Write a program to calculate distance s as a function
of time t using
1
s = ut + at 2 .
2
Consider t values from 1s to 101s in step of 10s. Also, u = 3m/s
and a = 20 m/s2 .

A. K (NIT Jalandhar) kumara@[Link] 7 / 10


Iterable objects
Exercise: Write a program to calculate distance s as a function
of time t using
1
s = ut + at 2 .
2
Consider t values from 1s to 101s in step of 10s. Also, u = 3m/s
and a = 20 m/s2 .
Ans:
u = 3 ;a =20;
for t in range(1,110,10):
s = u*t+(1/2)*a*t**2
print(t,s)

A. K (NIT Jalandhar) kumara@[Link] 7 / 10


Iterable objects
Example : Use for plotting
import [Link] as plt

u = 3 ;a =20;

tt = []
ss = []

for t in range(1,101,10):
s = u*t+(1/2)*a*t**2
print(t,s)

[Link](t)
[Link](s)

[Link](tt,ss)

A. K (NIT Jalandhar) kumara@[Link] 8 / 10


Iterable objects
Program for factorial of integer N
N = int(input(’enter the number N =’))

factorial = 1 # initializating factorial value


for i in range (1,N+1):
factorial = factorial*i
print(factorial)

Output:
enter the number N =3
6

A. K (NIT Jalandhar) kumara@[Link] 9 / 10


Nested for loop
Example
for i in range (1,3):
for j in range (1,3):
product = i*j
print(i,’*’,j,’=’,product)

A. K (NIT Jalandhar) kumara@[Link] 10 / 10


Nested for loop
Example
for i in range (1,3):
for j in range (1,3):
product = i*j
print(i,’*’,j,’=’,product)

Output
1 * 1 = 1
1 * 2 = 2
1 * 3 = 3
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6

A. K (NIT Jalandhar) kumara@[Link] 10 / 10


Section I
Basics of Scientific Programming (Python)
Lecture 1.6

Book recommended for first section:


“Learning Scientific Programming with Python” Christian Hills,
Cambridge (2nd Edition)

A. K (NIT Jalandhar) kumara@[Link] 1/8


Control flow
Sometime certain block of statements in a program are executed
only if certain conditions are satisfied.
Examples of control constructors
▶ if ... elif ... else
▶ while loop
▶ break
▶ contiue, pass, else

A. K (NIT Jalandhar) kumara@[Link] 2/8


Control flow
if ... elif ... else

if <logical expression1>:
<statements1>
elif<logical expression2>:
<statements2>
else:
<statements3>

Example: Program to find roots of quadratic equation


q = ax 2 + bx + c = 0 using formula

−b ± b 2 − 4ac
x=
2a

In above D = b 2 − 4ac is discriminant.

A. K (NIT Jalandhar) kumara@[Link] 3/8


Code for quadratic roots
from cmath import sqrt
a = float(input(’enter the coefficient a=’))

b = float(input(’enter the coefficient b=’))

c = float(input(’enter the coefficient c=’))


D = (b**2-4*a*c) # Discriminant
if (D>=0):
print(’roots are real’)
x1 = (-b+sqrt(D))/(2*a)
x2 = (-b-sqrt(D))/(2*a)
else:
print(’roots are imaginary’)
x1 = (-b+sqrt(D))/(2*a)
x2 = (-b-sqrt(D))/(2*a)
print(’First root, x1 = ’, x1)
print(’Second root, x2 = ’,x2)

A. K (NIT Jalandhar) kumara@[Link] 4/8


Program for factorial

###program to calculate factorial

N = int(input(’enter the number N =’))

if (N<0):
print(’factorial of negative number not defined’)
elif(N==0):
print(’factorial of zero is one’)
else:
factorial = 1
for i in range (1,N+1):
factorial = factorial*i
print(factorial)

A. K (NIT Jalandhar) kumara@[Link] 5/8


While loop
Example:
i = 0
while i<5:
i += 1 # i = i + 1
print(i)

Output:

1
2
3
4
5

A. K (NIT Jalandhar) kumara@[Link] 6/8


Break statement
Example:
for i in range(1,5):
A = i*2
if (i == 3):
break
print(i,A)

Output:

1 2
2 4

A. K (NIT Jalandhar) kumara@[Link] 7/8


Continue statement

for i in range(1,5):
if (i == 3):
continue
print(i)

Output:
1
2
4

A. K (NIT Jalandhar) kumara@[Link] 8/8


Section I
Basics of Scientific Programming (Python)
Lecture 1.7

Book recommended for first section:


“Learning Scientific Programming with Python” Christian Hills,
Cambridge (2nd Edition)

A. K (NIT Jalandhar) kumara@[Link] 1 / 16


Functions
Function is a set of statements which acts as a subprogram
Parts of program which repeat again and agian, can be written as
function
Functions can be in-built which are in the python or available in
library or can be constructed by user

A. K (NIT Jalandhar) kumara@[Link] 2 / 16


Functions
Consider following program to calculate the rest mass energy of
electron and proton
Code

c =3e8; #speed of light


m_e = 9.13e-31; # rest mass of electron
m_p = 1.67e-27; # rest mass of proton
J_MeV = 1.6e-13; # conversion factor Joule to MeV
E_e = (m_e*c**2) ;
E_e_MeV = E_e/J_MeV; # In MeV units

E_p = (m_p*c**2) ; # Note here formula repeating


E_p_MeV = E_p/J_MeV; # In MeV units

print(’Rest mass energy of electron =’,E_e_MeV,’MeV’)


print(’Rest mass energy of proton =’,E_p_MeV,’MeV’)

A. K (NIT Jalandhar) kumara@[Link] 3 / 16


Function definition
General syntax
Code

def function_name(Arguments):

Statement 1
Statement 2
Statement 3

return output_variables

Function should be defined before it is called.


Function will be called in main program

A. K (NIT Jalandhar) kumara@[Link] 4 / 16


Functions

# Function to calculate energy


def mass_energy(m):
c =3e8; #speed of light
J_MeV = 1.6e-13; # conversion factor Joule to MeV
E1 = (m*c**2) ;
E1_MeV = E1/J_MeV; # In MeV units
return E1_MeV

Main program part

m_e = 9.13e-31; # rest mass of electron in kg


m_p = 1.67e-27; # rest mass of proton
E_e = mass_energy(m_e)
E_p = mass_energy(m_p)
print(’Rest mass energy of eletron =’, E_e,’MeV’)
print(’Rest mass energy of protn =’, E_p,’MeV’)

A. K (NIT Jalandhar) kumara@[Link] 5 / 16


Program for factorial
Calculate the number of microstates Ω using formula
n!
Ω=
n!(n − n1 )!

In above, n is total number of particles, n1 is the number of particles in


ground state and n − n1 in the excited state.

Note: Make use of functions to calculate the factorials.

A. K (NIT Jalandhar) kumara@[Link] 6 / 16


Recall program for factorial

###program to calculate factorial

N = int(input(’enter the number N =’))

if (N<0):
print(’factorial of negative number not defined’)
elif(N==0):
print(’factorial of zero is one’)
else:
factorial = 1
for i in range (1,N+1):
factorial = factorial*i
print(factorial)

A. K (NIT Jalandhar) kumara@[Link] 7 / 16


Factorial as function

def factorial(N):
if (N<0):
print(’factorial of negative number not defined’)
elif(N==0):
print(’factorial of zero is one’)
else:
factorial_value = 1
for i in range (1,N+1):
factorial_value = factorial_value*i
return factorial_value

# Main program
n = int(input(’enter the number n =’))
n1 = int(input(’enter the number in first group =’))
microstates = factorial(n)/(factorial(n1)*factorial(n-n1))
print(’Number of microstates =’,microstates)

A. K (NIT Jalandhar) kumara@[Link] 8 / 16


Returning more than one value from function

def mass_energy(m):
c =3e8; #speed of light
J_MeV = 1.6e-13; # conversion factor Joule to MeV
E1 = (m*c**2) ;
E1_MeV = E1/J_MeV; # In MeV units
return E1,E1_MeV # packed as tuple
# Main program
m_e = 9.13e-31; # rest mass of electron in kg
# Method 1 of calling function and returning result
E_e_J,E_e_MeV = mass_energy(m_e) # Note left side
print(’Rest mass energy of eletron in Joule =’, E_e_J,’MeV’)
print(’Rest mass energy of electron in MeV =’,E_e_MeV,’MeV’)

# Method 2 of calling function and returning result


E = mass_energy(m_e) # Note left side
print(’Rest mass energy of eletron in Joule =’, E[0],’MeV’)
print(’Rest mass energy of electron in MeV =’,E[1],’MeV’)

A. K (NIT Jalandhar) kumara@[Link] 9 / 16


Default and Keyboard arguments

import math
def quadratic(a,b,c):
d = b**2-4*a*c
r1 = (-b+[Link](d))/(2*a)
r2 = (-[Link](d))/(2*a)

return r1,r2
# Main program
a1 = float(input(’enter value of a1=’))
b1 = float(input(’enter value of b1=’))
c1 = float(input(’enter value of c1=’))

R = quadratic(a1,b1,c1) # Note position of arguments


print(R)

When the arguments passed to function are in same order as given in


the function, these are called positional arguments

A. K (NIT Jalandhar) kumara@[Link] 10 / 16


Keyboard arguments
Order of arguments when calling function is different then in the
function itself
## Keyboard arguments program

import math
def quadratic(a,b,c):
d = b**2-4*a*c
r1 = (-b+[Link](d))/(2*a)
r2 = (-[Link](d))/(2*a)
return r1,r2
# Main program
a1 = float(input(’enter value of a1=’))
b1 = float(input(’enter value of b1=’))
c1 = float(input(’enter value of c1=’))

R = quadratic(b=b1,a=a1,c= c1) # Keyboard arguments program


print(R)

A. K (NIT Jalandhar) kumara@[Link] 11 / 16


Local and global variables
Variables defined only inside function but not used outside though
argument list are local variables
Variables defined outside function are available to use inside also even
though not called though argument list are known as global variables
import math
def quadratic(a,b,c):
d = b**2-4*a*c
q2 = 5 # local variable defined in function only
print(q1) # q1 is global variable
return d
# Main program
a1 = float(input(’enter value of a1=’))
b1 = float(input(’enter value of b1=’))
c1 = float(input(’enter value of c1=’))
q1 = float(input(’enter value of q1=’))
R = quadratic(b=b1,a=a1,c= c1)
print(q2) # q2 is local varraible and cannot be printed here
print(R)
A. K (NIT Jalandhar) kumara@[Link] 12 / 16
Global and non-local variables

import math
def quadratic(b):
global q1 # this require to make change in global
variable
d = b**2
q2 = 5 # local variable defined in function only
q1 = q1+1 # global varriable changed
print(’q1=’,q1) # q1 is global variable
return d

# Main program

b1 = float(input(’enter value of b1=’))


q1 = float(input(’enter value of q1=’))
R = quadratic(b1)
print(’R=’,R)

A. K (NIT Jalandhar) kumara@[Link] 13 / 16


Function as argument
def f(x):
A = x
return A

def g(x):
gf = x**2
return gf

def sum_fun(func,start,stop):
S = 0
for i in range(start,stop+1,1):
S = S+func(i)
return S

# Main program

print(sum_fun(f,1,3))
print(sum_fun(g,1,3))
A. K (NIT Jalandhar) kumara@[Link] 14 / 16
Lambda function
One line functions can be defined using lambda function
Consider function g = x 2 defined in following ways
g = lambda x: x**2 # using lambda function

## Above function is equivalent to:


def g(x):
gf = x**2
return gf

## or following
def g(x):
return x**2

A. K (NIT Jalandhar) kumara@[Link] 15 / 16


Lambda function
Example to use lambda function
def sum_fun(func,start,stop):
S = 0
for i in range(start,stop+1,1):
S = S+func(i)
return S
# Main program
print(sum_fun(lambda x: x,1,3))
print(sum_fun(lambda x: x**2,1,3))

# Other example f(x), single varaible


f = lambda x: x**2-2*x+3
print(f(2))

# Example g(x,y), two varaibles


g = lambda x,y: x**2*y-2*x*y+4
print(g(2,1))

A. K (NIT Jalandhar) kumara@[Link] 16 / 16


Section I
Basics of Scientific Programming (Python)
Lecture 1.8

Book recommended for first section:


“Learning Scientific Programming with Python” Christian Hills,
Cambridge (2nd Edition)

A. K (NIT Jalandhar) kumara@[Link] 1 / 14


Errors and Exceptions
Two types of errors
▶ Syntax error

▶ Exceptions

Syntax error: Grammatical errors and can be checked before program


is executed

Exception errors are runtime errors

A. K (NIT Jalandhar) kumara@[Link] 2 / 14


Syntax Errors
Code with error
for i in range(5)
print(i)

Error in above code


for i in range(5)
^
SyntaxError: expected ’:’

A. K (NIT Jalandhar) kumara@[Link] 3 / 14


Syntax Errors
Code with error
for lambda in range(5)
print(i)

Error in above code


for lambda in range(5)
^
SyntaxError: invalid syntax

A. K (NIT Jalandhar) kumara@[Link] 4 / 14


Syntax Errors
Code with error
if i = 3:
print(’hi’)

Error in above code


if i = 3:
^
SyntaxError: invalid syntax. Maybe you meant ’==’ or ’:=’
instead of ’=’?

A. K (NIT Jalandhar) kumara@[Link] 5 / 14


Syntax Errors
Code with error
if i == 3:
x = 2*i
y = 2*x

Error in above code


y = 2*x
^
IndentationError: unindent does not match any outer
indentation level

A. K (NIT Jalandhar) kumara@[Link] 6 / 14


Exception Errors (Logical error)
NameError : Variable name used but not defined
A = 3
X = 2*y
print(A)

Error in above code


X = 2*y

NameError: name ’y’ is not defined

A. K (NIT Jalandhar) kumara@[Link] 7 / 14


Exception Error
ZeroDivisionError
R = 3
Z = R/0

Error in above code


Z = R/0

ZeroDivisionError: division by zero

A. K (NIT Jalandhar) kumara@[Link] 8 / 14


Exception Errors
ValueError
A = float(’hello’)

Error in above code


A = float(’hello’)

ValueError: could not convert string to float: ’hello’

What about following?


B = print(float(’3.5’))

A. K (NIT Jalandhar) kumara@[Link] 9 / 14


Exception Errors
TypeError
Z = 3 + ’5’
print(Z)

Error in above code


Z = 3 + ’5’

TypeError: unsupported operand type(s) for +: ’int’ and ’str’

A. K (NIT Jalandhar) kumara@[Link] 10 / 14


Handling and Raising Exceptions
Handling Exceptions
x = 0
z =2
try:
y = 1/x
print(’y=’,y)
except ZeroDivisionError:
print(’division by zero not defined’)

A = 2*z
print(’A =’,A)

Output
division by zero not defined
A = 4

A. K (NIT Jalandhar) kumara@[Link] 11 / 14


Handling and Raising Exceptions
Example: Different exception will not be caught
x = 0
z =2
try:
k = 2*u
y = 1/x
print(’y=’,y)
print(’k = ’,k)
except ZeroDivisionError:
print(’division by zero not defined’)
A = 2*z
print(’A =’,A)

Output:
k = 2*u
NameError: name ’u’ is not defined

A. K (NIT Jalandhar) kumara@[Link] 12 / 14


Handling and Raising Exceptions
More than one exceptions as tuple
x = 0
z =2
try:
k = 2*u
y = 1/x
print(’y=’,y)
print(’k = ’,k)
except (ZeroDivisionError,NameError):
print(’division by zero not defined \
or variable not defined’)
A = 2*z
print(’A =’,A)

Output
division by zero not defined or variable not defined
A = 4
A. K (NIT Jalandhar) kumara@[Link] 13 / 14
Raising Exceptions
Code
u = 3
n = 7
if n%2:
raise ValueError(’n must be even’)

A = 2*u

Output
raise ValueError(’n must be even’)

ValueError: n must be even

A. K (NIT Jalandhar) kumara@[Link] 14 / 14


Section I
Basics of Scientific Programming (Python)
Lecture 1.9

Book recommended for first section:


“Learning Scientific Programming with Python” Christian Hills,
Cambridge (2nd Edition)

A. K (NIT Jalandhar) kumara@[Link] 1/5


Dictionary
Dictionaryname = {’Key name1’:value1, ’Key name2’:value2 }

Example
Physical_constants = {’light_speed’:3e8,
’me’:9.1e-31,
’h’:6.63e-34}

c = Physical_constants[’light_speed’]
m = Physical_constants[’me’]

E = m*c**2
print(E)

If same key value is used, recent will be used

A. K (NIT Jalandhar) kumara@[Link] 2/5


Dictionary
Values can be indexed using key
>> Physical_constants[’me’]

9.1e-31

Item in a dictionary can be assigned a value


Physical_constants[’me’] = 0.51

Different methods can be used with dictionary


get(), keys, values, items etc.

Example:
>> Physical_constants.get(’me’)
0.51

A. K (NIT Jalandhar) kumara@[Link] 3/5


Set
Unordered collection of unique items
A = set([1,5,9,1.2,9,2,1,’k’, 3+2j])
print(’A = ’,A)

Output:
A = {1.2, 1, 2, 5, 9, (3+2j), ’k’}

Check length
>> len(A)
7

Check membership
>> 10 in A
False

Braces can be used to construct set


B = {3,9,1,0,2,1}
A. K (NIT Jalandhar) kumara@[Link] 4/5
Set
Methods in set
[Link](10) # add element to set
[Link](1) # remove error
[Link](8) # key error will be raised as element not present
[Link](12)# error will not be raised if element not
present
[Link] # clear all elements from set

Exercise: Explore following methods with examples:


union, intersection, difference, symmetric_difference,
issuperset

A. K (NIT Jalandhar) kumara@[Link] 5/5

You might also like