0% found this document useful (0 votes)
4 views116 pages

Python Programming

The document outlines the M.Sc. Physics course MPSEC-01, which focuses on Python Programming and consists of eight units covering fundamental to advanced programming concepts. It provides a comprehensive introduction to Python, including variables, data types, control flow, functions, and applications in scientific computing and physics simulations. The course aims to equip learners with the skills necessary to apply Python in various fields, including data analysis, machine learning, and numerical methods.

Uploaded by

hari sree
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)
4 views116 pages

Python Programming

The document outlines the M.Sc. Physics course MPSEC-01, which focuses on Python Programming and consists of eight units covering fundamental to advanced programming concepts. It provides a comprehensive introduction to Python, including variables, data types, control flow, functions, and applications in scientific computing and physics simulations. The course aims to equip learners with the skills necessary to apply Python in various fields, including data analysis, machine learning, and numerical methods.

Uploaded by

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

KARNATAKA STATE OPEN UNIVERSITY

Mukthagangothri, Mysuru – 570006

[Link]. PHYSICS
(THIRD SEMESTER)

Course- MPSEC-1

Python Programming (Theory)


[Link]. PHYSICS
THIRD SEMESTER

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

Arrays: Matrix Computation, Linear Algebra Operations


Unit-5 64-72
Applications of Python-1: Systems of Equations: Linear Systems, matrix
Unit-6 inverse, eigenvalue problems, Fourier transforms: fast Fourier transform; maxima 73-86
and minima of functions.
Applications of Python-2: Euler method, Runge-Kutta methods, Gauss-Seidel
Unit-7 87-101
method, Newton-Raphson method, bisection method and Secant method.
Applications of Python-3: simple and double pendulums, Newton’s law of
Unit-8 gravitation, planetary motion, Projectile motion, Capacitor discharge in an RC 102-110
circuit, Planck’s law – plot ‘Planck curves’, Heisenberg’s uncertainty relation.

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.0 Introduction to Python Programming


1.1 Variables
1.2 Operators and Data Types
1.3 Precedence and Associativity
1.4 Comments
1.5 Type Conversions
1.6 Check your progress
1.7 Review Questions
1.8 References

1
MPSEC-1 Physics KSOU

1.0 INTRODUCTION TO PYTHON PROGRAMMING


Python 1.0, the first version of the language, came out in 1991. Python has grown and
changed since its start and the release of Version 1. It is now at Version 3.x (till 2018).
Python 2.0 came out on October 16, 2000. It had a lot of important new features and worked
with Unicode. The development process became more open and supported by the community
with this release. Python 3.0, which was first called Python 30a00 or py3k, came out on
December 3, 2008, after being tested for a long time.

Python is employed in the following fields:

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

• Python Keywords are not allowed as variable names.


• Variable names are case-sensitive. For example, computer and Computer are different
variables.

The general format for assigning values to variables is as follows:


variable_name = expression
 The equal sign (=) known as simple assignment operator is used to assign values to
variables. In the general, the operand to the left of the = operator is the name of the
variable and the operand to the right of the = operator is the expression which can be a
value or any code snippet that results in a value.
 Assignment operator should not be confused with the = used in algebra to denote
equality.
 While a Python program is running, not only can the value of a variable change, but
so can the type of data that is given to it.
 Python allows you to assign a single value to several variables simultaneously, for
example:
a = b = c =1

4
MPSEC-1 Physics KSOU

1.2 OPERATORS AND DATA TYPES


Operators are symbols, such as +, –, =, >, and <, that perform certain mathematical or
logical operation to manipulate data values and produce a result based on some rules.
Python language supports a wide range of operators. They are
1. Arithmetic Operators
2. Assignment Operators
3. Comparison Operators
4. Logical Operators
5. Bitwise Operators
1. Arithmetic Operators: To perform arithmetic operations like addition, subtraction,
division, multiplication, arithmetic operators are used. The list of arithmetic operators is
provided below:

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.3 PRECEDENCE AND ASSOCIATIVITY


The order in which operators are parsed in relation to one another is determined by
operator precedence. Higher precedence operators become the operands of lower precedence
operators. The way operators with the same precedence are parsed depends on associativity.
Nearly all operators are associative from left to right. In the table below, operator precedence
is sorted from highest precedence to lowest precedence in the table below.

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

1.5 TYPE CONVERSIONS


Python allows us to directly cast, or convert, a variable's type.
The type conversions available in Python are listed below:
 int() Function: Use the int() function to cast a number explicitly from a float or a
