Introduction to Python
Dr. Santosh Prasad Gupta
Assistant Professor
Department of Physics
Patna University, Patna
6/24/2021 Department of Physics, PU: SP Gupta 1
MPHY-CC209 : Physics Laboratory – II (Programming : Numerical)
Methods using: C/C++/Matlab/Python
Statistics of a data:
To find mean, standard deviation and frequency deviation of an actual
data set from any physics experiment
Graph plotting:
Plotting of graphs of functions such as exponential and trigonometric
functions.
Integration rule: A numerical approach to calculate the area under curve
Trapezoidal rule
Simpson’s 1/3rd rule
Simpson’s 3/8th rule
Linear equation solving:
Matrix inversion
Gauss Elimination method
6/24/2021 Department of Physics, PU: SP Gupta 2
Numerical method to find the root’s of a function:
The bisection method
Newton-Rapshon method.
Successive approximation (Method of Iteration)
Data interpolation:
Lagrange’s Interpolation formula
Differential equation
Euler’s method Numerical approach to solve
Runge-Kutta method (fourth order) order differential equation
Predictor corrector method
Solution of second order solution family of differential equation.
Plotting of third order solution family of differential equation
Monte Carlo simulation:
To find the area of a unit circle by Monte Carlo integration.
To simulate the random walk
6/24/2021 Department of Physics, PU: SP Gupta 3
The goal of this document is to teach you to think like a computer scientist. This way of
thinking combines some of the best features of mathematics, engineering, and natural science.
Low and high level languages:
low-level languages, sometimes referred to as machine languages or assembly languages.
Loosely speaking, computers can only execute programs written in low-level languages.
Low languages can convert to machine code without a compiler or interpreter. second-
generation programming languages use a simpler processor called an assembler. For
example: assembly and machine code
On the other hand high-level language such as and other high-level languages you might
have heard of are C, C++, Perl, and Java, have to be processed before they can run.
Programs written in a high-level language take less time to write, they are shorter
and easier to read, and they are more likely to be correct. Second, high-level
languages are portable, meaning that they can run on different kinds of computers
with few or no modifications. Low-level programs can run on only one kind of
computer and have to be rewritten to run on another. Due to these advantages,
almost all programs are written in high-level languages. Low-level languages are
used only for a few specialized applications.
6/24/2021 Department of Physics, PU: SP Gupta 4
Two kinds of programs process high-level languages into low-level languages:
interpreters and compilers. An interpreter reads a high-level program and executes it,
meaning that it does what the program says. It processes the program a little at a time,
alternately reading lines and performing computations.
A compiler reads the program and translates it completely before the program starts
running. In this case, the high-level program is called the source code, and the translated
program is called the object code or the executable. Once a program is compiled, you can
execute it repeatedly without further translation
Python is considered an interpreted language because Python programs are
executed by an interpreter.
6/24/2021 Department of Physics, PU: SP Gupta 5
Program :
is a sequence of instructions that specifies how to perform a computation. The
computation might be something mathematical, such as solving a system of equations or
finding the roots of a polynomial, but it can also be a symbolic computation, such as
searching and replacing text in a document or (strangely enough) compiling a program.
Debugging :
Programming is a complex process, and because it is done by human beings, it often
leads to errors. For whimsical reasons, programming errors are called bugs and the
process of tracking them down and correcting them is called debugging
History of Python:
Created in 1989 by Guido van Rossum and created as a scripting language for
administrative tasks Python is based on All Basic Code (ABC) and Modula-3. Named
after comic troupe Monty Python
Released publicly in 1991, and has growing community of Python developers and
evolved into well-supported programming language
6/24/2021 Department of Physics, PU: SP Gupta 6
Python modules: Module is a file with some Python code such as math module
Python library
Python library is a reusable chunk of code that you may want to include in your
programs/ projects. Compared to languages like C++ or C, Python libraries do not
pertain to any specific context in Python. Here, a library loosely describes a collection of
core modules. Essentially, then, a library is a collection of modules.
Python Standard Libraries
The Python Standard Library is a collection of exact syntax, token, and semantics of
Python. It comes bundled with core Python distribution. More than 200 core modules sit
at the heart of the standard library. This library ships with Python. But in addition to this
library, you can also access a growing collection of several thousand components from
the Python Package Index (PyPI). Some of them are; Matplotlib, NumPy, SciPy,
pandas, SymPy, etc.
Matplotlib : Matplotlib helps with data analyzing, and is a numerical plotting library. We
talked about it in Python for Data Science.
6/24/2021 Department of Physics, PU: SP Gupta 7
NumPy
It has advanced math functions and a rudimentary scientific computing package.
SciPy
Next up is SciPy, one of the libraries we have been talking so much about. It has a
number of user-friendly and efficient numerical routines. These include routines for
optimization and numerical integration.
6/24/2021 Department of Physics, PU: SP Gupta 8
Pandas
Pandas is a must for data-science. It provides fast, expressive, and flexible data structures
to easily (and intuitively) work with structured (tabular, multidimensional, potentially
heterogeneous) and time-series data.
SymPy
It is an open-source library for symbolic math. With very simple and comprehensible
code that is easily extensible, SymPy is a full-fledged Computer Algebra System (CAS).
It is written in Python, and hence does not need external libraries.
6/24/2021 Department of Physics, PU: SP Gupta 9
Installing Python :
Download the software from the site:
https://www.python.org/downloads/windows/
Installing Python Standard Libraries:
Before working with numpy, scipy and matplotlib, pandas, SymPy.
Open a cmd window and use the next set of commands one by one to
install NumPy, SciPy, Matplotlib, pandas, SymPy
python -m pip install numpy
python -m pip install scipy
python -m pip install matplotlib
python -m pip install pandas
python -m pip install sympy
6/24/2021 Department of Physics, PU: SP Gupta 10
There are two ways to use the interpreter: command-line mode and script mode.
In command-line mode, we type Python programs and the interpreter prints the result:
Alternatively, we can write a program in a file and use the interpreter to execute the
contents of the file. Such a file is called a script. The name of script file must has
extension .py such as test.py and so
command-line mode script mode
6/24/2021 Department of Physics, PU: SP Gupta 11
Python as calculator
Exponentiation gests first, followed by multiplication and division (including // and %)
and addition and subtraction come last .
6/24/2021 Department of Physics, PU: SP Gupta 12
Getting help in python
There is documentation built into Python known as module.
Example: Python has a module called math that contains familiar math functions,
including sin, cos, tan, exp, log, log10, factorial, sqrt, etc
Help about module: Type the following code in command line mode
>>>help()
help>“module”
Help about a particular module such as math: Type the following code in command line
mode >>>help()
help> math
Importing function from math module: Type the following code in command line mode
from math import sin, pi
print(sin(pi/2))
Comment in python: use # for commenting in python
# this is comment
6/24/2021 Department of Physics, PU: SP Gupta 13
Type of value in python: integer, float, string >>> type('Hello, World!')
<class 'str'>
>>> type(17)
<class 'int'>
>>> type(3.2)
<class 'float'>
Expression: >>> message = "What are you doing?"
>>> print (message)
What are you doing?
Name of the variable
76trombones is illegal >>> 76trombones = 'big parade'
because it does not begin SyntaxError: invalid syntax
with a letter. more$ is >>> more$ = 1000000
illegal because it contains SyntaxError: invalid syntax
an illegal character, the >>> class = 'Computer Science 101'
dollar sign. But what's wrong SyntaxError: invalid syntax
with class. Class is keyword
in python
6/24/2021 Department of Physics, PU: SP Gupta 14
Special keyword in python:
and def exec if not return assert del finally import or try break
elif for in pass while class else from is print yield continue
except global lambda raise
Function defining in python: import math
def sq(x): def area(radius):
return x*x temp = math.pi * radius**2
>>> sq(3) return temp
9 >>> area(3)
28.274333882308138
Logical operator
x != y # x is not equal to y
x > y # x is greater than y
x < y # x is less than y
x >= y # x is greater than or equal to y
x <= y # x is less than or equal to y
6/24/2021 Department of Physics, PU: SP Gupta 15
More on input and print
For a and b as a = eval(input('Enter the value of first number:'))
integer or float b=eval(input('Enter the value of second number:'))
print(a*b,'----',a+c,'----',b+c)
a = input('Enter the value of first number:')
For a and b as
b=input('Enter the value of second number:')
string
print('----',a+b,'----')
print ('-----\t'*5)
\n new line print('-----\t\t\t'*5)
\t tab print('-----\n'*5)
\’ for printing ’ print('----\''*5)
\” for printing ” print('----\"'*5)
print('----%'*5)
print('--- # % & " '*5)
6/24/2021 Department of Physics, PU: SP Gupta 16
>>> fruit = "banana"
String : strings are immutable
>>> letter = fruit[1]
>>> print (letter)
a
>>>len(fruit)
6
List
A list is an ordered set of values, where each value is identified by an index. The values
that make up a list are called its elements. Lists are similar to strings, which are ordered
sets of characters, except that the elements of a list can have any type. List are mutable.
There are several ways to create a new list; the simplest is to enclose the elements in
square brackets ([ and ]): as
>>>ls=[10, 20, 30, 40]
>>>ms =["spam", "bungee", "swallow"]
>>ls[0]
10
A nested list behave like a matrix
>>>matr=[[1,2,3],[4,5,6],[7,8,9]]
>>>matr[1][1]
5
6/24/2021 Department of Physics, PU: SP Gupta 17
Tuple
There is another type in Python called a tuple that is similar to a list except that it is
immutable. Syntactically, a tuple is a comma-separated list of values:.
>>> tup = ('a', 'b', 'c', 'd', 'e')
>>> tup[0]
'a'
Dictionaries
Dictionaries are similar to other compound types except that they can use any immutable
type as an index. A dictionary is a more general version of a list. Example: list of days
in the months of a year. The empty dictionary is denoted {}:
days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] # this list. blow is the dictionary
days = {'January':31, 'February':28, 'March':31, 'April':30,'May':31,
'June':30, 'July':31, 'August':31,'September':30, 'October':31,
'November':30, 'December':31}
Use {} for dictionary. ‘January’, ‘February’ etc. are the keys
Adding more elements in dictionary
>>> dict = {}
>>> dict['one'] = 'uno'
>>> dict['two'] = 'dos'
>>> print (dict)
{'one': 'uno', 'two': 'dos'}
6/24/2021 Department of Physics, PU: SP Gupta 18
for loop
Probably the most powerful thing about computers is that they can repeat
things over and over very quickly.
There are several ways to repeat things in Python, the most common of
which is the for loop.
# print hello in ten times # print hello in ten times in one line
for i in range(10): for i in range(10):
print('Hello') print('Hello’,end=‘’)
print('A')
print('B')
for i in range(5):
print('C')
print('D')
print('E')
print(‘loop is also over')
The value we put in the range function determines how many times we will loop.
The way range works is it produces a list of numbers from zero to the value minus
one. For instance, range(5) produces five values: 0, 1, 2, 3, and 4.
6/24/2021 Department of Physics, PU: SP Gupta 19
range Statement Values generated
range(10) 0,1,2,3,4,5,6,7,8,9
range(1,10) 1,2,3,4,5,6,7,8,9
range(3,7) 3,4,5,6
range(2,15,3) 2,5,8,11,14
range(9,2,-1) 9,8,7,6,5,4,3
Q. Write a program that prints out a list of the integers from
1 to 20 and their squares. The output should look like this:
1 --- 1
2 --- 4
3 --- 9 for i in range(1,21):
... print(i,'---',i*i)
20 --- 400
# try this
for i in range(1,21):
print(‘*’*i)
6/24/2021 Department of Physics, PU: SP Gupta 20
Multiplication table
for i in range(1,11): for i in range(1,11):
for j in range(1,11): for j in range(1,11):
print((i*j),end=' ') print('{:3d}'.format(i*j),end=' ')
print() print()
# try putting more print() # try putting more print()
if statement
if statement: when we only want to do something provided something else is true
Conditional operators
The comparison operators are ==, >, <, >=, <=, and !=. That last one is for
not equals. Here are a few examples:
Expression Description
if x>5: if x is greater than 5
if x>=5: if x is greater than or equal to 5
if x==5: if x is 5
if x!=5: if x is not 5
There are three additional operators used to construct
more complicated conditions: and, or, and not
6/24/2021 Department of Physics, PU: SP Gupta 21
Order of operations: and is done before or, so if you have a complicated condition
that contains both, you may need parentheses around the or condition.
a=eval(input('Enter your marks:')) a=eval(input('Enter your marks:'))
if a>=60 and a<=80: if a>=60 or a<=80:
print('your grade is B') print('your grade is B')
a=eval(input('Enter your marks:'))
if a!=60 or a!=80:
print('your grade is B')
marks = eval(input('Enter your score: '))
if marks >=90:
print('A')
if marks >=80 and marks<90:
print('B')
if marks >=70 and marks<80:
print('C')
if marks >=60 and marks<70:
print('D')
if marks <60:
print('F')
6/24/2021 Department of Physics, PU: SP Gupta 22
elif statement
marks = eval(input('Enter your score: '))
if marks >=90:
print('A')
elif marks >=80:
while statement print('B')
elif marks >=70:
count = 0 print('C')
while (count < 9): elif marks >=60:
print('The count is:', count) print('D')
count = count + 1 else:
print('bye!') print('F')
var = 1
while var == 1: # This constructs an infinite loop
num=eval(input('Enter a number :'))
print('You entered:', num)
print('Good bye!')
6/24/2021 Department of Physics, PU: SP Gupta 23
Assignments
Write a Python code:
Question 1: Take two numbers (a & b) in input and print the following
Sum (a+b)
Product (axb)
a power b
a modulo b
Question 2: Take a number in input and check whether number is odd or even.
Question 3: Print the alphabets from A to F with star (*).
Question 4: Print the numbers from 1 to 10 with star (*).
6/24/2021 Department of Physics, PU: SP Gupta 24