Python
Python
Python
Python
Outline
Looping
Introduction to python
Installing python
Hello World program using python
Data types
Variables
Expressions
Functions
String
List
Tuple
Set
Dictionary
Functions
Introduction to Python
Python is an open source, interpreted, high-level, general-purpose programming language.
Python's design philosophy emphasizes code readability with its notable use of significant
whitespace.
Python is dynamically typed and garbage-collected language.
Python was conceived in the late 1980s as a successor to the ABC language.
Python was Created by Guido van Rossum and first released in 1991.
Python 2.0, released in 2000,
introduced features like list comprehensions and a garbage collection system with reference counting.
Python 3.0 released in 2008 and current version of python is 3.11.5 (as of Aug-2023).
The Python 2 language was officially discontinued in 2020
3
Why Python?
Python has many advantages
Easy to learn
Less code
Syntax is easier to read
Open source
Huge amount of additional open-source libraries
Some libraries listed below.
matplotib for plotting charts and graphs
BeautifulSoup for HTML parsing and XML
NumPy for scientific computing
pandas for performing data analysis
SciPy for engineering applications, science, and mathematics
Scikit for machine learning
Django for server-side web development
And many more..
4
Installing Python
For Windows & Mac:
To install python in windows you need to download installable file from
https://www.python.org/downloads/
After downloading the installable file you need to execute the file.
For Linux :
For ubuntu 16.10 or newer
sudo apt-get update
sudo apt-get install python3.11
To verify the installation
Windows :
python --version
Linux :
python3 --version (linux might have python2 already installed, you can check python 2 using python --version)
Alternatively we can use anaconda distribution for the python installation
http://anaconda.com/downloads
Anaconda comes with many useful inbuilt libraries.
5
Hello World using Python
To write python programs, we can use any text editors or IDE (Integrated Development
Environment), Initially we are going to use Visual Studio Code.
Create new file in editor, save it as first.py (Extensions for python programs will be .py)
first.py Python line does not end with ;
1 print("Hello World from python")
To run the python file open command prompt and change directory to where your python file
is
6
Data types in Python
Name Type Description
Data Types
Integer int Whole number such as 0,1,5, -5 etc..
Float float Numbers with decimal points such as 1.5, 7.9, -8.2 etc..
String str Sequence of character (Ordered) such as “Ankit”, ‘college’, “Surat” etc..
Boolean bool Logical values indicating Ture or False (T and F here are capital in python)
Data Structures
Ordered Sequence of objects, will be represented with square brackets [ ]
List list
Example : [ 18, “Ankit”, True, 102.3 ]
Ordered immutable sequence of objects, will be represented with round brackets ( )
Tuple tup
Example : ( 18, “Ankit”, True, 102.3 )
Unordered collection of unique objects, will be represented with the curly brackets
Set set {}
Example : { 18, “Ankit”, True, 102.3 }
Unordered key : value pair of objects , will be represented with curly brackets { }
Dictionary dict
Example : { “college”: “Ankit”, “code”: “042” }
7
Variables in Python
A Python variable is a reserved memory location to store values.
Unlike other programming languages, Python has no command for declaring a variable.
A variable is created the moment you first assign a value to it.
Python uses Dynamic Typing so,
We need not to specify the data types to the variable as it will internally assign the data type to the variable
according to the value assigned.
we can also reassign the different data type to the same variable, variable data type will change to new data
type automatically.
We can check the current data type of the variable with type(variablename) in-built function.
Rules for variable name
Name can not start with digit
Space not allowed
Can not contain special character
Python keywords not allowed
Should be in lower case
8
Example of Python variable
Example :
demo.py
1 x = 10
2 print(x)
3 print(type(x))
Reassign same variable to hold different data type
4
5 y = 123.456
6 print(y)
7
8 x = “scet"
9 print(x)
10 print(type(x))
Run in terminal
1 python demo.py
Output
1 10
2 int
3 123.456
4 scet
5 str
9
Python – Input and Output
The purpose of a computer is to process data and return results.
The data given to the computer is called ‘Input’.
The result returned by the computer is called ‘Output’.
For performing input-output, Python provides statements
Output Statements
Input Statements
10
Output Statements
To display output or result, Python provides print() function.
It has several formats:
print() – with display blank line.
print(“string”) – the string is displayed as it is.
We can use escape sequence characters inside print() function.
We can use repetition operator (*) inside print() function.
To join two string in display, we can use ‘+’ operator inside print() function.
11
Output Statements
Output : Ankit
print() function
Output : Scet
12
Input Statements
To accept input from keyboard, Python provides input() function.
This function takes a value from the keyword and returns it as a string
Once the value comes into variable, it can be converted into ‘int’ or ‘float’.
Output :
1 a=input(“Enter the value”)
Enter the value 10
2 b=input(“Enter the value”)
Enter the value 20
3 print(a)
10
4 print(b)
20
5 print(a+b)
1020
Output :
1 a=int(input(“Enter the value”)) Enter the value 10
2 b=int(input(“Enter the value”)) Enter the value 20
3 print(a) 10
4 print(b) 20
5 print(a+b) 30
13
String in python
String is Ordered Sequence of character such as “Ankit”, ‘SCET’, “Surat” etc..
Strings are arrays of bytes representing Unicode characters.
String can be represented as single, double or triple quotes.
String with triple Quotes allows multiple lines.
String in python is immutable.
Square brackets can be used to access elements of the string, Ex. “ABCDEFG”[1] = B,
characters can also be accessed with reverse index like “ABCDEFG”[-1] = G.
String index
x = " A B C D E F G "
index = 0 1 2 3 4 5 6
Reverse index = -7 -6 -5 -4 -3 -2 -1
14
String functions in python
Python has lots of built-in methods that you can use on strings, we are going to cover some
frequently used methods for string like
len()
count()
capitalize(), lower(), upper()
istitle(), islower(), isupper()
find(), rfind(), replace()
index(), rindex()
Methods for validations like
isalpha(), isalnum(), isdecimal(), isdigit()
strip(), lstrip(), rstrip()
Etc..
Note : len() is not the method of the string but can be used to get the length of the string
lendemo.py
1 x = “Ankit" Output : 5 (length of “Ankit”)
2 print(len(x))
15
String methods (cont.)
count() method will returns the number of times a specified value occurs in a string.
countdemo.py
1 x = “ankita"
Output : 2 (occurrence of ‘a’ in “Ankita”)
2 ca = x.count('a')
3 print(ca)
title(), lower(), upper() will returns capitalized, lower case and upper case string
respectively.
changecase.py
1 x = “SCET College"
Output : Scet College
2 c = x.title()
3 l = x.lower() Output : scet college
4 u = x.upper()
5 print(c) Output : SCET COLLEGE
6 print(l)
7 print(u)
16
String methods (cont.)
istitle(), islower(), isupper() will returns True if the given string is capitalized, lower case
and upper case respectively.
checkcase.py
1 x = ‘scet college'
2 c = x.istitle() Output : False
3 l = x.islower()
4 u = x.isupper() Output : True
5 print(c)
6 print(l) Output : False
7 print(u)
strip() method will remove whitespaces from both side of the string and returns the string.
stripdemo.py
1 x = ' Ankit '
2 f = x.strip() Output : Ankit(without space)
3 print(f)
rstrip() and lstrip() will remove whitespaces from right and left side respectively.
17
String methods (cont.)
find() method will search the string and returns the index at which they find the specified
value
finddemo.py
1 x = 'SCET institute, Surat, india'
2 f = x.find('in') Output : 5 (occurrence of ‘in’ in x)
3 print(f)
rfind() will search the string and returns the last index at which they find the specified value
rfinddemo.py
1 x ='SCET institute, Surat, india'
2 r = x.rfind('in') Output : 23 (last occurrence of ‘in’ in x)
3 print(r)
Note : find() and rfind() will return -1 if they are unable to find the given string.
replace() will replace str1 with str2 from our string and return the updated string
replacedemo.py
1 x ='SCET institute, Surat, india' Output :
2 r = x.replace('india','INDIA') “SCET institute, Surat, INDIA”
3 print(r)
18
String methods (cont.)
index() method will search the string and returns the index at which they find the specified
value, but if they are unable to find the string it will raise an exception.
indexdemo.py
1 x = 'SCET institute, Surat, india '
2 f = x.index('in') Output : 5 (occurrence of ‘in’ in x)
3 print(f)
rindex() will search the string and returns the last index at which they find the specified
value , but if they are unable to find the string it will raise an exception.
rindexdemo.py
1 x = 'SCET institute, Surat, india'
2 r = x.rindex('in') Output : 23 (last occurrence of ‘in’ in x)
3 print(r)
Note : find() and index() are almost same, the only difference is if find() is unable to find the
string it will return -1 and if index() is unable to find the string it will raise an exception.
19
String methods (cont.)
isalnum() method will return true if all the characters in the string are alphanumeric (i.e
either alphabets or numeric).
isalnumdemo.py
1 x = ‘ankit123'
2 f = x.isalnum() Output : True
3 print(f)
isalpha() and isnumeric() will return true if all the characters in the string are only alphabets
and numeric respectively.
isdecimal() will return true is all the characters in the string are decimal.
isdecimaldemo.py
1 x = '123.5'
2 r = x.isdecimal() Output : True
3 print(r)
Note : isnumeric() and isdigit() are almost same, you suppose to find the difference as Home
work assignment for the string methods.
20
String Slicing
We can get the substring in python using string slicing, we can specify start index, end index
and steps (colon separated) to slice the string.
syntax
x = 'Sarvajanik College of Engineering and Technology, Surat, gujarat, INDIA'
subx = x[startindex:endindex:steps]
endindex will not be included in the substring
strslicedemo.py
1 x = 'Sarvajanik College of Engineering and Technology,
2 Surat, gujarat, INDIA'
3 subx1 = x[0:10]
subx2 = x[50:55] Output : Sarvajanik
4
subx3 = x[66:]
5 subx4 = x[::2] Output : Surat
6 subx5 = x[::-1]
7 print(subx1) Output : INDIA
8 print(subx2)
9 print(subx3) Output : Sraai olg fEgneigadTcnlg,Srt uaa,IDA
10 print(subx4) Output : AIDNI ,tarajug ,taruS ,ygolonhceT dna gnireenignE fo egelloC
11 print(subx5) kinajavraS
21
String print format
str.format() is one of the string formatting methods in Python3, which allows multiple
substitutions and value formatting.
This method lets us concatenate elements within a string through positional formatting.
strformat.py
1 x = '{} institute, Surat'
Output : SCET institute, Surat
2 y = x.format(‘SCET')
3 print(y) Inline function call
4 print(x.format('ABCD')) Output : ABCD institute, Surat
22
String print format (cont.)
We can specify the order of parameters in the string
strformat.py
1 x = '{1} institute, {0}'
Output : Surat institute, SCET
2 y = x.format(‘SCET',‘Surat')
3 print(y) Inline function call
4 print(x.format('ABCD','XYZ')) Output : XYZ institute, ABCD
We can also specify alias within the string to specify the order
strformat.py
1 x = '{collegename} institute, {cityname}'
Output : SCET institute, Surat
2 print(x.format(collegename=‘SCET',cityname=‘Surat'))
We can format the decimal values using format method
strformat.py
1 per = (438 / 500) * 100
2 x = 'result = {r:3.2f} %'.format(r=per) Output : result = 87.60 %
3 print(x)
width precision
23
Data structures in python
There are four built-in data structures in Python - list, dictionary, tuple and set.
24
List
List is a mutable ordered sequence of objects, duplicate values are allowed inside list.
List will be represented by square brackets [ ].
Python does not have array, List can be used similar to Array.
list.py Output : institute (List index starts with 0)
1 my_list = [‘SCET', 'institute', ‘Sura']
2 print(my_list[1]) Output : 3 (length of the List)
3 print(len(my_list)) Output : [‘SCET', 'institute', ‘Surat']
4 my_list[2] = “Surat" Note : spelling of Surat is updated
5 print(my_list)
6 print(my_list[-1]) Output : Surat (-1 represent last element)
We can use slicing similar to string in order to get the sub list from the list.
list.py
1 my_list = [‘SCET', 'institute', ‘Surat','gujarat','INDIA']
2 print(my_list[1:3])
Output : ['institute', ‘Surat']
Note : end index not included
25
List methods
append() method will add element at the end of the list.
appendlistdemo.py
1 my_list = [‘SCET', 'institute', ‘Surat']
2 my_list.append('gujarat') Output : [‘SCET', 'institute', ‘Surat', 'gujarat']
3 print(my_list)
insert() method will add element at the specified index in the list
insertlistdemo.py
1 my_list = [‘SCET', 'institute', ’Surat']
2 my_list.insert(2,'of') Output : [‘SCET', 'institute', 'of', 'engineering', ‘Surat']
3 my_list.insert(3,'engineering')
4 print(my_list)
extend() method will add one data structure (List or any) to current List
extendlistdemo.py
1 my_list1 = [‘SCET', 'institute']
2 my_list2 = [‘Surat','gujarat']
3 my_list1.extend(my_list2) Output : [‘SCET', 'institute', ‘Surat', ‘gujarat']
4 print(my_list1)
26
List methods (cont.)
pop() method will remove the last element from the list and return it.
poplistdemo.py
1 my_list = ['SCET', 'institute','Surat']
2 temp = my_list.pop() Output : Surat
3 print(temp)
print(my_list) Output : ['SCET', 'institute‘]
4
remove() method will remove first occurrence of specified element
removelistdemo.py
1 my_list = ['SCET', 'institute', 'SCET','Surat']
2 my_list.remove('SCET')
Output : ['institute', 'SCET', 'Surat']
3 print(my_list)
clear() method will remove all the elements from the List
clearlistdemo.py
1 my_list = ['SCET', 'institute', 'SCET','Surat']
2 my_list.clear()
3 print(my_list) Output : []
29
Tuple
Tuple is a immutable ordered sequence of objects, duplicate values are allowed inside list.
Tuple will be represented by round brackets ( ).
Tuple is similar to List but List is mutable whearas Tuple is immutable.
tupledemo.py Output : ('SCET', 'institute', 'of', 'engineering', 'of', 'Surat')
1 my_tuple = ('SCET','institute','of','engineering','of','Surat')
2 print(my_tuple)
3 print(my_tuple.index('engineering')) Output : 3 (index of ‘engineering’)
4 print(my_tuple.count('of'))
Output : 2
5 print(my_tuple[-1])
Output : Surat
30
Dictionary
Dictionary is a unordered collection of key value pairs.
Dictionary will be represented by curly brackets { }.
Dictionary is mutable.
syntax
my_dict = { 'key1':'value1', 'key2':'value2' }
dictdemo.py
1 my_dict = {'college':"SCET", 'city':"Surat",'type':"engineering"}
2 print(my_dict['college']) values can be accessed using key inside square brackets
3 print(my_dict.get('city')) as well as using get() method
Output : SCET
Surat
31
Dictionary methods
keys() method will return list of all the keys associated with the Dictionary.
keydemo.py
1 my_dict = {'college':"SCET", 'city':"Surat",'type':"engineering"}
2 print(my_dict.keys())
Output : ['college', 'city', 'type']
values() method will return list of all the values associated with the Dictionary.
valuedemo.py
1 my_dict = {'college':"SCET", 'city':"Surat",'type':"engineering"}
2 print(my_dict.values()) Output : ['SCET', 'Surat', 'engineering']
items() method will return list of tuples for each key value pair associated with the
Dictionary.
itemsdemo.py
1 my_dict = {'college':"SCET", 'city':"Surat",'type':"engineering"}
2 print(my_dict.items()) Output : [('college', 'SCET'), ('city', 'Surat'), ('type',
'engineering')]
32
Set
Set is a unordered collection of unique objects.
Set will be represented by curly brackets { }.
tupledemo.py
1 my_set = {1,1,1,2,2,5,3,9}
Output : {1, 2, 3, 5, 9}
2 print(my_set)
Set has many in-built methods such as add(), clear(), copy(), pop(), remove() etc.. which are
similar to methods we have previously seen.
Only difference between Set and List is that Set will have only unique elements and List can
have duplicate elements.
33
Operators in python
We can segregate python operators in the following groups
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
We will discuss some of the operators from the given list in detail in some of next slides.
34
Arithmetic Operators
Note : consider A = 10 and B = 3
Operator Description Example Output
+ Addition A+B 13
- Subtraction A-B 7
/ Division A/B 3.3333333333333335
* Multiplication A*B 30
% Modulus return the remainder A%B 1
// Floor division returns the quotient A // B 3
** Exponentiation A ** B 10 * 10 * 10 = 1000
35
Logical Operators
Note : consider A = 10 and B = 3
Operator Description Example Output
and Returns True if both statements are true A > 5 and B < 5 True
or Returns True if one of the statements is true A > 5 or B > 5 True
Negate the result, returns True if the result is
not
False
not ( A > 5 ) False
36
Identity & Member Operators
Identity Operator
Note : consider A = [1,2], B = [1,2] and C=A
Operator Description Example Output
Returns True if both variables are the same A is B FALSE
is
object A is C TRUE
Returns True if both variables are different
is not
object
A is not B TRUE
Member Operator
Note : consider A = 2 and B = [1,2,3]
Operator Description Example Output
Returns True if a sequence with the
in
specified value is present in the object
A in B TRUE
Returns True if a sequence with the
not in specified value is not present in the object A not in B FALSE
37
Operator Precedence
Precedence represents the priority level.
38
Mathematical Functions
In program
import math
x=math.sqrt(16)
print(x)
39
Python Shallow Copy and Deep Copy
In Python, we use = operator to create a copy of an object. You may think that this creates a
new object; it doesn't. It only creates a new variable that shares the reference of the original
object.
copy.py
1 old_list = [[1, 2, 3], [4, 5, 6], [7, 8, 'a']]
Old List: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
2 new_list = old_list ID of Old List: 140673303268168
3 new_list[2][2] = 9
4 print('Old List:', old_list) New List: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
5 print('ID of Old List:', id(old_list)) ID of New List: 140673303268168
6 print('New List:', new_list)
7 print('ID of New List:', id(new_list))
Essentially, sometimes you may want to have the original values unchanged and only modify
the new values or vice versa. In Python, there are two ways to create copies:
Shallow Copy
Deep Copy
40
Shallow Copy
A shallow copy creates a new object which stores the reference of the original elements.
So, a shallow copy doesn't create a copy of nested objects, instead it just copies the reference
of nested objects. This means, a copy process does not recurse or create copies of nested
objects itself.
shallow-add.py
1 import copy
2 old_list = [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
3 new_list = copy.copy(old_list)
4 old_list.append([4, 4, 4])
Old list: [[1, 1, 1], [2, 2, 2], [3, 3, 3], [4, 4, 4]]
5 print("Old list:", old_list) New list: [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
6 print("New list:", new_list)
shallow-update.py
1 import copy
2 old_list = [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
3 new_list = copy.copy(old_list) Old list: [[1, 1, 1], [2, 'AA', 2], [3, 3, 3]]
4 old_list[1][1] = 'AA' New list: [[1, 1, 1], [2, 'AA', 2], [3, 3, 3]]
5 print("Old list:", old_list)
6 print("New list:", new_list)
41
Deep Copy
A deep copy creates a new object and recursively adds the copies of nested objects present in
the original elements.
deep-update.py
1 import copy
2 old_list = [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
3 new_list = copy.deepcopy(old_list) Old list: [[1, 1, 1], ['BB', 2, 2], [3, 3, 3]]
4 old_list[1][0] = 'BB' New list: [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
5 print("Old list:", old_list)
6 print("New list:", new_list)
In the above program, when we assign a new value to old_list, we can see only the old_list is
modified. This means, both the old_list and the new_list are independent. This is because
the old_list was recursively copied, which is true for all its nested objects.
42
If statement
if statement is written using the if keyword followed by condition and colon(:) .
Code to execute when the condition is true will be ideally written in the next line with
Indentation (white space).
Python relies on indentation to define scope in the code (Other programming languages often
use curly-brackets for this purpose).
43
If else statement
Syntax
1 if some_condition :
2 # Code to execute when condition is true
3 else :
4 # Code to execute when condition is false
44
If, elif and else statement
Syntax Else if remove se
1 if some_condition_1 :
2 # Code to execute when condition 1 is true
3 elif some_condition_2 :
4 # Code to execute when condition 2 is true
5 else :
6 # Code to execute when both conditions are false
ifelifdemo.py Run in terminal
1 x = 10 1 python ifelifdemo.py
2
Output
3 if x > 12 :
4 print("X is greater than 12") 1 X is greater than 5
5 elif x > 5 :
6 print("X is greater than 5")
7 else :
8 print("X is less than 5")
45
For loop in python
Many objects in python are iterable, meaning we can iterate over every element in the object.
such as every elements from the List, every characters from the string etc..
We can use for loop to execute block of code for each element of iterable object.
Syntax For loop ends with :
1 for temp_item in iterable_object :
2 # Code to execute for each object in iterable
46
Range in for loop
The range() object is also known as range() function in python is useful to provide a sequence
of numbers.
range(n) gives numbers from 0 to n-1.
If we write range(10), It will give number from 0 to 9 in sequence.
If we write range(5,10), it will give number from 5 to 9
If we write range(1,10,2), it will give number 1,3,5,7,9
Output :
forrange.py
1 forrange1.py Output :
2 1
1 for i in range(1,5): 3 1 for i in range(1,5,2):
2 print(i) 2 print(i) 3
4
47
For loop (tuple unpacking)
Sometimes we have nested data structure like List of tuples, and if we want to iterate with
such list we can use tuple unpacking.
withouttupleunapacking.py withtupleunpacking.py
1 my_list = [(1,2,3), (4,5,6), (7,8,9)] 1 my_list = [(1,2,3), (4,5,6), (7,8,9)]
2 for list_item in my_list : 2 for a,b,c in my_list :
3 print(list_item[1]) 3 print(b)
This
Output : Output :
technique is
2 2
known as
5 5
tuple
8 8
unpacking
range() function will create a list from 0 till (not including) the value specified as argument.
rangedemo.py Output :
0
1 my_list = range(5)
1
2 for list_item in my_list :
2
3 print(list_item)
3
4 48
While loop
While loop will continue to execute block of code until some condition remains True.
For example,
while felling hungry, keep eating
while have internet pack available, keep watching videos
Syntax while loop ends with :
1 while some_condition :
2 # Code to execute in loop
49
break, continue & pass keywords
break : Breaks out of the current closest breakdemo.py
enclosing loop. 1 for temp in range(5) : Output :
2 if temp == 2 : 0
3 break 1
4
5 print(temp)
passdemo.py
Pass : Does nothing at all, will be used 1 for temp in range(5) :
Output : (nothing)
as a placeholder in conditions where you 2 pass
don’t want to write anything.
50
Input Statements
Conversion of a number in any base to Decimal is also possible with int() casting function.
input1.py
1 bin=input(“Enter the number”) Output :
2 a=int(bin,2) Enter the number100
3 print(“number=”,a) number= 4
4 oct=input(“Enter the number”)
5 b=int(oct,2) Enter the number1001
6 print(“number=”,b) number= 9
It is possible to accept more than one data by means of single input() function, split() function
along with for loop.
input2.py
Output :
1 a,b = [x for x in input("enter a and b").split() ]
enter a and b1 2
2 print(a,b)
12
3 a,b = [x for x in input("enter a and b").split(',') ]
enter a and b10,20
4 print(a,b)
10 20
51
Eval() function
The eval() function takes a string and evaluates the result of the string by taking it as a
Python expression.
eval.py
Output: 13
1 a,b=5,10
2 result=eval("a+b-2")
3 print(result)
4 x=eval(input("enter an
5 expression=")) Output: enter an expression=2*10+7
6 print("Result",x) Result 27
52