string to an integer.
 float() Function: The floating point number created from a number or string is
returned by the float() function.
 str() Function: The str() function gives back a string that is mostly readable by
humans.
 chr() Function: Convert an integer to a string of one character whose ASCII code is
same as the integer using chr() function. The integer value should be in the range of
0–255.
 complex() Function: To convert a string or number to a complex number, use the
complex() function. It will print a complex number with the value real + imag*j.
 ord() Function: The ord() function returns an integer representing Unicode code
point for the given
 Unicode character.
 hex() Function: Use the hex() function to transform an integer number (of any size)
into a lowercase, "0x"-prefixed hexadecimal string.
 oct() Function: Use the oct() function to transform an integer number (of any size)
into an octal string that is prefixed with "0o."

1.6 CHECK YOUR PROGRESS


1. Which Python library is popularly referred to as the HTTP library written for humans
a. Receive
b. Requests
c. Sockets

11
MPSEC-1 Physics KSOU

d. Send
Ans: b

2. Which operator returns the remainder of the operands?


a. /
b. //
c. %
d. **
Ans: c

3. Single-line comments start with the _____________ symbol.


a. *#
b. #
c. *
d. &
Ans: b

4. Multiline comments can be done by adding _____________ on each end of the


comment.
a. "' "'(triple quote)
b. # (Hash)
c. $ (dollar)
d. % (modulus)
Ans: a

1.7 REVIEW QUESTIONS


1. Explain the applications of Python in different fields:
Ans:
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.

12
MPSEC-1 Physics KSOU

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

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.

2. Define a variable. How to assign values to them?


Ans:
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.
• Python Keywords are not allowed as variable names.
• Variable names are case-sensitive. For example, computer and Computer are different
variables.

The general format for assigning values to variables is as follows:


variable_name = expression
 The equal sign (=) known as simple assignment operator is used to assign values to
variables. In the general, the operand to the left of the = operator is the name of the
variable and the operand to the right of the = operator is the expression which can be a
value or any code snippet that results in a value.
 Assignment operator should not be confused with the = used in algebra to denote
equality.
 While a Python program is running, not only can the value of a variable change, but
so can the type of data that is given to it..
 Python allows you to assign a single value to several variables simultaneously, for
example:
a = b = c =1

14
MPSEC-1 Physics KSOU

3. Mention different Operators in Python and Explain Arithmetic Operators.


Ans: Operators are symbols, such as +, –, =, >, and <, that perform certain mathematical or
logical operation to manipulate data values and produce a result based on some rules.
Python language supports a wide range of operators. They are
1. Arithmetic Operators
2. Assignment Operators
3. Comparison Operators
4. Logical Operators
5. Bitwise Operators
1. Arithmetic Operators: To perform arithmetic operations like addition, subtraction, division,
multiplication, arithmetic operators are used. The list of arithmetic operators is provided
below:

4. Outline different assignment operators with examples.


Ans:
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.

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

2.0 Control Flow Statements


Python has a set of control flow statements that you can use in your program. Most of
the time, the statements in your Python program are run from top to bottom. In addition to
sequential control flow statements, you can also use decision-making and looping control
flow statements to break up the flow of execution. This lets your program run different blocks
of code based on whether or not certain conditions are met.

The Python Programming Language's control flow statements are


1. Sequential Control Flow Statements: The statements that are run in the same order
as they appear in the programme, one after the other, line by line.
2. Decision Control Flow Statements: Depending on whether a condition is True or
False, the decision structure may skip an entire block of statements or run one block
of statements instead of another (if, if...else, and if...elif...else).
3. Loop Control Flow Statements: This is a type of control structure that lets a block
of statements be run more than once until a condition that ends the loop is met (for
loop and while loop). Iteration statements and Repetition statements are other names
for Loop Control Flow Statements.

18
MPSEC-1 Physics KSOU

 if Decision Control Flow Statement


The syntax for if statement is,

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:

 if…else Decision Control Flow Statement


An else statement can arrive after an if statement, but it is not required. There is no condition
in an else clause. If the Boolean Expression is True, the statements in the if block will be run.
If the Boolean Expression is False, you can use the optional else block to run statements. The
if...else statement lets you choose between two options.

19
MPSEC-1 Physics KSOU

The syntax for if…else statement is,

If the Boolean_Expression evaluates to True, then statement_1 is run. If it evaluates to False,


then statement_2 is run. The blocks are set apart by using indentation. Either statement_1 or
statement_2 is run, and then the control moves to the statement that comes after the if
statement. Also, the keywords for if and else should be in the same column.

