Python Programming
Python Programming
[Link]. PHYSICS
(THIRD SEMESTER)
Course- MPSEC-1
Course: MPSEC-01
Python Programming (Theory)
i
Programme Name: [Link]. Physics Semester: Third Semester
Course Code: MPSEC-01 Course Name: Python Programming (Theory)
Credit: 2 Total Number of Units : 08 units
EXPERT COMMITTEE
Vice Chancellor Prof. Sharanappa V. Halse Chairman
Dean (Academic) Prof. Lakshmi. N. Member
Course Coordinator Mr. S. V. Niranjana Member
Department Chairman Mr. S. V. Niranjana Member
COURSE EDITORIAL BOARD
BOS Chairman Prof. S. Krishnaveni Chairperson
External Expert Prof. T. Shivalingaswamy Member
Internal Expert Mr. S. V. Niranjana Member
Department Chairman Mr. S. V. Niranjana Member
COURSE PREPARATION TEAM
COURSE WRITER COURSE: MPSEC-01
Python Programming (Theory)
Dr. Chandra
Assistant Professor, Department of Physics, The National Block –A and Block-B
Institute of Engineering, Mananthavadi Road, Mysuru -08 (Unit 1 to Unit 8)
Course Editor: Mr. S.V. Niranjana, Assistant Professor, Department of Studies in Physics,
Karnataka State Open University, Mukthagangothri, Mysuru-06
Content Formatting: Mr. S. V. Niranjana
Publication coordinator:
Dr. Santhosh Naik. R., Director, Prasaranga (University Publication), KSOU, Mysuru-06
ISBN: 978-93-6011-771-9
@ Karnataka State Open University, 2024
All rights reserved. No part of this work may be reproduced in any form or any other means,
without permission in writing from the Karnataka State Open University.
Further information on the Karnataka State Open University Programmes may be obtained from
the University’s Office at Mukthagangothri, Mysuru – 570 006
Or visit our website: [Link]
Disclaimer: The opinions expressed in this publication are those of the authors.
Pages: 110 Cover Design: Mr. S. V. Niranjana
Printed on behalf of the Karnataka State Open University, Mysuru, by The Registrar, KSOU,
Mysuru-570006
ii
TABLE OF CONTENTS
Page No.
BLOCK-A
Introduction to python programming, Variables, Operators and Data types,
Operations on data types; Input and Output statements, Precedence and 1-16
Unit-1
Associativity, Comments, Type Conversions
Decision control flow statements (if, if…else, if…elif…else, Nested if, Types of
Unit-2 Looping statements - while and for loop, Nested loops, Break and Continue 17-28
Statements.
Functions: Modules, Built-in functions, User defined functions, Scope and
Unit-3 lifetime of variables, Default parameters, Keyword arguments. Strings- Creating 29-45
and storing strings, Basic String operations, Formatting strings.
Lists-Basic list operations, Slicing and indexing, List methods. Dictionaries-
creating dictionaries, Dictionary methods, Tuples and sets- creating/indexing and
Unit-4 46-63
slicing/tuple methods and set methods. Introduction to numpy and matplotlib for
basic plotting
BLOCK-B
iii
PRELUDE
Python has rapidly emerged as one of the most popular and versatile programming languages
in recent years, owing to its simplicity, readability, and vast ecosystem of libraries. It is a
language of choice for beginners, yet powerful enough to drive innovation in fields like web
development, data science, machine learning, and artificial intelligence. The increasing
demand for Python skills across industries reflects its significance in the ever-evolving world
of technology.
This course aims to provide a solid foundation for anyone beginning their journey into
Python programming. Starting from the fundamentals, such as variables, operators, and data
types, it gradually delves into more complex topics like control flow, loops, functions, and
working with strings, lists, and dictionaries. Each concept is introduced with practical
examples and clear explanations, ensuring that learners grasp the essential building blocks of
Python. Moreover, special attention is given to Python's key features, such as modules, built-
in functions, and user-defined functions, which are crucial for creating reusable, organized,
and efficient code. The course also covers advanced topics like type conversions, precedence,
and associativity, which allow learners to understand the nuances of Python's execution flow.
As we navigate through the various elements of Python, from input/output statements to
decision control and looping structures, this course provides a structured path that transforms
novice programmers into confident Python developers, capable of tackling real-world
problems with elegance and precision.
Further, this course is designed to introduce and apply Python to key mathematical and
scientific concepts that are crucial for students and professionals alike. It begins with Arrays
and Matrix Computation, fundamental tools for handling large datasets and performing linear
algebra operations such as matrix inversion, eigenvalue problems, and Fourier transforms.
These techniques are the backbone of many computational fields, including physics,
engineering, and machine [Link] course then transitions into more advanced
applications through a series of problem-solving methods under Applications of Python-1.
Here, Python is used to tackle systems of linear equations, solve eigenvalue problems, and
efficiently compute fast Fourier transforms—an essential tool in signal processing and time-
series analysis. In Applications of Python-2, we dive into numerical methods for solving
iv
differential equations and non-linear systems. Techniques such as the Euler method, Runge-
Kutta methods, Gauss-Seidel method, Newton-Raphson method, and bisection and secant
methods are explored. These numerical approaches form the core of applied mathematics,
enabling solutions to problems that are otherwise intractable analytically. Finally,
Applications of Python-3 extends Python’s use to real-world physics simulations. By
applying Python to classical mechanics (simple and double pendulums, planetary motion, and
projectile motion), as well as electrical circuits and quantum mechanics (Planck’s law,
Heisenberg’s uncertainty relation), learners gain hands-on experience in modeling and
simulating physical phenomena. These applications highlight Python’s versatility in both
classical and modern physics, bridging the gap between theory and experimentation.
v
MPSEC-1 Physics KSOU
UNIT-1
1
MPSEC-1 Physics KSOU
1. Academia: Python is being used in research at a faster rate than ever before, and it is
competing with MATLAB for the coveted title of most popular research language.
2. Scientific Tools: Simulation and analysis of complex systems can only be done with
the help of scientific tools. SciPy library, NumPy, Jupyter, Sympy, and Matplotlib are
the main scientific packages that make up the Python ecosystem.
3. Machine Learning: Scikit-Learn is a well-known Machine Learning tool that is built
on top of other Python scientific tools like NumPy, SciPy, and Matplotlib. This makes
it easy for new models to be added to Scikit-Learn. Scikit-Learn works with different
models for Classification, Regression, Clustering, Model Selection, Dimensionality
Reduction, and Pre-processing.
4. Natural Language Processing: The well-known Python module for natural language
processing is called Natural Language Toolkit (NLTK).
5. Data Analysis: The Pandas library changed everything about how data is analysed in
Python. Pandas is built on top of NumPy and has two important data structures: Series
and DataFrame. It can store any kind of data, like integers, floats, strings, objects, and
more.
6. Statistics: A Python library called Statsmodels is used to look at statistics. It works
with different models and features, such as linear aggression models, generalised
linear models, discrete choice models, and functions for time series analysis.
Statsmodels is tested thoroughly by comparing it to other statistical packages. This is
done to make sure that the results are correct. Pandas and Statsmodels can both be
used to fit statistical models.
7. Hypertext Transfer Protocol (HTTP) Library: People often call the "Requests
HTTP" library the "library written for people." Most HTTP operations can be done
with Python's standard HTTP library named ‘urllib. request’. But that library’s
2
MPSEC-1 Physics KSOU
Application Programming Interfaces (APIs) are hard to use and have a lot of words.
To solve these problems, a separate library called "Requests HTTP" was made.
Common HTTP verbs like POST, GET, PUT, and DELETE, which stand for create,
read, update, and delete, are all fully supported.
8. Database Connectors/ORM/NoSQL Connectors: Database connectors are drivers
that let us query about the database directly from the programming language. Most
people use MySQL and PostgreSQL, which are open-source databases. Oracle's
MySQL-Python-Connector for Python is the most-used Python connector for
MySQL, while Psycopg2 is the most-used Python connector for PostgreSQL.
9. Web Frameworks: The most used web frameworks are Django and Flask. Both have
different purposes. Flask is a microframework that is used to build small applications
with few needs. It is different from Django, which is a full-fledged framework.
Django has built-in support for caching, internationalisation, serialisation, ORM
support, and an automatic admin interface. Flask, on the other hand, lets users install
external libraries to configure web services to their needs.
10. Cloud Computing: OpenStack is written entirely in Python, and it is used to make
both public and private clouds that can grow as needed. OpenStack Foundation is in
charge of making sure that OpenStack software gets made. Several cloud service
providers, such as Google App Engine, Amazon Web Services (AWS), Heroku, and
Microsoft Azure, make it easy to host Python apps in the cloud.
Note:
In the following document, Python of version 3.9.6 and IDE as Visual Studio Code is used.
Ans also to show the syntax and working the Python Interactive mode is used as well. The
three greater-than signs “>>>” is the primary prompt of the interactive mode.
1.1 VARIABLES
A variable is a place holder with a name that can hold any kind of data that the
program can use to assign and change as it runs. In Python, to create a new variable, we just
give it a name and a value. There is no need to explicitly mention the data types of the
variables we define.
Rules to follow when making a variable:
• Variable names can consist of any number of letters, underscores and digits.
• Variable should not start with a number.
3
MPSEC-1 Physics KSOU
4
MPSEC-1 Physics KSOU
5
MPSEC-1 Physics KSOU
2. Assignment Operators: Assignment operators are used to set the value of the right
operand to the value of the left operand after the right operand is evaluated. Assignment
operations always go from right to left.
6
MPSEC-1 Physics KSOU
3. Comparison Operators: Comparison operators are used for comparing the values of two
operands. These comparison operators always produce the Boolean value True or False as
their output. The operands can be either Boolean values or Numbers, Strings (Strings are
compared letter by letter using their ASCII values), or Strings.
7
MPSEC-1 Physics KSOU
4. Logical Operators: In order to compare or negate the logical values of their operands and
return the new logical value, logical operators are needed. The operand values that the logical
operators work with evaluate to True or False. The logical operator's output is always a
Boolean value, either True or False.
As logical expressions are evaluated left to right, they are tested for possible “shortcircuit”
valuation using the following rules:
1. False and (some_expression) is short-circuit evaluated to False.
2. True or (some_expression) is short-circuit evaluated to True.
The rules of logic guarantee that these evaluations are always correct. The some_expression
part of the above expressions is not evaluated, so any side effects of doing so do not take
effect.
8
MPSEC-1 Physics KSOU
5. Bitwise Operators: Bitwise operators carry out bit-by-bit operations on their operands,
which are treated as a series of bits (zeroes and ones). For instance, the binary equivalent of
the decimal number ten is 1010. Such binary representations are used for the operations of
bitwise operators, which return standard Python numerical values.
9
MPSEC-1 Physics KSOU
1.4 COMMENTS
A comment is text that the Python interpreter ignores and indicates what the
program or a specific section of the program is trying to do. Programmers can
comprehend, maintain, and debug the software with the aid of comments. Single-line
and multiline comments are both supported in Python.
Use the hash (#) symbol to begin creating a comment in Python. All content after the
hash (#) symbol on the same line becomes a comment. For instance,
# This Python comment is one-line long.
10
MPSEC-1 Physics KSOU
The use of triple quotes, either "' or "', is a method for making multiline comments.
Multiline strings typically employ these triple quotes. They can also be used as a
multiline comment, though. For instance,
'''This is
multiline comment
in Python using triple quotes'''
11
MPSEC-1 Physics KSOU
d. Send
Ans: b
12
MPSEC-1 Physics KSOU
13
MPSEC-1 Physics KSOU
automatic admin interface. Flask, on the other hand, lets users install external libraries to
configure web services to their needs.
10. Cloud Computing: OpenStack is written entirely in Python, and it is used to make
both public and private clouds that can grow as needed. OpenStack Foundation is in
charge of making sure that OpenStack software gets made. Several cloud service
providers, such as Google App Engine, Amazon Web Services (AWS), Heroku, and
Microsoft Azure, make it easy to host Python apps in the cloud.
14
MPSEC-1 Physics KSOU
15
MPSEC-1 Physics KSOU
1.8 REFERENCE
1. Gowrishankar.S., & Veena.A. (2018). Introduction to Python Programming. CRC
press
2. Chun, W. (2001). Core python programming (Vol. 1). Prentice Hall Professional.
16
MPSEC-1 Physics KSOU
UNIT-2
2.0 Control Flow Statements
2.1 Nested if Statement
2.2 while Loop
2.3 for Loop
2.4 continue and break Statements
2.5 Check your progress
2.6 Review Questions
2.7 References
17
MPSEC-1 Physics KSOU
18
MPSEC-1 Physics KSOU
The if statement starts with the keyword "if" and ends with a colon. In an if statement, the
expression should be a Boolean expression. Based on the value of the Boolean_Expression,
the if statement decides whether or not to run a certain statement. If the result of the
Boolean_Expression is True, the statements in the if block will be run. If the result is False,
none of the statements will be run. In Python, the if block statements are shown by how much
they are indented, and the end is shown by the first statement that is not indented.
Program:
Output:
19
MPSEC-1 Physics KSOU
Program:
Output:
20
MPSEC-1 Physics KSOU
Program:
21
MPSEC-1 Physics KSOU
Output:
22
MPSEC-1 Physics KSOU
Output:
The while keyword is used to begin the while loop and a colon to stop it. When using a while
statement, the Boolean_Expression is initially evaluated before the statements in the while
loop block are carried out. The statements in the while loop block are never executed if the
Boolean_Expression evaluates to False. The while loop block is run if the
Boolean_Expression evaluates to True. The Boolean_Expression is once more verified
following each iteration of the loop block, and if it is True, the loop is iterated once more. An
iteration of the loop is when the loop block is run more than once. This process keeps going
until the Boolean expression evaluates to False, at which point the while statement ends.
After the while loop, the first statement that came before it is run again.
Program:
Output:
23
MPSEC-1 Physics KSOU
The for loop is made up of the for keyword and a colon at the end. Iteration variable iteration
variable is allotted the first item in the sequence. In this case, iteration_variable can be any
name for a valid variable. After that, the statement block is run. This process of assigning
items from the sequence to the iteration variable and then running the statement continues
until all the items in the sequence are done. The following program demonstrates the different
ways on how ‘for’ loop can be used.
Program:
Output:
24
MPSEC-1 Physics KSOU
Program:
Output:
a. Iterative
b. Conditional
c. multi-way
d. All of these
Ans: a
2. Which keyword is used to take the control to the beginning of the loop?
a. exit
b. break
25
MPSEC-1 Physics KSOU
c. continue
d. None of these
Ans: c
for Loop:
The syntax for the for loop is,
The for loop is made up of the for keyword and a colon at the end. Iteration variable
iteration variable is allotted the first item in the sequence. In this case, iteration_variable
26
MPSEC-1 Physics KSOU
can be any name for a valid variable. After that, the statement block is run. This process
of assigning items from the sequence to the iteration variable and then running the
statement continues until all the items in the sequence are done. The following program
demonstrates the different ways on how ‘for’ loop can be used.
Program:
Output:
With the break and continue statements, you have more control over how the code in a loop
is run. When the break statement is found, the control immediately moves to the first
instruction after the loop. Use the continue statement to move on to the next iteration
without exiting the loop. In while and for loops, you can use both continue and break.
27
MPSEC-1 Physics KSOU
Output:
4. Write a Program to Find the Average of n Natural Numbers where n Is the Input
from the User, by using while loop:
Output:
2.7 REFERENCE
1. Gowrishankar.S., & Veena.A. (2018). Introduction to Python Programming. CRC
press
2. Chun, W. (2001). Core python programming (Vol. 1). Prentice Hall Professional.
28
MPSEC-1 Physics KSOU
UNIT-3
3.0 Functions and Strings
3.1 Built-In Functions
3.2 User-Defined Functions
3.3 Scope and Lifetime of Variables
3.4 Default Parameters
3.5 Keyword Arguments
3.6 Strings
3.6.1 Creating and Storing Strings
3.6.2 Basic String Operations
3.6.3 Formatting Strings
3.7 Check your progress
3.8 Review Questions
3.9 Reference
29
MPSEC-1 Physics KSOU
30
MPSEC-1 Physics KSOU
A function definition is introduced using the keyword def. The variables listed in the function
specification are referred to as parameters or formal parameters.
A function definition in Python consists of the def keyword followed by
1. The function's name. The name of the function has to follow the same rules as the
names of variables: it can be a letter, a number, or an underscore, but it can't start with
a number. Also, you can't name a function with a keyword.
2. A list of the function's parameters is put inside parentheses and separated by commas.
Some functions have no parameters at all, while others may have one or more.
31
MPSEC-1 Physics KSOU
3. At the end of the function header, there needs to be a colon. The name of the function
is written on the first line of the function definition. This line is called the function
header.
4. The blocks of statements that make up the function body begin on the line after the
function header and must all be indented to the same depth.
function_name(argument_1, argument_2,…,argument_n)
The actual value given to the calling function is known as an argument. The formal
parameters in the definition of the function and the actual arguments passed to the calling
function must match exactly one to one. The formal parameters are temporarily "bound" to
the arguments when a function is called, and the calling function assigns the parameters'
initial values.
A function should be defined before it is called, and only after the function has been
called should the block of statements in the function definition be executed.
The way a program runs is not changed by the definition of a function. Control is transferred
from the caller function to the function definition when you call a function. Following the
execution of the block of statements contained in the function definition, control is returned
to the caller function, which then executes the subsequent statement. The Python interpreter
keeps track of the control flow between various program statements.
The Python interpreter automatically defines a few unique variables before running
the source code. The Python interpreter assigns the special built-in __name__ variable to
have the string value "__main__" if it is running the source code as a standalone main
program.
The Python interpreter scans the program and runs the code it finds after creating these
special variables. The entire block of code with an indentation level of 0 is run. If the
function is not called, a block of statements in the function definition are not carried out.
if __name__ == "__main__":
statement(s)
32
MPSEC-1 Physics KSOU
The entry point to your programme is the special variable with the value "__main__,"
__name__. The block of statements in the if statement will be executed by the Python
interpreter when it scans the statement and determines that __name__ equal "__main__."
Output:
33
MPSEC-1 Physics KSOU
variable has no impact on the global variable. Within the function in which it is defined, only
the local variable has any significance.
Output:
34
MPSEC-1 Physics KSOU
Output:
35
MPSEC-1 Physics KSOU
Output:
3.6 STRINGS
Another fundamental data type offered by Python is strings. They are made up of one or
more characters enclosed in appropriate quotation marks. A string is made up of a series of
characters, which can be any combination of letters, numbers, punctuation, and spaces. You
can use a single quotation, double quote, or triple quote to denote strings.
36
MPSEC-1 Physics KSOU
37
MPSEC-1 Physics KSOU
String Comparison:
Two strings can be compared using (>, <, <=, >=, ==, !=) to get a Boolean True or False
value. Python compares strings using the characters' ASCII values. Different comparison
operators can be used to compare strings. Using ‘= =’, strings are compared for equality
(double equal sign). The ‘! =’ sign is used to compare string inequality. Even an empty string
can be used to compare strings.
38
MPSEC-1 Physics KSOU
Format Specifiers:
Evaluated expressions may also be seen in format specifiers. The syntax for an
operation that formats an f-string is,
39
MPSEC-1 Physics KSOU
Escape Sequences:
Escape sequences consist of a backslash (/) and either a letter or a letter and digit
combination. Control sequences are another name for escape sequences.
By replacing the particular meaning of the characters that follow it with a different
interpretation, the backslash (\) character is utilised to escape the meaning of the characters
that follow it. Therefore, every escape sequence has two or more characters.
Raw Strings:
The character r is added before the string to make it a raw string. In Python, a raw string
ignores any formatting, including escape characters, that may be present.
Unicodes:
40
MPSEC-1 Physics KSOU
Every character in the Unicode Standard has a specific number, independent of the
platform, gadget, programme, or language. As a result of its widespread adoption by
contemporary software vendors, data may now be sent without corruption across a wide
range of platforms, gadgets, and programmes.
Different character encodings can be used to implement Unicode. Numerous additional
encodings are in use, and the Unicode Standard provides Unicode Transformation Formats
such UTF-8, UTF-16, and UTF-32. The three encodings that are most frequently used are
UTF-8, UTF-16, and UCS-2 (Universal Coded Character Set), which is a forerunner to UTF-
16.
Normal Python strings are just bytes; they are not Unicode. Use the 'u' prefix on the string
literal to produce a Unicode string.
41
MPSEC-1 Physics KSOU
Ans: c
4. The two types of functions used in Python are
a. Built-in and user-defined
b. Custom function and user function
c. User function and system call
d. System function
Ans: a
Ans: User-defined functions are reusable code snippets that users design to carry out
particular tasks within the application.
A function definition is introduced using the keyword def. The variables listed in the
function specification are referred to as parameters or formal parameters.
The syntax for function definition is,
42
MPSEC-1 Physics KSOU
A function is not executed when it is defined. A function is simply defined when it is given a
name and instructions on what to perform when it is called. The given actions are really
carried out with the specified parameters when the function is called.
The syntax for function call or calling function is,
function_name(argument_1, argument_2,…,argument_n)
The actual value given to the calling function is known as an argument. The formal
parameters in the definition of the function and the actual arguments passed to the calling
function must match exactly one to one. The formal parameters are temporarily "bound" to
the arguments when a function is called, and the calling function assigns the parameters'
initial values.
2. List all the escape characters in Python with examples.
Ans: Escape sequences consist of a backslash (/) and either a letter or a letter and digit
combination. Control sequences are another name for escape sequences.
By replacing the particular meaning of the characters that follow it with a different
interpretation, the backslash (\) character is utilised to escape the meaning of the characters
that follow it. Therefore, every escape sequence has two or more characters.
43
MPSEC-1 Physics KSOU
3. Write Python Program to Calculate the Length of a String without Using Built-In
len() Function:
Program:
Output:
Program:
44
MPSEC-1 Physics KSOU
Output:
3.9 REFERENCE
1. Gowrishankar.S., & Veena.A. (2018). Introduction to Python Programming. CRC
press
2. Chun, W. (2001). Core python programming (Vol. 1). Prentice Hall Professional.
45
MPSEC-1 Physics KSOU
UNIT-4
46
MPSEC-1 Physics KSOU
If the index value exceeds the number of items in the list, “IndexError: list index out
of range” error is generated. You can also access list items with negative index numbers by
counting backwards from the end of the list, beginning with -1. Negative indexing is handy
when searching for an item at the conclusion of a lengthy list.
47
MPSEC-1 Physics KSOU
Lists are mutable in nature because the list items can be changed after the list has been
formed.
A list can be changed without assigning the list to an entirely new variable by simply
swapping out an older item with a newer one.
An assignment (=) on lists does not create a new copy when a variable that already
contains a list is assigned to a new variable. Assignment, on the other hand, causes both
variable names to refer to the same list in memory.
48
MPSEC-1 Physics KSOU
Python supports list slicing, where a portion of the list can be extracted by specifying
an index range and the colon (:) operator, which is a list in and of itself.
The list slicing syntax is,
list_name[start: stop: [step]]
The values start and stop are also integers (positive or negative values). List slicing
returns a portion of the list from start index to stop index, which includes start index but
excludes stop index. Step is an optional specification of the increment value to slice by.
49
MPSEC-1 Physics KSOU
4.3 DICTIONARIES
4.3.1 CREATING DICTIONARY
A dictionary is a collection of key: value pairs that are not ordered and for which the keys
must be distinct within the dictionary. Using curly braces, dictionaries are created by
including a list of key: value pairs separated by commas. The words to the left of the colon
50
MPSEC-1 Physics KSOU
operator are the keys, and the words to the right of the colon operator are the values. Each of
these key and value pairs is also separated by a colon (:). Dictionary entries are indexed by
keys as opposed to lists, which use a range of numbers. A key:value pair in this context refers
to a key and the value it corresponds to. Case matters when using dictionary keys.
The syntax for creating a dictionary is,
dict_name={key_1:value_1, key_2:value_2,…….key_n:value_n}
Dictionary keys can be either a string or an integer and are of the immutable type. You cannot
use lists as keys since they can be altered on the fly via index assignments, slice assignments,
or operations like append() and extend(). The dictionary does not permit duplicate keys. The
placement of key:value pairs in dictionaries is irrelevant.
51
MPSEC-1 Physics KSOU
52
MPSEC-1 Physics KSOU
4.4 TUPLES
4.4.1 CREATING TUPLES
Tuples are used to group related items without having to develop a special type to carry
them. Tuples are a finite ordered list of values of potentially different types. Tuples can never
be altered. A tuple's values cannot be altered once it has been generated. A comma-separated
collection of values enclosed in parentheses () designates a tuple. A tuple's individual values
are referred to as items.
The syntax for creating a tuple is,
tuple_name = (item_1, item_2, ...., item_n)
Any object, string, number, variable, object, or even another tuple itself can be stored. Tuples
don't have to be homogeneous and can contain a variety of various kinds of elements.
53
MPSEC-1 Physics KSOU
If the index value exceeds the number of items in the tuple, “IndexError: tuple index out of
range” error is generated. You can also access tuple items with negative index numbers by
counting backwards from the end of the tuple, beginning with -1. Negative indexing is handy
when searching for an item at the conclusion of a lengthy tuple.
Python supports tuple slicing, where a portion of the tuple can be extracted by specifying an
index range and the colon (:) operator, which is a tuple in and of itself.
The tuple slicing syntax is,
tuple_name[start: stop: [step]]
The values start and stop are also integers (positive or negative values). Tuple slicing returns
a portion of the tuple from start index to stop index, which includes start index but excludes
stop index. Step is an optional specification of the increment value to slice by.
54
MPSEC-1 Physics KSOU
55
MPSEC-1 Physics KSOU
The most crucial item in NumPy is the ‘ndarray’ since it aids in array creation. These are
zero-based indexed arrays. Consecutive memory regions are assigned to the array's
component elements. ‘[Link]’ is a Python function that can be used to generate a
simple array.
The following arguments are accepted by the function:
object: It returns an array or nested sequence.
dtype: Dtype identifies the data type of the array.
copy: If this argument's value is true, the object is copied.
order: An array can have any order, including row major (C) or column major (F) or
any (A)
subok: Returned array forced is to be a base class array
56
MPSEC-1 Physics KSOU
A list L with n values (indexed 0 to (n-1)) can be supplied to the plot function to create a
simple plot. The x-axis in the resulting plot will have values ranging from 0 to (n-1) while the
Y-axis will display the values from the supplied list. A label is connected to the X-axis by the
xlabel function. A string is the xlabel function's argument. A label is connected to the Y-axis
using the ylabel function. The figure is displayed via the show function. The savefig function
can be used to save the figure as well.
57
MPSEC-1 Physics KSOU
patterns, and relationships. Typically, these are instruments for reasoning with quantitative
data. Matplotlib has numerous plots, including line, bar, scatter, and histogram, among
others.
Matplotlib offers an object-oriented API for incorporating plots into Python GUI toolkits
such as PyQt, WxPython, and Tkinter. It is also compatible with IPython shells, Jupyter
notebooks, and web application servers.
Matplotlib features a procedural interface called Pylab, which is supposed to emulate
MathWorks' proprietary programming language MATLAB. Matplotlib and NumPy are the
open-source alternatives to MATLAB.
58
MPSEC-1 Physics KSOU
1. Explain the ways of indexing and slicing the list with examples:
Ans: Through indexing, a list's items can be called individually as an ordered series of
elements. The expression included within the bracket is known as the index. With the first
item at index 0, the second at index 1, and so on, lists employ square brackets [] to access
individual items. The value being accessed is indicated by the index given within the square
brackets.
The syntax for gaining access to a list item is,
list_name[index]
where index always denotes the item to be picked and should be an integer number.
If the index value exceeds the number of items in the list, “IndexError: list index out of
range” error is generated. You can also access list items with negative index numbers by
counting backwards from the end of the list, beginning with -1. Negative indexing is handy
when searching for an item at the conclusion of a lengthy list.
Lists are mutable in nature because the list items can be changed after the list has been
formed.
A list can be changed without assigning the list to an entirely new variable by simply
swapping out an older item with a newer one.
59
MPSEC-1 Physics KSOU
An assignment (=) on lists does not create a new copy when a variable that already contains a
list is assigned to a new variable. Assignment, on the other hand, causes both variable names
to refer to the same list in memory.
Python supports list slicing, where a portion of the list can be extracted by specifying an
index range and the colon (:) operator, which is a list in and of itself.
The list slicing syntax is,
list_name[start: stop: [step]]
The values start and stop are also integers (positive or negative values). List slicing returns a
portion of the list from start index to stop index, which includes start index but excludes stop
index. Step is an optional specification of the increment value to slice by.
60
MPSEC-1 Physics KSOU
Dictionary keys can be either a string or an integer and are of the immutable type. You cannot
use lists as keys since they can be altered on the fly via index assignments, slice assignments,
or operations like append() and extend(). The dictionary does not permit duplicate keys. The
placement of key:value pairs in dictionaries is irrelevant.
61
MPSEC-1 Physics KSOU
Output:
Output:
62
MPSEC-1 Physics KSOU
4.10 REFERENCE
1. Gowrishankar.S., & Veena.A. (2018). Introduction to Python Programming. CRC
press
2. Chun, W. (2001). Core python programming (Vol. 1). Prentice Hall Professional.
63
MPSEC-1 Physics KSOU
UNIT-5
5.0 Arrays
5.1 Matrix Computation
5.1.1 Inner Product
5.1.2 Dot Product
5.2 Linear Algebra Operations
5.2.1 Transpose
5.2.2 Trace
5.2.3 Determinant
5.3 Check your progress
5.4 Worked Examples
5.5 Reference
64
MPSEC-1 Physics KSOU
5.0 ARRAYS
5.1 MATRIX COMPUTATION
Python's Numpy is typically used to do numerical calculations. For matrix operations, it
also provides specialised classes and sub-packages. By reducing numerous for loops,
vectorization enables numpy to process matrix operations more quickly.
Matrixes and ndarrays are two distinct concepts in numpy. Numpy has common functions as
well as special functions devoted to linear algebra, for instance, the linalg package has some
special functions devoted to linear algebra. Matrix and ndarray dimensions should always be
verified.
65
MPSEC-1 Physics KSOU
66
MPSEC-1 Physics KSOU
67
MPSEC-1 Physics KSOU
5.2.2 TRACE
In a square matrix, the trace is the total of the diagonal elements. The trace can be
calculated using one of two methods. We can simply obtain the diagonal elements first, and
then the sum, using the ndarray object's trace() method.
Program of Trace:
Output of Trace:
68
MPSEC-1 Physics KSOU
5.2.3 DETERMINANT
The det() function, which is part of the numpy linalg package, can be used to calculate the
determinant of a square matrix. The matrix cannot be inverted if the determinant is 0. In
algebraic terms, it is referred to as a singular matrix.
69
MPSEC-1 Physics KSOU
70
MPSEC-1 Physics KSOU
71
MPSEC-1 Physics KSOU
5.5 REFERENCE
1. Gowrishankar.S., & Veena.A. (2018). Introduction to Python Programming. CRC
press
2. Landau, R. H., Páez, M. J., & Bordeianu, C. C. (2015). Computational physics:
Problem solving with Python. John Wiley & Sons.
72
MPSEC-1 Physics KSOU
UNIT-6
73
MPSEC-1 Physics KSOU
There is overlap in the functionality offered by the SciPy and NumPy submodules, and
the SciPy library also includes a linalg submodule. SciPy has functions that are absent from
[Link], including those that deal with the Schur and LU decompositions, various
methods for computing the pseudoinverse, and matrix transcendentals like the matrix
logarithm. In [Link], several functions that are present in both have expanded
functionality. To solve generalised eigenvalue problems, for instance, [Link] can
accept a second matrix parameter. However, some NumPy functions offer more adaptable
broadcasting options. For instance, although [Link] only accepts a single square
array as its initial input, [Link] can handle "stacked" arrays.
74
MPSEC-1 Physics KSOU
In this system, there are three linear equations. The same set of variables termed x, y, and z
are present in each equation. Finding values for x, y, and z that satisfy all the equations is
what it means to solve this linear system, if it exists.
75
MPSEC-1 Physics KSOU
We employ the solve() function from the NumPy ‘linalg’ sub package to resolve this linear
system.
Program:
Output:
76
MPSEC-1 Physics KSOU
In this linear system the coefficient matrix is a singular matrix and hence no solution exist for
this system of linear equations. If python program is run for this linear system then python
throws an Exception as the following ‘[Link]: Singular matrix’.
Program:
77
MPSEC-1 Physics KSOU
Output:
Output:
78
MPSEC-1 Physics KSOU
Program:
Output:
79
MPSEC-1 Physics KSOU
The trace of the same matrix (2+3+2=7) is the same as the sum of the eigenvalues
(1+5+1=7). The determinant (5) of the same matrix is the same as the product of the
eigenvalues (1x5x1=5).
Principal Component Analysis makes extensive use of eigenvalues and eigenvectors (PCA).
In PCA, the principal components (the directions of maximum variance) are represented by
the eigenvectors of the correlation or covariance matrix, and the corresponding eigenvalues
are used to calculate how much variation is explained by each principal component.
6.5 FFT
Fundamentally, Fourier analysis is a technique for summarising periodic components
to represent a function and recovering the function from those components. The discrete
Fourier transform is what happens when discretized versions of the function and its Fourier
transform are used instead (DFT). The Fast Fourier Transform (FFT), which was first
introduced by Cooley and Tukey and was known to Gauss (1805), is a highly quick approach
for computing the DFT and has become a mainstay of numerical computing.
The discrete Fourier transform is used in many different applications in digital signal
processing, such as filtering, because it divides its input into components that contribute at
discrete frequencies. In this context, the discretized input to the transform is commonly
80
MPSEC-1 Physics KSOU
referred to as a signal because it exists in the time domain. The output, which exists in the
frequency domain, is known as a spectrum or transform.
Program:
Output:
81
MPSEC-1 Physics KSOU
82
MPSEC-1 Physics KSOU
The following program finds the maxima and minima of the given function. Here
function to which those values are computed are coded inside the function named ‘function
(x, y)’. Similarly change the function values according to the equation we want to the
compute those values.
Program:
Output:
83
MPSEC-1 Physics KSOU
Output:
2. Write a python program to solve the system of linear equation using numpy library
2x + y = 2z = -1
3x – 3y -z = 5
x – 2y + 3z = 6
84
MPSEC-1 Physics KSOU
Output:
Output:
Output:
85
MPSEC-1 Physics KSOU
6.9 REFERENCES
1. Ayars, E. (2013). Computational Physics With Python. California State University.
2. Landau, R. H., Páez, M. J., & Bordeianu, C. C. (2015). Computational physics:
Problem solving with Python. John Wiley & Sons.
86
MPSEC-1 Physics KSOU
UNIT-7
87
MPSEC-1 Physics KSOU
The following programs can be run by the following command in the terminal ‘python
file_name.py’ where ‘file_name’ is the name of the python file.
In this program x0 & y0 represents initial condition. xn is calculation point on which value
of yn corresponding to xn is to be calculated using Euler method. step represents number of
finite steps before reaching to xn.
After running the program in the terminal, it asks for initial conditions of ‘x’ and ‘y’,
calculation point ‘xn’ and the number of steps ‘n’.
88
MPSEC-1 Physics KSOU
89
MPSEC-1 Physics KSOU
In this program x0 & y0 represents initial condition. xn is calculation point on which value
of yn corresponding to xn is to be calculated using Runge-Kutta method. step represents
number of finite steps before reaching to xn.
After running the program in the terminal, it asks for initial conditions of ‘x’ and ‘y’,
calculation point ‘xn’ and the number of steps ‘n’.
90
MPSEC-1 Physics KSOU
In Gauss Seidel method, we first arrange given system of linear equations in diagonally
dominant form.
For example, if system of linear equations is:
After arranging equations in diagonally dominant form, we form equations for x, y, & z like
the following:
91
MPSEC-1 Physics KSOU
These equations are defined as three different functions f1(y, z), f2(x, z) and f3(x, y) as show
in the program below. Similarly, for other system of linear equations, rearrange them in
diagonally dominant form and code them in these 3 different functions.
In this program, initial conditions have been set as 0(zero) for x, y and z and count has been
set to 1, which can be modified according to the problem’s requirement.
After running the program in the terminal, it asks for tolerable error ‘e’.
92
MPSEC-1 Physics KSOU
In this python program, x0 is initial guess, e is tolerable error, f(x) is non-linear function
whose root is being obtained using Newton Raphson method.
After running the program in the terminal, it asks for initial guess ‘x0’, tolerable error ‘e’ and
maximum step ‘n’.
93
MPSEC-1 Physics KSOU
94
MPSEC-1 Physics KSOU
In this python program, x0 and x1 are two initial guesses, e is tolerable error and nonlinear
function f(x) is defined.
After running the program in the terminal, it asks for first initial guess ‘x0’, second initial
guess ‘x1’ and tolerable error ‘e’.
95
MPSEC-1 Physics KSOU
96
MPSEC-1 Physics KSOU
In this python program, x0 & x1 are two initial guess values, e is tolerable error and f(x) is
actual non-linear function whose root is being obtained using secant method.
Variable x2 holds approximated root in each step.
After running the program in the terminal, it asks for first initial guess ‘x0’, second initial
guess ‘x1’, tolerable error ‘e’ maximum step ‘n’.
97
MPSEC-1 Physics KSOU
2. Write a python program to solve the function f(x) = x3+4x2-10 using the Secant
method, where First Guess is 1, Enter Second Guess is 2, Tolerable Error is
0.000001, Maximum Step is 10.
Output:
98
MPSEC-1 Physics KSOU
3. Write a python program to solve the following system of equations using the
Gauss-Seidel method, where tolerable error is 0.0001
2x + y +z = 5
3x + 5y + 2z = 15
2x + y + 4z = 8
Output:
99
MPSEC-1 Physics KSOU
4. Write a python program to solve the following system of equations using the
Gauss-Seidel method, where tolerable error is 0.0000001.
x+y+z=7
x + 2y + 2z = 13
x + 3y + z = 13
Output:
100
MPSEC-1 Physics KSOU
7.8 REFERENCES
1. Kong, Q., Siauw, T., & Bayen, A. (2020). Python Programming and Numerical
Methods: A Guide for Engineers and Scientists. Academic Press.
2. Johansson, R., Johansson, R., & John, S. (2019). Numerical Python (Vol. 1). Apress.
101
MPSEC-1 Physics KSOU
UNIT-8
102
MPSEC-1 Physics KSOU
Program:
Output:
103
MPSEC-1 Physics KSOU
In the python program we calculate the ‘mean lifetime’ as well. We take the following as
inputs: Half-life of the element, Initial Mass of the element, Time for radioactive
disintegration.
Program:
Output:
104
MPSEC-1 Physics KSOU
Output:
The above equation is solved by Euler’s method and the graph is plotted using the matplotlib
library.
Program:
Output:
105
MPSEC-1 Physics KSOU
Output:
106
MPSEC-1 Physics KSOU
Velocity of an atom
The velocity of an atom moving across a surface is giving by using periodic model:
2 F0 x
v x v02 cos 1
m n
Where ‘m’ is mass, x is its position, v0 is initial velocity and n is scaled distance between the
atoms.
In this program we take inputs for mass, position, initial velocity, scaled distance and Force.
Program:
Output:
Projectile Motion
g
y tan x x2
2u cos
2 2
Where ‘y’ is the vertical displacement, ‘u’ is the initial velocity and ‘g’ is the gravity and ‘x’
is the horizontal displacement and theta is the angle of projection.
107
MPSEC-1 Physics KSOU
In this program horizontal displacement ‘x’ is the variable and be taken from the ‘linspace’
function from numpy library.
Program:
Output:
Program:
108
MPSEC-1 Physics KSOU
Output:
2. Write a python program to find the gravitational force between two bodies of mass
9kg and 11kg each and distance between them is 10 meters.
Program:
Output:
3. Write a python program to find the velocity of an atom moving across a surface is
giving by using periodic model, where mass is 5kg, position is 13m, initial velocity is
3m/s and scaled distance between the atoms is 4 and Force is 1N.
Program:
109
MPSEC-1 Physics KSOU
Output:
Output:
8.7 REFERENCES
1. Malthe-Sørenssen, A. (2015). Elementary mechanics using Python. Cham: Springer.
2. Moruzzi, G. (2020). Essential Python for the Physicist (p. 302). Cham: Springer
International Publishing.
110