PYTHON NOTES FOR BS-PHYSICS
Dr. Sara Medhet
Programming:
Programming is the art of communicating with computers through a
set of languages, algorithms, and data structures to create software, applications, or
system that perform desired functions.
Python:
Python is a dynamically typed, general purpose programming language that
supports an object-oriented programming approach as well as a functional
programming approach.
Python is an interpreted and a high-level programming language.
It was created by Guido Van Rossum in 1989.
Features of Python:
Python is simple and easy to understand.
It is interpreted and platform-independent which makes debugging very easy.
Python is an open-source programming language.
Python provides very big library support. Some of the popular libraries
include NumPy, Matplotlib, Sympy etc.
It is possible to integrate other programming languages within python.
What is Python used for
Python is used in Data Visualization to create plots and graphical
representations.
Python helps in Data Analytics to analyze and understand raw data for insights
and trends.
It is used in AI and Machine Learning to simulate human behavior and to learn
from past data without hard coding.
It is used to create web applications.
It can be used to handle databases.
It is used in business and accounting to perform complex mathematical
operations along with quantitative and qualitative analysis.
Modules:
Module is like a code library which can be used to borrow code written by somebody
else in our python program. There are two types of modules in python:
1. Built in Modules - These modules are ready to import and use and ships with
the python interpreter. There is no need to install such modules explicitly.
2. External Modules - These modules are imported from a third party file or
can be installed using a package manager like pip or conda. Since this code is
written by someone else, we can install different versions of a same module
with time.
The pip command:
It can be used as a package manager pip to install a python module. Let’s install a
module called pandas using the following command
pip install math
Using a module in Python (Usage)
We use the import syntax to import a module in Python. Here is an example code:
import math
y = math.sqrt(8)
print(y) #print the square root of the given number
Python Comments
A comment is a part of the coding file that the programmer does not want to execute,
rather the programmer uses it to either explain a block of code or to avoid the
execution of a specific part of code while testing.
Single-Line Comments:
To write a comment just add a ‘#’ at the start of the line.
#Printing Hello World
print("Hello World !!!")
Output:
Hello World !!!
Multi-Line Comments:
To write multi-line comments you can use ‘#’ at each line or you can use the
multiline string.
#It will execute a block of code if a specified condition is true.
#If the condition is false then it will execute another block of code.
p=7
if (p > 5):
print("p is greater than 5.")
else:
print("p is not greater than 5.")
or
"""This is an if-else statement.
It will execute a block of code if a specified condition is true.
If the condition is false then it will execute another block of code."""
p=7
if (p > 5):
print("p is greater than 5.")
else:
print("p is not greater than 5.")
Output:
p is greater than 5.
Variables and Data Types
Variable:
Variable is like a container that holds data. Very similar to how our containers in
kitchen holds sugar, salt etc. Creating a variable is like creating a placeholder in
memory and assigning it some value. In Python it’s as easy as writing:
a=1
b = True
c = "Alice"
d = None
These are four variables of different data types.
Data Type:
Data type specifies the type of value a variable holds. This is required in
programming to do various operations without causing an error.
In python, we can print the type of any operator using type function:
a=1
print(type(a))
b = "1"
print(type(b))
By default, python provides the following built-in data types:
1. Numeric data: int, float, complex
int: 3, -8, 0
float: 7.349, -9.0, 0.0000001
complex: 6 + 2i
2. Text data: str
str: "Hello World!!!", "Python Programming"
3. Boolean data:
Boolean data consists of values True or False.
4. Sequenced data: list, tuple
List: A list is an ordered collection of data with elements separated by a comma and
enclosed within square brackets. Lists are mutable and can be modified after
creation.
Example:
list1 = [8, 2.3, [-4, 5], ["apple", "banana"]]
print(list1)
Output:
[8, 2.3, [-4, 5], ['apple', 'banana']]
Tuple: A tuple is an ordered collection of data with elements separated by a comma
and enclosed within parentheses. Tuples are immutable and cannot be modified after
creation.
Example:
tuple1 = (("parrot", "sparrow"), ("Lion", "Tiger"))
print(tuple1)
Output:
(('parrot', 'sparrow'), ('Lion', 'Tiger'))
5. Mapped data: dict
dict: A dictionary is an unordered collection of data containing a key:value pair. The
key:value pairs are enclosed within curly brackets.
Example:
dict1 = {"name":"Sakshi", "age":20, "canVote":True}
print(dict1)
Output:
{'name': 'Sakshi', 'age': 20, 'canVote': True}
Operators
Python has different types of operators for different operations. To create a
calculator we require arithmetic operators.
Arithmetic operators
Operator Operator Name Example
+ Addition 15+7
- Subtraction 15-7
* Multiplication 5*7
** Exponential 5**3
/ Division 5/3
% Modulus 15%7
// Floor Division 15//7
Exercise
Create a calculator using python arithmetic operations.
Solution: Here 'n' and 'm' are two variables in which the integer value is being stored.
Variables 'ans1' , 'ans2' ,'ans3', 'ans4','ans5' and 'ans6' contains the outputs
corresponding to addition, subtraction, multiplication, division, modulus and floor
division respectively.
n = 15
m=7
ans1 = n+m
print("Addition of n and m is", ans1)
ans2 = n-m
print("Subtraction of n and m is", ans2)
ans3 = n*m
print("Multiplication of n and m is", ans3)
ans4 = n/m
print("Division of n and m is", ans4)
ans5 = n%m
print("Modulus of n and m is", ans5)
ans6 = n//m
print("Floor Division of n and m is", ans6)
Typecasting in python
The conversion of one data type into the other data type is known as type casting in
python or type conversion in python.
Python supports a wide variety of functions or methods like: int(), float(), str(),
tuple(), set(), list(), dict(), etc. for the type casting in python.
Two Types of Typecasting:
1. Explicit Conversion (Explicit type casting in python)
2. Implicit Conversion (Implicit type casting in python).
Explicit typecasting:
The conversion of one data type into another data type, done via developer or
programmer's intervention or manually as per the requirement, is known as explicit
type conversion.
It can be achieved with the help of Python’s built-in type conversion functions such
as int(), float(), hex(), oct(), str(), etc .
Example of explicit typecasting:
a = "1"
b = "2"
print(int(a) + int(b))
Output:
Implicit type casting:
Data types in Python do not have the same level i.e. ordering of data types is not the
same in Python. Some of the data types have higher-order, and some have lower
order. While performing any operations on variables with different data types in
Python, one of the variable's data types will be changed to the higher data type.
According to the level, one data type is converted into other by the Python interpreter
itself (automatically). This is called, implicit typecasting in python.
Python converts a smaller data type to a higher data type to prevent data loss.
Example of implicit type casting:
# Python automatically converts
# a to int
a=7
print(type(a))
# Python automatically converts b to float
b = 3.0
print(type(b))
# Python automatically converts c to float as it is a float addition
c=a+b
print(c)
print(type(c))
Output:
<class 'int'>
<class 'float'>
10.0
<class 'float'>
Taking User Input in python
In python, we can take user input directly by using input() function. This input
function gives a return value as string/character hence we have to pass that into a
variable
Syntax:
variable=input()
But input function returns the value as string. Hence we have to typecast them
whenever required to another datatype.
Example:
variable=int(input())
variable=float(input())
We can also display a text using input function. This will make input() function take
user input and display a message as well
Example:
a=input("Enter the name: ")
print(a)
Output:
Enter the name: Alice
Alice
Accessing Characters of a String
In Python, string is like an array of characters. We can access parts of string by using
its index which starts from 0.
Square brackets can be used to access elements of the string.
Example:
Name=Alice
print(name[0])
print(name[1])
print(name[2])
print(name[3])
print(name[4])
Output:
A
l
i
c
e
Length of a String
We can find the length of a string using len() function.
Example:
fruit = "Mango"
len1 = len(fruit)
print("The length of word Mango is", len1)
Output:
The length of word Mango is 5
String Slicing
This method of specifying the start and end index to specify a part of a string is
called slicing.
Example:
pie = "ApplePie"
print(pie[:5]) #Slicing from Start
print(pie[5:]) #Slicing till End
print(pie[2:6]) #Slicing in between
print(pie[-8:]) #Slicing using negative index
Output:
Apple
Pie
pleP
ApplePie
if-else Statements
Sometimes the programmer needs to check the evaluation of certain expression(s),
whether the expression(s) evaluate to True or False. If the expression evaluates to
False, then the program execution follows a different path than it would have if the
expression had evaluated to True.
Based on this, the conditional statements are further classified into following types:
if
if-else
if-else-elif
nested if-else-elif.
An if……else statement evaluates like this:
if the expression evaluates True:
Execute the block of code inside if statement. After execution return to the code out
of the if……else block.\
if the expression evaluates False:
Execute the block of code inside else statement. After execution return to the code
out of the if……else block.
Example:
applePrice = 210
budget = 200
if (applePrice <= budget):
print("Alexa, add 1 kg Apples to the cart.")
else:
print("Alexa, do not add Apples to the cart.")
Output:
Alexa, do not add Apples to the cart.
elif Statements
Sometimes, the programmer may want to evaluate more than one condition, this can
be done using an elif statement.
Working of an elif statement
Execute the block of code inside if statement if the initial expression evaluates to
True. After execution return to the code out of the if block.
Execute the block of code inside the first elif statement if the expression inside it
evaluates True. After execution return to the code out of the if block.
Execute the block of code inside the second elif statement if the expression inside it
evaluates True. After execution return to the code out of the if block.
.
.
.
Execute the block of code inside the nth elif statement if the expression inside it
evaluates True. After execution return to the code out of the if block.
Execute the block of code inside else statement if none of the expression evaluates
to True. After execution return to the code out of the if block.
Example:
num = 0
if (num < 0):
print("Number is negative.")
elif (num == 0):
print("Number is Zero.")
else:
print("Number is positive.")
Output:
Number is Zero.
Nested if statements
We can use if, if-else, elif statements inside other if statements as well.
Example:
num = 18
if (num < 0):
print("Number is negative.")
elif (num > 0):
if (num <= 10):
print("Number is between 1-10")
elif (num > 10 and num <= 20):
print("Number is between 11-20")
else:
print("Number is greater than 20")
else:
print("Number is zero")
Output:
Number is between 11-20
Introduction to Loops
Sometimes a programmer wants to execute a group of statements a certain number
of times. This can be done using loops. Based on this loops are further classified into
following main types;
for loop
while loop
The for Loop
for loops can iterate over a sequence of iterable objects in python. Iterating over a
sequence is nothing but iterating over strings, lists, tuples, sets and dictionaries.
Example: iterating over a string:
name = 'Alice'
for i in name:
print(i)
Output:
A
l
i
c
e
Example: iterating over a list:
colors = ["Red", "Green", "Blue", "Yellow"]
for x in colors:
print(x)
Output:
Red
Green
Blue
Yellow
range():
What if we do not want to iterate over a sequence? What if we want to use for loop
for a specific number of times?
Here, we can use the range() function.
Example:
for k in range(5):
print(k)
Output:
0
1
2
3
4
Here, we can see that the loop starts from 0 by default and increments at each
iteration.
But we can also loop over a specific range.
Example:
for k in range(4,9):
print(k)
Output:
4
5
6
7
8
Quick Quiz
Explore about third parameter of range (ie range(x, y, z))
Python while Loop
As the name suggests, while loops execute statements while the condition is True.
As soon as the condition becomes False, the interpreter comes out of the while loop.
Example:
i= 0
while (i< 3):
print(i)
i=i+1
Output:
0
1
2
Else with While Loop
We can even use the else statement with the while loop. Essentially what the else
statement does is that as soon as the while loop condition becomes False, the
interpreter comes out of the while loop and the else statement is executed.
Example:
x=5
while (x > 0):
print(x)
x=x-1
else:
print('counter is 0')
Output:
5
4
3
2
1
counter is 0
Good Luck