Program:

Output:

 if…elif…else Decision Control Statement


The if...elif...else statement is also called a multi-way decision control statement. When you
need to choose between more than one option, you use an if statement with an elif statement.
The keyword "elif" is short for "else if," and it can be used to avoid too much indenting. The
else statement must always come last and will again be the default action.

20
MPSEC-1 Physics KSOU

The syntax for if…elif…else statement is,

This if...elif...else decision control statement is run as follows:


• If more than one Boolean expression evaluates to True, only the first logical Boolean
expression will be run.
• Statement 1 is run if Boolean_Expression_1 is True.
• Statement 2 is run if Boolean_Expression_1 is false and Boolean_Expression_2 is true.
• Statement 3 is run if Boolean_Expression_1 and Boolean_Expression_2are both false and
Boolean_Expression_3 is true, and so on.
• statement last is run if none of the Boolean Expressions are true.

Program:

21
MPSEC-1 Physics KSOU

Output:

2.1 NESTED if STATEMENT


In some cases, you need to put an if statement inside another statement. A Nested if statement
is an if statement that has another if statement in its if block or else block.
The syntax of the nested if statement is

If the Boolean_Expression_1 is evaluated to True, then the control shifts to


Boolean_Expression_2 and if that expression is evaluated to True, then statement 1 is
executed; if Boolean_Expression_2 is evaluated to False then the statement 2 is executed. If
the value of Boolean Expression 1 is False, then statement 3 is run.
Program:

22
MPSEC-1 Physics KSOU

Output:

2.2 while LOOP


The syntax for while loop is,

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

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

2.4 continue AND break STATEMENTS


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.

Program:

Output:

2.5 CHECK YOUR PROGRESS


1. _________ control statement repeatedly executes a set of statements.

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

3. The step argument in range () function _________.


a. indicates the beginning of the sequence
b. indicates the end of the sequence
c. indicates the difference between every two consecutive numbers in the
sequence
d. generates numbers up to a specified value
Ans: c
4. What is the keyword that is used to come out of a loop only for that iteration?
a. break
b. return
c. continue
d. if
Ans: a

2.6 REVIEW QUESTIONS


1. Explain the syntax of for loop with an example.

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:

2. What is the purpose of using break and continue?

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.

3. Write a Program to show the usage of if..elif..else:

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

3.0 FUNCTIONS AND STRINGS


When a block of statements within a program needs to be run more than once, functions
are employed. You can use a function to carry out the activity rather than repeatedly writing
the block of statements to do it. This group of statements are assembled under one name that
can be used to call it from other parts of the program. A function can be executed as many
times as you wish after being written once. Functions also shrink the size of the program by
getting rid of redundant lines of code. Functions can either be User-defined functions or
Built-in functions.

3.1 BUILT-IN FUNCTIONS


The built-in and always-available functions of the Python interpreter are numerous. Some
of the built-in functions include input (), print (), and range ().
A few Built-in Functions in Python:

30
MPSEC-1 Physics KSOU

3.2 USER-DEFINED FUNCTIONS


User-defined functions are reusable code snippets that users design to carry out particular
tasks within the application.
The syntax for function definition is,

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.

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.
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__."

Program to Demonstrate a Function with and without Arguments:

Output:

3.3 SCOPE AND LIFETIME OF VARIABLES


Programs written in Python have two scopes: global and local. If a variable's value can be
accessed and changed across the entire program, it is considered a global variable. The scope
of global variables is universal. A local variable is one that is specified inside the definition
of a function. A variable's lifetime is the length of time it has been present. Every time the
function is called, the local variable is generated and destroyed. No code outside of the
function definition can access it. Local variables defined inside of a function have a local
scope and are present while the function is running.
As long as no local variable with the same name has been defined, it is allowed to access
global variables from within a function. Although a local variable and a global variable may
share the same name, they are completely unrelated, so changing the value of the local

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.

Program to Demonstrate the Scope of Variables

Output:

3.4 DEFAULT PARAMETERS


The parameters of the function definition may benefit from having a default value
provided in some circumstances. Here, default parameters can be useful. The function
specification for each default argument includes a default value. Any calling function can
skip arguments for default parameters but must supply arguments for every necessary
parameter listed in the function specification. For that parameter, the default value is applied
if no argument is supplied.
Default parameters are often defined towards the end of the parameter list, following any
needed parameters. Non-default parameters are not permitted to come after default
parameters. The default value is only evaluated once.
Program to Demonstrate the Use of Default Parameters:

