PYTHON
INTRODUCTION TO PYTHON
• Python is popular programming language. It was created
by Guido Van Rossum in 1991 at CWI(Centrum
Wiskunde & Informatics) Netherlands.
• Python got its name BBC comedy series “Monty python
Flying Circus”
• It is a general purpose , high level programming
language.
• It is an object oriented language.
WHY PYTHON ?
• Simple and Easy to Learn
• Cross Platform
• Free and open Source
• Interpreted Language
• Rich library Support
• Portable
• Variety of Usage and application
WHERE PYTHON IS USED ?
• Web frameworks and applications
• GUI-based desktop applications
• Graphic design
• Image processing applications
• Games, and Scientific/ computational Applications
• ML, AI, Neural networks
• Data science, Data visualization
• Database development
Working in Python
Before we start working on Python we need to install Python in our
computer. There are multiple distributions available today:
• Default Installation available from www.python.org is called
Cpython installation and comes with Python interpreter,
PythonIDLE(Python GUI) and pip(package installer)
• ANACONDA Python distribution is one such highly recommended
distribution that comes with preloaded many packages and
libraries(NumPy, SciPy, Panda etc)
• Other Popular IDEs like Spyder, PyCharm, etc. Spyder IDE is
available as a part of ANACONDA.
TOKENS: The smallest individual unit in a program is called
token.
Python has following tokens:
• Keyword
• Identifier(Name)
• Literal
• Operators
• Punctuators
# a sample program
name=“abc” # string value
age=15 # integer value
contribution=56.7 # float value
print(name, “aged” , age , “has contributed” , contribution)
name, age, contribution are identifier(name of variable),
print is a keyword and (, “ ,# , () ) all are punctuators
PYTHON OPERATORS
Operators are symbols used to perform operations on
values and variables. eg 10+25
Types of Operators in Python
• Unary Operators: are those that require one operand to operate
upon.
Operator Purpose
+ Unary Plus
- Unary minus
~ Bitwise complement
Not Logical Negation
• Binary operators : are those that require two operators to operate
upon.
# python program to demonstrate the use of "//"
print(10//3)
print (-5//2)
print (5.0//2)
print (-5.0//2)
Output:
3
-3
2.0
-3.0
# Python program to demonstrate the use of "/"
print(5/5)
print(10/2) NOTE: Result of true
print(-10/2) division is always a
floating number.
1.0
5.0
-5.0
# Relational operators : compares two values and return result
True or false
In strings be careful while comparison,
a = 13 capital letters are considered less than
b = 33 small case
# a > b is False
print(a > b)
# a < b is True
print(a < b)
# a == b is False
print(a == b)
# Augmented Assignment Operators
When we perform an operation on a variable and store the result
in same variable
a+=b
a=a+b
# Membership Operators : in , not in
x = 24
y = 20
list = [10, 20, 30, 40, 50]
if (x not in list):
print("x is NOT present in given list")
else:
print("x is present in given list")
if (y in list):
print("y is present in given list")
else:
print("y is NOT present in given list")
# Bitwise Operators: are used to change individual bits in any
operand
# Logical Operators: are and, or, not
and and or operators work in 2 ways
1) relational expression as operands eg (8>6)and(6>5) True
2) number, list or string operands
When number/string/list as operand then or operator work as:
If first operand x is false then return y operand as result otherwise
return x
eg 0 or 0 then 0 “abc” or “xyz” then ‘abc’
5 or 0 then 5
When number/string/list as operand then and operator work
as:
If first operand x is false then return x operand as result otherwise
return y
eg 0 and 0 then 0
5 and 0 then 0
‘a’ and ‘j’ then ‘j’
OPERATOR PRECEDENCE
Find output of following code snippet:
1) print(3**2+(6+6)**(1+1)) ans 153
2) print( 3**3**2) ans 19683
3) print(float(22//3+3/3) ans 8.0
4) f=int(3+5/8.0) ans 3
print(f)
5) a,b,c,d=13.2,20,50.0,49
print(a/4)
print(a//4)
print(b**3)
print(c//6)
print(d%5)
6) x,y= -8,-15
print(x//3)
print(8/-3)
• Note – type( ) function is used to determine
the data type of variable
1. a = 5
print("Type of a:",type(a))
O/P:
Type of a: <class 'int'>
2. String1 = “ Hello "
print(String1)
print(type(String1))
O/P
Hello
<class 'str'>
MUTABLE & IMMUTABLE DATA TYPES
Mutable data types in Python are those whose value can be changed in place
after they have been created.
Python has built in function id( ) which return the address of an
object in memory.
>>> my_list = [1, 2, 3]
>>> id(my_list)
55834760
>>> my_list
[1, 2, 3]
>>> my_list[0] = 'a new value’
>>> id(my_list) 55834760
>>> my_list
['a new value', 2, 3]
The value assigned to a variable cannot be changed for the
Immutable data types.
For example, String is an immutable data type in Python. We cannot
change its content, otherwise, we may fall into a TypeError. Even if
we assign any new content to immutable objects, then a new object
is created (instead of the original being modified).
>>> x = 24601
>>> x
24601
>>> id(x)
1470416816
>>> x = 24602
>>> x
24602
>>> id(x)
1470416832
Variables are not like storage containers with fixed memory address where
value changes every time. Each time we change the value the variable
memory address also change. That’s why string, number , tuples are
immutable.
Python is object oriented language. Everything in python is a
object. Object is an entity that has some characteristic , behavior
Every python object has 3 attributes:
• type of object
• value of object
• id of object
type( ) returns the type of object
id( ) returns memory location of object
value The data items stored in object is a value of object. We use
print() to get value of object.
A=100
print(A)
Simple Input and Output
In python we can take input from user using the built-in function input().
Syntax:
Variable= input(<message to display>)
NOTE : value taken by input() function will always be of String type by
default so we will not be able to perform any arithmetic operation on
variable.
>>> marks=input("Enter your marks")
Enter your marks 100
>>> type(marks)
<class 'str’>
Here we can see even we are entering value 100 but it will be treated as
string and will not allow any arithmetic operation. The solution to this
problem is to convert values of input( ) to numeric type using int ( ) or
float( )
Output through print( )
Python allows to display output using print( )
OUTPUT :
Hands On
1) WAP to enter length and breadth and calculate area of rectangle
2) WAP to enter radius of circle and calculate area of circle.
3) WAP to calculate sum and average of 3 numbers
4) The following code is not giving desired output. we want to enter
100 and obtain output as 200. Identify the error and correct it
LOOPS
It means repetition of tasks. There are situations where we want to
repeat same set of tasks again and again eg table of no, factorial of
number etc. To carry out repetition of statements, python provide 2
loop statements:
1) While loop 2) for loop
range( ) function: It is used in for loop to repeat statement n
number of times. Range function generates set of values from
lower_limit to upper_limit-1
Syntax
range(lower_limit, upper_limit, step(optional))
range(1,10) generate values 1 to 9
range(1,10,2) values will be 1,3,5,7,9
1) for loop is used to process items of any sequence like List, Tuple,
String
2) It is used to create loop for fixed number of times like 5,10 times
using range() function
# for loop with list
# print counting
• for loop with range( ) from 1 to 20
2) while loop: It repeat the instructions as long as condition is true. This loop
contains loop elements like initialization , condition, Body of loop, update
statement.
Hands On
1) WAP to print table of a number
2) WAP to calculate factorial of a number
3) WAP to calculate 1+2+3 ____+n
4) WAP to find highest among 3 numbers
5) WA nested loop program to print tables
2 to 10
String Manipulation
• Strings are sequence of characters ,where each character has a
unique index. The indexes of string begin from 0 to (length-1) in
forward direction and -1,-2 …… -length in backward direction.
• Strings are enclosed in quotes of any type- single quotation,
double quotation and triple quotation.
• Strings are immutable data type.
String Operators
1) String Concatenation:
examples : “tea” + “pot” = teapot
‘1’ + ‘1’ = 11
‘123’ + ‘abc’ = 123abc
# you can not combine numbers and strings as operands in + operator
2) String Replication Operator *
Operands data type Operation Example
performed
numbers multiplication 9*9=81
String, number replication “abc”*2= “abcabc”
Number, String replication 3* “#” = “###”
# You can not have strings as both operands with * operator
3) Membership Operator: in, not in
Examples:
#check presence of substring variable
str1='python script’
str2='script’
print('str2 is a part of str1:',str2 in str1 )
Output :
Str2 is a part of str1: True
String Indexing(accessing characters)
Each character in string has an index value. Indexing starts at 0 and must be
an integer. Trying to access a character out of index range will raise an error.
To access any characters of string, we use square brackets along with index.
Positive 0 1 2 3 4 5 6 7 8 9 10 11
Index
a H e l l o w o r l d !
Negative -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
Index
String Slicing
slice() function in python is used to extract a continuous sequence(it may be an
empty sequence, complete sequence or a partial sequence) of any object(array,
string, tuple) .
Syntax :
String_name (start: end: step)
Positive 0 1 2 3 4 5 6 7 8 9
Index
a S a v e M o n e y
Negative -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
Index
String Built In Functions
1) len( ) : returns length of string
2) capitalize( ) : returns copy of string with first letter capitalized
3) title( ) : converts first letter of every word in uppercase and remaining
letters in lower case
4) count( ) : count the occurrences of substring in string
5) find( ) 6) index ( )
Return the index position of substring It returns the index where specified
in string substring is found
Returns -1 if not found Raises value error if substring not
found
7) isalnum( ) : Returns true if characters in string
are alphabets or numbers.
Returns true if characters in string are
alphanumeric
8) isalpha( ) : Returns true if all characters in
string are alphabets.
Returns true if characters in string are
alphanumeric
9) isdigit( ) : Returns true if all characters in
string are digits.
Returns true if characters in string ar
10) islower( ) : returns True if all characters in string are lowercase.
11) isupper( ) : returns True if all characters in string are uppercase.
NOTE: Both islower( ) and isupper( ) check
the case for letters only, symbol present in
string are ignored.
12) lower( ) : returns copy of string converted to lowercase.
13) upper( ) : returns copy of string converted to uppercase.
14) replace(old, new ) : returns copy of string with all occurrences of substring
replaced with new string.
15) split( ) : It splits a string based on given character or string.
16) partition( ) : It splits a string at first occurrence of separator and return
tuple with 3 items..
17) startswith( ): Returns True if string starts with substring sub
18) endswith( ): Returns True if string ends with substring sub
19) strip( ) : returns a copy of string with leading and trailing whitespaces
removed
Hands on
1) WAP to accept a string and print individual word of it along its length.
2) To check whether a string is palindrome or not [67]
3) Program to count vowels in string
4) WAP to enter a string and count lowercase letters, uppercase letters, digits
and alphabets.
5) Find output
List Manipulation
• List is an ordered sequence that is mutable and made of one or
more elements.
• A list can have elements of different data types, such as integer,
float, string, tuple or even another list.
• Elements of list are enclosed in square brackets and are separated
by comma.
• List indices also start from 0.
Creating a List from Sequence
The list( ) method takes sequence type and convert a given record, tuple or
string into list.
From the above code whatever values we will enter will be of string type.
Most commonly used method to enter list is eval(input( ))
Accessing List elements
List indices start from 0 and go to length-1. We can access the
elements of list either moving from left to right(+ve index) or from
right to left(-ve index). Each element of list can be accessed through
their indexes enclosed inside square brackets.
Updating A list
Lists are mutable we can assign
a new value to an existing
value.
Syntax:
List[index]=<new value>
Traversing a list
It means accessing each element of a list. The elements of list
can be accessed individually using for loop and in operator.
WAP to find sum of all elements in list
Operations on List
List manipulation in Python can be done using various operators like
concatenation (+), repetition (*), slicing of the list, and membership
operators( in /not in).
1) CONCATENATION
The (+) operator is used to add to two lists.
The syntax of the given operation is: List1+List2
NOTE: + operator when
used with list ,requires
both operands of list type
2. REPITITION/REPLICATION
(*) operator replicates the list number of specified times.
The syntax of the given operation: List*n
Note: List multiplication by another list generate error
3. MEMBERSHIP TESTING
The membership operator checks whether an element exists in the given
list.
•in: Return True if an element exists in the given list; False otherwise
•not in: Return True if an element does not exist in the given list; False
otherwise.
4. List Slicing in Python
List slicing returns a slice or part of the list from the given index range x to y.
(x is included but y is not included).
The syntax of the list slicing is: List[ start: stop: step_value]
Slices for List Modification:
We can use slices to overwrite one or more list elements with one or
more elements.
The values being assigned must be
a sequence i.e list, string, tuple
Making Copy of List
list( ) and copy ( ) are used for copying a list
a and b are different list. Changes made in one
list will not be reflected in other list.
But if we simply assign
a=[1,2,3]
b=a
It is just an alias of a .Changes made in one list
will be reflected in other list also . So use list()
and copy( ) method for creating true copy of list.
LIST BUILT IN FUNCTIONS
Function Description Example
len( ) Return length of list
index( ) Returns the index of first
matched item. If item is not
found then raise value error
append( ) Add a single item to list. It
does not return new list,
original is modified
In append( ) len is increased by 1
extend( ) Adds multiple item (given in
form of list) to a list. In
extend() length is increased
by length of inserted list
insert( ) It inserts the item at a given
position.
Syntax:
list.insert(<ind>,<item>)
Function Description Example
pop( ) Remove item from given
list.pop(index position in list and return
) it. If index not given then
remove last item
remove( ) It remove the first
list.remove( occurrence of given item in
value) list
clear( ) Removes all item from list
and list becomes empty
count( ) Count the item that we
passed as an argument
sort( ) Sort the elements in
increasing order
reverse( ) Reverses the order of list Both sort() and reverse()
functions done in place ,a new
list is not created
sorted( ) A new list is created with
sorted version of list
Hands On
WAP to read a list of elements. Input an element from the user that has
to be inserted and input the position at which element is to be inserted.
Apply a built in function to insert an element at desired position.
WAP to create a copy of list. In list’s copy add 10 to its first and last
element. Then display the list
WAP to find sum of elements in list
WAP to input a number and count the occurrences of that no in list
WAP to input 2 lists and display the maximum element from elements of
both list combined , along with its index in its list.
WA menu driven program to perform list operations
a) Append b) Insert c) Append a list to another list
d) Modify element e) Delete element from given position
f) Delete element with given value
TUPLES
Tuple is a sequence data type similar to list. A tuple consist of multiple values
separated by commas. Tuples are enclosed in ( ). Its elements can be
heterogenous . The elements of tuple are addressed using index value. The
index value of tuple start with 0.
Tuples are immutable, we cannot change the elements of tuple in place. This
means we cannot perform insert, update and delete operations on them.
Note: Tuple are immutable but member objects may be mutable.
T= (“hello”,1,5,9.7,”python”) # heterogenous tuple
T= ( ) # empty tuple
T= (10,20,30) or
T=10,20,30 # a tuple can be represented without parentheses
T= ((1,2,4),(6,7,5)) # Nested tuple
If a tuple consist of single element ,then element should be followed by a
comma
Tup=(70,) # Singleton tuple
Tuple is immutable data type, if we modify an element of tuple, it will show
an error.
Creating Tuple
1. Tuple can be created using function tuple ( )
2. Creating tuple with single element:
It is mandatory to type comma after
single value , otherwise it is treated
as string or integer
3. Creating tuple from sequence
T=tuple(sequence)
We can also use eval ( ) func to input elements of tuple
ACCESSING A TUPLE
The elements of tuple can be accessed through indexes given in
square brackets .The tuple index can be positive or negative integer
value . Positive value of index means counting forward from
beginning of tuple and –ve index means counting backward from end
of tuple.
TRAVERSING A TUPLE
It means accessing each element of tuple one after other at the same
time.
Traversing using for loop Traversing using range function
Unpacking Tuple: Creating tuple from set of elements is packing
and creating individual values from tuple elements is unpacking of
tuples. Syntax for unpacking
<var1> , <var2> ,<var3>,…=t
NOTE: Unpacking requires
that list of variables on left
has the same no of elements
as the length of tuple
TUPLE BUILT IN FUNCTIONS
len( ): This functions returns the length of a tuple.
count( ): It is used to count occurrences of item in a tuple.
max( ): This function returns the element with maximum value.
min( ): This function returns the element with minimum value.
any( ): This function returns True if a tuple is having at least one item. If
tuple is empty, it return False.
sum( ): This function return the sum of elements of tuple. It work on numeric
values only.
sorted( ): It returns the new sorted list with sorted elements in it.
index( ): It find the first index of specified item and return the index.
Indirectly modifying Tuple :
Use the functions tuple( ) and list ( )
Hands On
1) A tuple stores (11,21,31,42,51), where its last 2 nd element is mistyped.
WAP to correct its last second element as 41
2) WAP to input n numbers from user , store these numbers in tuple and
print maximum, minimum , sum and mean of all elements in a tuple
3) WAP to input a tuple and create 2 new tuples from it, one containing
every 3rd element in reverse order, and other containing every alternate
elements between 3rd to 9th element
4) Find the output
5) Find the output
6) WAP to check if a tuple contains any duplicate elements in it.
7) WAP to input name of n students and store them in a tuple. Also input
a name and find this student exist in tuple or not
DICTIONARY
It is an unordered collection of items where each item is a key-value pair.
Each key maps to a value.
Each key is separated from its value by a colon (:). The dictionary is
enclosed in { }
Keys are unique and immutable and values are mutable.
The elements in dictionary are indexed by keys not by positions or
indices.
Values of dictionary can be of any type, but keys must be of immutable
type such as string, tuple, numbers .
Dictionary is mutable.
d= { } # empty dictionary
d= {“R”: “Rainy”, “S” : “Summer” , “W”: “Winter”} # dictionary with key
value pair
CREATING DICTIONARY
Accessing Elements in a dictionary
Elements are accessed with square brackets along with keys to obtain value
Syntax:
dict_name(key).
Traversing a Dictionary
Appending values to Dictionary: dictname[“key”]=value
Updating Values to Dictionary
Two dictionaries can be merged in one by update( ) method. It merges key
value of one dictionary with other and overwrites values of same key.
Syntax:
Dic1.update(dic2)
Removing Item from Dictionary : del dictname[“key”]
“del” is used to delete the key present in dictionary . If key is not found then
raises an error.
2. pop( ) method not only deletes the item specified by key but also return the
deleted value.
• get( ) method : give value of given key
• items( ): It returns the content of dictionary as a list of tuples
• keys( ): It returns a list of keys from key value pair.
• values( ): It returns a list of values from key value pair.
• copy( ): If we copy a dictionary using (=) it will create a reference to same
dictionary and modification will be in both dictionaries. So use copy( ) to
create a new dictionary and modification done on base dictionary will not
be reflected
• fromkeys( ): This is used to create dictionary from collection of keys.
• zip( ): clubs first value from first set with first value of second set , second
value from first set with second value of second set and so on.
• popitem( ): This is used to remove last item from dictionary. Items are
removed in LIFO order.
Calculating Maximum, Minimum and Sum
• Dictionary having homogeneous keys can be compared.
• The sum( ) function can work with dictionaries having keys
which are addition compatible.
HANDS ON
1) WAP to create a dictionary M which stores the marks of students of class
with roll no as keys and marks as values.
2) Consider already created dictionary M. WAP to input a roll no and delete
it from dictionary. Display error msg if roll no does not exist in the
dictionary.
3) Your school has decided to give scholarship of rs2500 to some selected
students. WAP to input selected students roll no and create a dictionary.
4) WAP to delete keys of a dictionary in LIFO order.
stu={1:”neha”, 2: “Sneha” , 3: “Avneet”, 4: “Aena” ,5: “Mona”}
5) WAP to print the maximum, minimum, sum of keys of numbers
numbers={1:111,2:222 , 3: 333 , 4: 444}
Also find maximum, minimum, sum of values of numbers
6) What is the result of following?
dict={ “jo” :1 , “Ra” : 2}
dict.update({“ph” : 2})
print(dict)