Python Unit 1
Python Unit 1
Overview of
Python and
Data
Structure
Looping
Outline
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.8.3 (as
of June-2020).
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.8
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 first.py
new file in editor, save it as first.py (Extensions for python
Python line does not end with ;
programs will be .py)
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..
Sequence of character (Ordered) such as “darshan”, ‘college’,
String str
“રાજકોટ” etc..
Logical values indicating Ture or False (T and F here are
Boolean bool Data Structures
capital in python)
Ordered Sequence of objects, will be represented with square
List list brackets [ ]
Example : [ 18, “darshan”, True, 102.3 ]
Ordered immutable sequence of objects, will be represented with
Tuple tup round brackets ( )
Example : ( 18, “darshan”, True, 102.3 )
Unordered collection of unique objects, will be represented with
Set set the curly brackets { }
Example : { 18, “darshan”, True, 102.3 }
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
8
Example of Python variable
Example :
demo.p
y
1 x = 10
2 print(x) Reassign same variable to hold different
3 print(type(x)) data type
4
5 y = 123.456
6 print(y)
7
8 x = “thapar insitute of engneering and technology"
9 print(x)
10 print(type(x))
Run in terminal
1 python demo.py
Output
1 10
2 int
3 123.456
4 thapar institute of engineering and technology
5 str
9
String in python
String is Ordered Sequence of character such as “thapar”, ‘college’,
“રાજકોટ” 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.
“thapar”[1]
String index = t, characters can also be accessed with reverse index like
“thapar”[-1] = r.
x = " t h a p a r "
index = 0 1 2 3 4 5
Reverse index = 0 -6 -5 -4 -3 -2
10
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 = "Darshan" Output : 7 (length of “Darshan”)
2 print(len(x))
11
String methods (cont.)
count() method will returns the number of times a specified value occurs
incountdemo.py
a string.
1 x = "Darshan" Output : 2 (occurrence of ‘a’ in
2 ca = x.count('a')
3 print(ca)
“Darshan”)
title(), lower(), upper() will returns capitalized, lower case and upper
case string respectively.
changecase.py
1 x = "darshan Institute, rajkot"
2 c = x.title() Output : Darshan Institute, Rajkot
3 l = x.lower()
4 u = x.upper() Output : darshan institute, rajkot
5 print(c)
6 print(l) Output : DARSHAN INSTITUTE,
7 print(u) RAJKOT
12
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 = 'darshan institute, rajkot'
2 c = x.istitle() Output : False
3 l = x.islower()
4 u = x.isupper() Output : True
5 print(c)
6 print(l)
7 print(u)
Output : False
strip() method will remove whitespaces from both side of the string and
returns the string.
stripdemo.py
1 x = ' Darshan '
2 f = x.strip() Output : Darshan (without space)
3 print(f)
rstrip() and lstrip() will remove whitespaces from right and left side
respectively. 13
String methods (cont.)
find() method will search the string and returns the index at which they
find the specified value
finddemo.py
1 x = 'darshan institute, rajkot, india'
2 f = x.find('in') Output : 8 (occurrence of ‘in’ in x)
3 print(f)
rfind() will search the string and returns the last index at which they find
rfinddemo.py
the1 specified
x = 'darshanvalue
institute, rajkot, india'
Output : 27 (last occurrence of ‘in’ in
2 r = x.rfind('in')
3 print(r)
x)
Note : find() and rfind() will return -1 if they are unable to find the given
replacedemo.p
string. y
1 x = 'darshan institute, rajkot, india'
Output :
replace() will replace str1 with str2
2 r = x.replace('india','INDIA') from
“darshan our rajkot,
institute, stringINDIA”
and return the
3 print(r)
updated string
14
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 = 'darshan institute, rajkot, india'
2 f = x.index('in') Output : 8 (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
rindexdemo.py
raise
1 x an exception.
= 'darshan institute, rajkot, india'
Output : 27 (last occurrence of ‘in’ in
2 r = x.rindex('in')
3 print(r)
x)
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. 15
String methods (cont.)
isalnum() method will return true if all the characters in the string are
alphanumeric (i.e either alphabets or numeric).
isalnumdemo.p
y
1 x = 'darshan123'
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 : isnuberic() and isdigit() are almost same, you suppose to find the
difference as Home work assignment for the string methods.
16
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 = 'darshan institute of engineering and technology, rajkot, gujarat, INDIA'
subx = x[startindex:endindex:steps]
endindex will not be included in the
strslicedemo.p substring
y
1 x = 'darshan institute of engineering and technology, rajkot, gujarat, INDIA'
2 subx1 = x[0:7]
3 subx2 = x[49:55] Output : darshan
4 subx3 = x[66:]
5 subx4 = x[::2] Output : rajkot
6 subx5 = x[::-1]
7 print(subx1) Output : INDIA
8 print(subx2)
9 print(subx3) Output : drhnisiueo niern n ehooy akt uaa,IDA
10 print(subx4) Output : AIDNI ,tarajug ,tokjar ,ygolonhcet dna gnireenigne fo
11 print(subx5)
etutitsni nahsrad
17
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
strformat.py
formatting.
1 x = '{} institute, rajkot'
2 y = x.format('darshan') Output : darshan institute, rajkot
3 print(y)
Inline function call
4 print(x.format('ABCD'))
Output : ABCD institute, rajkot
18
String print format (cont.)
We can specify the order of parameters in the string
strformat.py
1 x = '{1} institute, {0}'
2 y = x.format('darshan','rajkot') Output : rajkot institute, darshan
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 : darshan institute,
2 print(x.format(collegename='darshan',cityname='rajkot')) rajkot
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
19
Data structures in python
There are four built-in data structures in Python - list, dictionary, tuple and
set.
Name Type Description
Ordered Sequence of objects, will be represented with square
List list brackets [ ]
Example : [ 18, “darshan”, True, 102.3 ]
Unordered key : value pair of objects , will be represented with
Dictionar
dict curly brackets { }
y
Example : { “college”: “darshan”, “code”: “054” }
Ordered immutable sequence of objects, will be represented with
Tuple tup round brackets ( )
Example : ( 18, “darshan”, True, 102.3 )
Unordered collection of unique objects, will be represented
set with the curly brackets { }
Set
Lets explore all the data: {
Example structures in detail…
18, “darshan”, True, 102.3 }
20
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 = ['darshan', 'institute', 'rkot']
2 print(my_list[1]) Output : 3 (length of the List)
3 print(len(my_list))
4 my_list[2] = "rajkot" Output : ['darshan', 'institute', 'rajkot']
5 print(my_list) Note : spelling of rajkot is updated
6 print(my_list[-1])
Output : rajkot (-1 represent last element)
We can
list.pyuse slicing similar to string in order to get the sub list from the list.
1 my_list = ['darshan', 'institute', 'rajkot','gujarat','INDIA']
2 print(my_list[1:3])
Output : ['institute', 'rajkot']
Note : end index not included
21
List methods
append() method will add element at the end of the list.
appendlistdem
o.py
1 my_list = ['darshan', 'institute', 'rajkot']
2 my_list.append('gujarat') Output : ['darshan', 'institute', 'rajkot',
3 print(my_list) 'gujarat']
insert() method will add element at the specified index in the list
insertlistdemo.
py
1 my_list = ['darshan', 'institute', 'rajkot']
2 my_list.insert(2,'of') Output : ['darshan', 'institute', 'of',
3 my_list.insert(3,'engineering') 'engineering', 'rajkot']
4 print(my_list)
extend() method will add one data structure (List or any) to current List
extendlistdem
o.py
1 my_list1 = ['darshan', 'institute']
2 my_list2 = ['rajkot','gujarat']
3 my_list1.extend(my_list2) Output : ['darshan', 'institute', ‘rajkot',
4 print(my_list1) ‘gujarat']
22
List methods (cont.)
pop() method will remove the last element from the list and return it.
poplistdemo.py
1 my_list = ['darshan', 'institute','rajkot']
2 temp = my_list.pop() Output : rajkot
3 print(temp)
4 print(my_list) Output : ['darshan', 'institute‘]
remove() method will remove first occurrence of specified element
removelistdem
o.py
1 my_list = ['darshan', 'institute', 'darshan','rajkot']
2 my_list.remove('darshan')
Output : ['institute', 'darshan', 'rajkot']
3 print(my_list)
clear() method will remove all the elements from the List
clearlistdemo.p
y
1 my_list = ['darshan', 'institute', 'darshan','rajkot']
2 my_list.clear()
Output : []
3 print(my_list)
sort()
sortlistdemo.p
method will sort the elements in the List
y
1 my_list = ['darshan', 'college','of','enginnering','rajkot']
2 my_list.sort() Output : ['college', 'darshan', 'enginnering',
3 print(my_list) 'of', 'rajkot']
4 my_list.sort(reverse=True) Output : ['rajkot', 'of', 'enginnering',
5 print(my_list) 'darshan', 'college']
24
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 : ('darshan', 'institute', 'of', 'engineering',
1 my_tuple = ('darshan','institute','of','engineering','of','rajkot')
'of', 'rajkot')
2 print(my_tuple)
3 print(my_tuple.index('engineering')) Output : 3 (index of ‘engineering’)
4 print(my_tuple.count('of'))
5 print(my_tuple[-1]) Output : 2
Output : rajkot
25
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':"darshan", 'city':"rajkot",'type':"engineering"
2 }
3 print(my_dict['college']) values can be accessed using key inside
print(my_dict.get('city')) square brackets as well as using get() method
Output : darshan
rajkot
26
Dictionary methods
keys() method will return list of all the keys associated with the Dictionary.
keydemo.py
1 my_dict = {'college':"darshan", 'city':"rajkot",'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':"darshan", 'city':"rajkot",'type':"engineering"
2 }
Output : ['darshan', 'rajkot', 'engineering']
print(my_dict.values())
items() method will return list of tuples for each key value pair associated
itemsdemo.py
with the Dictionary.
1 my_dict = {'college':"darshan", 'city':"rajkot",'type':"engineering"
2 }
Output : [('college', 'darshan'), ('city',
print(my_dict.items())
'rajkot'), ('type', 'engineering')]
27
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.
28
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.
29
Arithmetic Operators
Note : consider A = 10 and B = 3
Operator Description Example Output
+ Addition A+B 13
- Subtraction A-B 7
3.3333333333333
/ Division A/B
335
* Multiplication A*B 30
% Modulus return the remainder A%B 1
// Floor division returns the quotient A // B 3
10 * 10 * 10 =
** Exponentiation A ** B
1000
30
Logical Operators
Note : consider A = 10 and B = 3
Operator Description Example Output
Returns True if both statements are
and
true
A > 5 and B < 5 True
Returns True if one of the
or
statements is true
A > 5 or B > 5 True
Negate the result, returns True if the
not
result is False
not ( A > 5 ) False
31
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 A is B FALSE
is
the same object A is C TRUE
Returns True if both variables are
is not
different 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
in the specified value is present in A in B TRUE
the object
Returns True if a sequence with
not in the specified value is not present A not in B FALSE
in the object
32
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).
Syntax if statement ends with :
1 if some_condition :
2 # Code to execute when condition is true
Indentation (tab/whitespace) at the
beginning
33
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
ifelsedemo.p
Run in terminal
y
1 x = 3 1 python ifelsedemo.py
2
3 if x > 5 : Output
4 print("X is greater than 5" 1 X is less than 5
5 )
6 else :
print("X is less than 5")
34
If, elif and else statement
Syntax
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
35
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
Syntax
object. For loop ends with :
1 for temp_item in iterable_object :
2 # Code to execute for each object in iterable
Indentation (tab/whitespace) at the
beginning
fordemo1. fordemo2.
Output : Output :
py py
1 my_list = [1, 2, 3, 4] 1 1 my_list = [1,2,3,4,5,6,7,8,9] 2
2 for list_item in my_list : 2 2 for list_item in my_list : 4
3 print(list_item) 3 3 if list_item % 2 == 0 : 6
4 4 print(list_item) 8
36
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
withtupleunpacking.py
.py
1 my_list = [(1,2,3), (4,5,6), (7,8,9) 1 my_list = [(1,2,3), (4,5,6), (7,8,
2 ] 2 9)]
3 for list_item in my_list : 3 for a,b,c in my_list :
print(list_item[1]) print(b)
This
Output : Output :
technique
2 2
is known
5 5
as 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)
2 for list_item in my_list : 1
3 print(list_item) 2
3
4 37
While loop
While loop will continue to execute block of code until some condition
remains True.
For example,
while felling hungry, keep eating
Syntax
while have internet pack available, keep watching videos
while loop ends with :
1 while some_condition :
2 # Code to execute in loop
Indentation (tab/whitespace) at the Output :
withelse.p X is
beginning
y
1 x = 5 greater
whiledemo.py 2 while x < 3 : than 3
1 x = 0
Output :
3 print(x)
2 while x < 3 : 0 4 x += 1 # x+
3 print(x) 1 5 + is valid in python
4 x += 1 # x++ is valid in python 2 6 else :
print("X is greater than 3")
38
break, continue & pass keywords
break : Breaks out of the current breakdemo.py
closest enclosing loop. 1 for temp in range(5) : Output :
2 if temp == 2 : 0
3 break 1
4
5 print(temp)
passdemo.py Output :
Pass : Does nothing at all, will 1 for temp in range(5) : (nothing)
be used as a placeholder in 2 pass
conditions where you don’t want
to write anything.
39
Functions in python
Creating clean repeatable code is a key part of becoming an effective
programmer.
A function is a block of code which only runs when it is called.
In Python
Syntax a function is defined using the def keyword:
ends with :
def function_name() :
#code to execute when function is called
Indentation (tab/whitespace) at the
beginning Output :
hello world
functiondemo. =====================
py =========
1 def seperator() :
2 print('==============================')
from darshan college
3 =====================
4 print("hello world") =========
5 seperator() rajkot
6 print("from darshan college")
7 seperator()
8 print("rajkot")
40
Function (cont.) (DOCSTRIGN & return)
Doc string helps us to define the documentation about the function within
theSyntax
function itself.
Enclosed within triple quotes
def function_name() :
'''
DOCSTRING: explains the function
INPUT: explains input
OUTPUT: explains output
'''
#code to execute when function is called
41