34
MPSEC-1 Physics KSOU

Output:

3.5 KEYWORD ARGUMENTS


As you've seen up to this point, whenever a function is called with a set of values as its
arguments, the values are allocated to the parameters in the function declaration in
accordance with their order. The expression kwarg = value can be used in the calling function
to explicitly declare the name and value of each argument. Positional arguments must come
before keyword arguments in the calling function. Order is not relevant; all keyword
arguments must match at least one of the function definition's parameters. In the function
definition, no parameter may have the same value more than once.

Program to Demonstrate the Use of Keyword Arguments:

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.

3.6.1 CREATING AND STORING STRINGS


Single or double quotation marks can be used to denote strings. You only need to assign a
string to a variable in order to store it inside of that variable. Additionally, a single character
is handled as a string. There is no requirement that a string contain any characters. Empty
strings, often known as " and "," are both acceptable strings. You must use the opposite type
of quote mark inside a string that is surrounded by one kind. Backslashes must come before
the inner quote if you wish to use the same quotation marks to enclose a string as you did to
enclose it. Triple quotes can be used to surround a string that spans multiple lines. Inside of
the triple quotes, any newlines and white spaces are literally reflected in the string. Python
uses the data type "str" for strings.

36
MPSEC-1 Physics KSOU

3.6.2 BASIC STRING OPERATIONS


Consider the string values "face" and "book" are being allocated to two string variables.
The + operator is used to combine the strings string 1 and string 2 to create a new string
"facebook". The values of both strings are contained in the new concatenated string. The +
operator cannot be used to combine values of two different types. A string can be multiplied
by using the * operator. The string is repeated the number of times you specify.
Using the 'in' and 'not in' membership operators, you may determine whether a string is
present in another string. It gives back a Boolean value of True or False. If the string value in
the left operand appears in the string value's sequence of characters in the right operand, the
'in' operator evaluates to True. If the string value in the left operand does not appear in the
string value's sequence of characters in the right operand, the 'not in' operator evaluates to
True.

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.

 Built-In Functions Used on Strings:

38
MPSEC-1 Physics KSOU

3.6.3 FORMATTING STRINGS


Python offers several options for formatting text strings. These consist of str. format ()
and %-formatting (). Each of these approaches has benefits, but they also each have
drawbacks that make them difficult to apply in real-world situations. A method known as "f-
strings" is gaining acceptance. The f-strings offer a simple syntax for embedding expressions
inside string literals. What we see in a Python program's source code, including the quotation
marks, is a string literal. As opposed to being a constant value, an f-string is actually an
expression that is evaluated at run time. An f-string is a literal string that begins with the
letter "f" and contains expressions enclosed in the curly braces '{' and '}'.

 Format Specifiers:
Evaluated expressions may also be seen in format specifiers. The syntax for an
operation that formats an f-string is,

The f character should be prepended when formatting an f-string. string_statement is a


character string. You specify the variable_ name whose value will be shown between curly
brackets. The width and precision settings can be specified optionally. If supplied, curly
braces must contain both width and precision. Additionally, variable_name must be separated
from width or precision values by a colon. With width, you can pad or create space around
the variable_name value element. Strings are left-justified by default, but numbers are right-
justified. Precision refers to the total number of displayed digits in a number. This contains
the decimal point and all digits, both preceding and following the decimal point.

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.

3.7 CHECK YOUR PROGRESS


1. The arithmetic operator that cannot be used with strings is
a. +
b. *
c. −
d. All of these
Ans: c
2. The function that is used to find the length of the string is
a. len(string)
b. length(string)
c. len[string]
d. length[string]
Ans: a
3. The keyword that is used to define the block of statements in function?
a. function
b. func
c. def
d. pi

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

3.8 REVIEW QUESTIONS


1. Explain with syntax how to create a user-defined functions and how to call the user-
defined function from the main function.

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,

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

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:

4. Program to Check If a 3 Digit Number Is Armstrong Number or Not

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

4.0 Lists-Basic List Operations


4.1 Indexing and Slicing in Lists
4.2 List Methods
4.3 Dictionaries
4.3.1 Creating Dictionary
4.3.2 Dictionary Methods
4.4 Tuples
4.4.1 Creating Tuples
4.4.2 Indexing and Slicing in Tuples
4.4.3 Tuple Methods
4.5 Set Methods
4.6 Introduction to Numpy
4.7 Introduction to Matplotlib
4.8 Check your progress
4.9 Review Questions
4.10 Reference

46
MPSEC-1 Physics KSOU

4.0 LISTS-BASIC LIST OPERATIONS


The + sign can also be used to concatenate lists in Python, and the * operator is used to
generate a sequence of repeated list elements. The '= =' operator is used to compare the
contents of the two lists, and the outcome is a Boolean. Using the ‘in’ and ‘not in’
membership operators, you may determine whether an item is present in the list. It offers a
True or False Boolean response.

4.1 INDEXING AND SLICING IN LISTS


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.

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.

4.2 LIST METHODS


You can obtain a list of all the methods connected to a list by supplying the list function
to the ‘dir ()’.

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.

4.3.2 DICTIONARY METHODS


You can obtain a list of all the methods connected to a dictionary by supplying the
dictionary function to the ‘dir ()’.

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.

4.4.2 INDEXING AND SLICING IN TUPLES


Through indexing, each item in a tuple can be called separately. The index is the
expression included within the bracket. The first item in a tuple is at index 0, the second item
is at index 1, and so forth. Tuples employ square brackets [] to retrieve individual items. The
value being accessed is indicated by the index that is provided between square brackets.
The syntax for gaining access to a tuple item is,
tuple_name[index]
where index always denotes the item to be picked and should be an integer number.

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.

4.4.3 TUPLE METHODS


You can obtain a list of all the methods connected to a tuple by supplying the tuple
function to the ‘dir ()’.

4.5 SET METHODS


You can obtain a list of all the methods connected to a set by supplying the set function to
the ‘dir ()’.

54
MPSEC-1 Physics KSOU

4.6 INTRODUCTION TO NUMPY


The operations that can be applied to a variable in Python must be explained each time it
is given a value, which takes time. There is rarely a requirement for such a strategy if the type

55
MPSEC-1 Physics KSOU

of a variable would not change in a certain circumstance. This is applicable to mathematical


operations as well as calculations used in science and statistics. By casting the codes to
defined types and modifying them, the codes in such circumstances can be made efficient.
Numerical Python, also known as NumPy, is a Python library. Multidimensional array
objects and the algorithms used to process them are both included in NumPy. When
combined with SciPy, Scientific Python, and MATPLOTLIB, one of NumPy's biggest
benefits is its capacity to carry out MATLAB-like tasks. Contrary to MATLAB, NumPy is
open source.

Multidimensional arrays can be subjected to logical and mathematical operations, Fourier


transforms, and operators for linear algebra and random numbers using NumPy. Since
multidimensional arrays are utilised in many techniques, including machine learning
algorithms, having the capacity to manipulate them becomes important.

The FORTRAN-based, lightning-fast LINPACK linear algebra package is used by


Numpy. An important benefit is that arrays are multiplied element-wise by default. This
implies that you can just multiply the arrays if you have numerous lists of numbers that need
to be multiplied together. Instead, you can define each list of numbers as a numpy array. This
method of performing the multiplications is both faster and simpler overall than using a for
loop. In a similar vein, functions that typically compute single values may frequently
compute array values when provided with an array of input.

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

 ndmin: The minimum number of dimensions is specified by this option.

4.7 INTRODUCTION TO MATPLOTLIB


Visualization provides an understanding of the outcomes and may assist in identifying
hidden patterns. The software package Matplotlib makes it easier to visualise data and plot
different kinds of graphs. The matplotlib's pyplot collection offers a set of functions that aid
programmers in carrying out a variety of plotting-related activities. These functions give
Python programmers MATLAB-like features. Plotting a figure, making a plotting area,
assigning labels, etc. are all functions offered by pyplot. The pyplot keeps track of the area
and the current figure, allowing it to guide the functions to the appropriate axes.

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.

Matplotlib is a phenomenal Python visualisation package for 2D array charts. Matplotlib


is a cross-platform toolkit for data visualisation based on NumPy arrays and designed to
operate with the SciPy stack as a whole. One of the main advantages of visualisation is that it
provides us with visual access to vast quantities of data in simply digestible representations.
Matplotlib includes a vast assortment of plots. Plots facilitate the comprehension of trends,

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.

4.8 CHECK YOUR PROGRESS


1. If zoo = ["lion", "tiger"], what will be zoo * 2?
a. ['lion']
b. ['lion', 'lion', 'tiger', 'tiger']
c. ['lion', 'tiger', 'lion', 'tiger']
d. ['tiger']
Ans: c

2. Which of the following statements create a dictionary?


a. dic = {}
b. dic = {"charles":40, "peterson":45}
c. dic = {40: "charles", 45: "peterson"}
d. All of the above
Ans: d

3. Which of the following is a mutable type?


a. Strings
b. Lists
c. Tuples
d. Frozenset
Ans: b

58
MPSEC-1 Physics KSOU

4.9 REVIEW QUESTIONS

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

2. Briefly explain how a dictionary is created with an example.


Ans: 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
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.

61
MPSEC-1 Physics KSOU

3. Program to Illustrate Traversing of Lists Using the for loop


Program:

Output:

4. Program to Illustrate Traversing of key:value Pairs in Dictionaries using for Loop


Program:

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.

5.1.1 INNER PRODUCT


The inner product returns a single integer after receiving two vectors of equal size
(scalar). Each vector's associated elements are multiplied, and the sum of all of those
products is used to calculate this. Vectors are referred to in Numpy as one-dimensional
Numpy arrays.
Either [Link]() or [Link]() can be used to obtain the inner product (). Both provide the same
outcomes. Two vectors, each of the same size, serve as the functions' inputs.

Program for inner product:

65
MPSEC-1 Physics KSOU

Output for inner product:

5.1.2 DOT PRODUCT


For matrices, the dot product is defined. It is the product of all the equivalent components
in the two matrices added together. The first matrix's columns must have the same number of
rows as the second matrix's rows in order to get the dot product.
Matrix creation in Numpy can be done in one of two methods. Utilizing the numpy ndarray
class is the most popular choice. Here, two-dimensional Numpy arrays are created (ndarray
objects). The numpy matrix class is the alternative. Here, we develop objects for matrices.
[Link]() can be used to get the dot product of ndarray and matrix objects ().
The consequence of using the * operator to multiple two ndarray objects is element-by-
element multiplication. On the other hand, the dot (matrix) product, which is equivalent to the
previous [Link](), is produced when multiplying two matrix objects with the * operator.
Program for dot product:

66
MPSEC-1 Physics KSOU

Output for dot product:

5.2 LINEAR ALGEBRA OPERATIONS


5.2.1 TRANSPOSE
By reversing a matrix's rows and columns, the transposition can be determined. To obtain
the transpose, we can use the [Link]() function, the NumPy [Link]()
method, or ndarray.T (a special method that does not call for parentheses). All provide the
same result.
A vector can also be subjected to the transpose. A one-dimensional numpy array cannot,
however, be transposed theoretically. A vector should be defined as a two-dimensional
numpy array with double square brackets if you truly wish to transpose it.

Program for Transpose:

67
MPSEC-1 Physics KSOU

Output for transpose:

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.

Program for determinant:

Output for determinant:

69
MPSEC-1 Physics KSOU

5.3 CHECK YOUR PROGRESS


1. Python's ……… is typically used to do numerical calculations.
2. …….. are referred to in Numpy as one-dimensional Numpy arrays.
3. ……… of all the equivalent components in the two matrices added together.
4. The matrix cannot be inverted if the determinant is …..

5.4 WORKED EXAMPLES


1. Write a python program to find the trace of the matrix:
[[1 2 3]
[4 5 6]
[7 8 9]]
Output:

2. Write a python program to find the determinant of the matrix:


[[2 -3 1]
[2 0 -1]
[1 4 5]]
Output:

70
MPSEC-1 Physics KSOU

3. Write a python program to transpose of the matrix:


[[2 -9 3]
[13 11 -17]
[3 6 15]
[4 13 1]]
Output:

4. Write a program to find the trace of the matrix:


[[1 2 -3]
[4 -5 6]
[-7 8 9]]
Output:

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

6.0 Applications of Python-1


6.1 System of Linear Equations
6.2 Matrix Representation of a Linear System
6.3 True Inverse
6.4 Eigenvectors and Eigenvalues
6.5 FFT
6.6 Maxima and Minima
6.7 Check your progress
6.8 Worked Examples
6.9 References

73
MPSEC-1 Physics KSOU

6.0 APPLICATIONS OF PYTHON-1


BLAS and LAPACK are used by the NumPy linear algebra functions to offer effective
low-level implementations of common linear algebra methods. It is feasible for NumPy to
supply these libraries using C versions of some of their reference implementations, however
it is preferable to use highly optimised libraries that make use of specific processor features.
OpenBLAS, MKL (TM), and ATLAS are a few examples of these libraries. Due to the
multithreaded nature of those libraries and their dependence on the processor, environmental
variables and third-party programmes like threadpoolctl may be required to regulate the
thread count or specify the processor architecture.

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.

6.1 SYSTEM OF LINEAR EQUATIONS


A collection of two or more linear equations with the same set of variables is referred to
as a system of linear equations in linear algebra. The system's equations are all taken into
account simultaneously. Different industries, including manufacturing, marketing, business,
transportation, etc., use linear equation systems. When the number of variables and equations
is increased, the procedure of solving a system of linear equations also becomes more
challenging. Every equation in the system must be satisfied by the answer. Systems of linear
equations can be solved using the NumPy (Numerical Python), SciPy (Scientific Python), and
SymPy (Symbolic Python) packages in Python. These libraries make use of the vectorization
principle, which enables them to do matrix computations quickly by reducing the number of
for loops.
There isn't always a single solution to a linear system. Some of them have an endless
number of solutions or no solution at all.

74
MPSEC-1 Physics KSOU

The following image which contains a linear system of equations:

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.

6.2 MATRIX REPRESENTATION OF A LINEAR SYSTEM


The solution to the above system of linear equations can be found by doing matrix
operations on a specific matrix known as the augmented matrix.

There are two parts of this augmented matrix:


 Coefficient matrix: Only the variable coefficients are contained in this rectangular
array. This is a 3 x 3 square matrix in our example, which is located to the left of the
vertical line in the image above. For each of the equations, the coefficients of x are
listed in the first column, y are listed in the second column, and so on. The linear
system's number of equations is equal to the number of rows. The number of columns
in the linear system corresponds to the number of various variables. This can be
displayed as a 2-dimensional array in NumPy. This is frequently given to a variable
having an uppercase letter in the name (such as A or B).
 Augment: In the image above, this column vector extends all the way to the vertical
line. It includes the linear equations' constants. This is a 3 x 1 column vector in our
case. This can be shown as a 1-dimensional array in NumPy. This is frequently given
to a variable having a lowercase letter in the name (such as b).

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

Consider another linear system with no solution:

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:

6.3 TRUE INVERSE


The inv() function of the numpy linalg package can be used to determine the true
inverse of a square matrix. A square matrix has a genuine inverse if its determinant is not 0.
You will encounter an error if you attempt to calculate the true inverse of a singular matrix,
which is a square matrix with a determinant of 0.

Consider a square matrix, where its determinant is not 0.


[[2, 2, 1],
[1, 3, 1].
[1, 2 3]]
Program:

Output:

78
MPSEC-1 Physics KSOU

6.4 EIGENVECTORS AND EIGENVALUES


Consider the n x n matrix A. If the vector x is non-zero and it satisfies the equation below,
then the scalar lambda(‘λ’) is said to be an eigenvalue of A.

The eigenvector of A corresponding to x is referred to as the vector. The eig()


function in numpy calculates eigenvalues and eigenvectors simultaneously.

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

The input signal –

 FFT applied signal –

 Inverse FFT applied signal:

82
MPSEC-1 Physics KSOU

6.6 MAXIMA AND MINIMA

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

6.7 CHECK YOUR PROGRESS


1. A collection of two or more linear equations with the same set of variables is referred
to as ………………
2. ………… can be shown as a 1-dimensional array in NumPy.
3. The eigenvector of A corresponding to x is referred to as the …….

6.8 WORKED EXAMPLES


1. Write a python program to solve the system of linear equation using numpy library
x – 2y + 3x = 9
-x + 3y -z = -6
2x - 5y + 5z = 17

Output:

Solution for the above-mentioned system if linear equation is (1, −1,2)

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:

Solution for the above-mentioned system if linear equation is (1, -1,1)


3. Write a python program to find the inverse of the following matrix

Output:

4. Write a python program to find the inverse of the following matrix

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

7.0 Applications of Python-2


7.1 Euler Method
7.2 Runge-Kutta Method
7.3 Gauss-Seidel Method
7.4 Newton-Raphson Method
7.5 Bisection Method
7.6 Secant Method
7.7 Worked Examples
7.8 References

87
MPSEC-1 Physics KSOU

7.0 APPLICATIONS OF PYTHON-2

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.

7.1 EULER METHOD

The following program implements Euler’s method in python. It considers a simple


equation ‘x + y’ to be solved and that function will be coded in function named ‘f (x, y)’
which the returns the above equation. Similarly, change the function definition according to
the equation to be solved.

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

Program for Euler method:

88
MPSEC-1 Physics KSOU

Output for Euler method:

7.2 RUNGE-KUTTA METHOD

The following program implements Range-Kutta’s method in python. It considers a


simple equation ‘x + y’ to be solved and that function will be coded in function named ‘f (x,
y)’ which the returns the above equation. Similarly, change the function definition according
to the equation to be solved.

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

Program for Runge-Kutta method:

90
MPSEC-1 Physics KSOU

Output for Range-Kutta method:

7.3 GAUSS-SEIDEL METHOD

In Gauss Seidel method, we first arrange given system of linear equations in diagonally
dominant form.
For example, if system of linear equations is:

Then they can be arranged like the following:

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

Program for Gauss-Seidel method:

92
MPSEC-1 Physics KSOU

Output for Gauss-Seidel method:

7.4 NEWTON-RAPHSON METHOD

The following program implements Newton-Raphson’s method in python. It considers


the equation ‘x^3 - 5x – 9’ to be solved and that equation will be coded in function named ‘f
(x)’ which the returns the above equation. It also considers another function ‘g (x)’ which
returns the derivative of the equation in ‘f (x)’ and that derivative will be coded in this
function as ‘3x^2 - 5’. Similarly, change the function definition according to the equation to
be solved.

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

Program for Newton-Raphson method:

93
MPSEC-1 Physics KSOU

Output for Newton-Raphson method:

94
MPSEC-1 Physics KSOU

7.5 BISECTION METHOD

The following program implements Bisection’s method in python. It considers the


equation ‘x^3 - 5x – 9’ to be solved and that equation will be coded in function named ‘f (x)’
which the returns the above equation. Similarly, change the function definition according to
the equation to be solved.

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

Program for Bisection method:

95
MPSEC-1 Physics KSOU

Output for Bisection method:

7.6 SECANT METHOD

The following program implements Bisection’s method in python. It considers the


equation ‘x^3 - 5x – 9’ to be solved and that equation will be coded in function named ‘f (x)’
which the returns the above equation. Similarly, change the function definition according to
the equation to be solved.

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

Program for Secant method:

Output for Secant method:

97
MPSEC-1 Physics KSOU

7.7 WORKED EXAMPLES


1. Write a python program to solve the function f(x) = 3*cos(x) - ex using the
Newton Raphson method, where Initial Guess is 0.5, Tolerable Error is 0.00001,
Maximum Step is 10.
Output:

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

8.0 Applications of Python-3


8.1 Calculate the Solar Mass
8.2 Half Life Period of Radioactive Material
8.3 Newton’s Law of Gravitation
8.4 Capacitor Discharge in RC Circuit
8.5 Check your progress
8.6 Worked Examples
8.7 References

102
MPSEC-1 Physics KSOU

8.0 APPLICATIONS OF PYTHON-3


8.1 CALCULATE THE SOLAR MASS
Solar Mass can be calculated by the following formula. Here ‘pi’ can be imported by numpy
library. ‘AU’ indicates the astronomical unit of length and is defined to be average distance
between Sun and Earth. ‘yr’ indicate light year. In this program we take G, AU, yr as input
and calculate the solar mass.

Program:

Output:

8.2 HALF LIFE PERIOD OF RADIOACTIVE MATERIAL


From an original mass N0 of a radioactive material, the remaining mass after time ‘t’ is
given the equation for radioactive decay below.
t
N  t   N 0e 

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:

8.3 NEWTON’S LAW OF GRAVITATION


Gravitational Force between two objects is calculated by the equation:
m1 m2
F G
r2
In the python program, we take inputs for the mass of both the objects and the distance
between those two objects.
Program:

104
MPSEC-1 Physics KSOU

Output:

8.4 CAPACITOR DISCHARGE IN RC CIRCUIT


The differential equation of discharging capacitor is given by:

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

 Motion in frictional surface


Following program is used to find the distance covered by a wooden block with initial
velocity v0 m/s on different materials of different coefficient of friction. Position of the block
can be expressed as:
1
x  t   v0t   gt 2
2
Where ‘u’ is coefficient of friction and ‘g’ is 9.81m/s2.
Time at which the block will stop moving is given by:
v
T 0
g
The initial velocity and the acceleration owing to gravity are the two primary inputs for this
issue. The friction coefficient, the third input, is provided as a list that is presented within [],
as seen in the programming below.
Program:

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

The projectile motion of a body is given by the following equation:

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:

8.5 CHECK YOUR PROGRESS


1. ‘AU’ indicates the …………. of length.
2. The differential equation of discharging capacitor is given by …………….

8.6 WORKED EXAMPLES


1. Write a python program to find the remaining mass of a radioactive element whose
half-life is 200sec, initial mass if 5 kg, after 500 sec.

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:

4. Write a python program to plot the projectile motion of a body


Program:

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

You might also like