Core Python
Core Python
MOHAN REDDY
MOHAN S. REDDY
Table of Contents
INTRODUCTION TO PYTHON _____________________________________________________________________ 4
IDENTIFIERS: _________________________________________________________________________________ 12
Page 2 of 118
MOHAN S. REDDY
Page 3 of 118
MOHAN S. REDDY
Introduction to PYTHON
Python is a simple, easy to learn, powerful, high level and object-
oriented programming language.
Python is an interpreted scripting language also.
Python was developed by Guido Van Rossum and Released in
1991.
Python is a general purpose, dynamic, high level and interpreted
programming language.
It supports Object Oriented programming approach to develop
applications.
It is simple and easy to learn and provides lots of high-level data
structures.
Python is easy to learn yet powerful and versatile scripting language
which makes it attractive for Application Development.
Python supports multiple programming pattern, including object
oriented, and functional or procedural programming styles.
We don't need to use data types to declare variable because it
is dynamically typed so we can write a=10 to assign an integer value
in an integer variable.
Page 4 of 118
MOHAN S. REDDY
Features of PYTHON:
2. Expressive Language
Python language is more expressive means that it is more
understandable and readable.
3. Interpreted Language
Python is an interpreted language i.e. interpreter executes the code
line by line at a time. This makes debugging easy and it’s suitable for
beginners.
4. Cross-platform Language
Python can run equally on different platforms such as Windows,
Linux, Unix and Macintosh etc. So, we can say that Python is a
portable language.
Page 5 of 118
MOHAN S. REDDY
6. Object-Oriented Language
Python supports object-oriented language and concepts of classes
and objects come into existence.
7. Extensible
It implies that other languages such as C/C++ can be used to
compile the code and thus it can be used further in our python code.
10. Integrated
It can be easily integrated with languages like C, C++, and Java etc.
Page 6 of 118
MOHAN S. REDDY
Versions of PYTHON:
Python 0.9.0 - February 20, 1991
Python 0.9.1 - February, 1991
Python 0.9.2 - Autumn, 1991
Python 0.9.4 - December 24, 1991
Python 0.9.5 - January 2, 1992
Python 0.9.6 - April 6, 1992
Python 0.9.8 - January 9, 1993
Python 0.9.9 - July 29, 1993
Python 1.0 - January 1994
Python 1.2 - April 10, 1995
Python 1.3 - October 12, 1995
Python 1.4 - October 25, 1996
Python 1.5 - December 31, 1997
Python 1.6 - September 5, 2000
Python 2.0 - October 16, 2000
Python 2.1 - April 15, 2001
Python 2.2 - December 21, 2001
Python 2.3 - July 29, 2003
Python 2.4 - November 30, 2004
Python 2.5 - September 19, 2006
Python 2.6 - October 1, 2008
Python 2.7 - July 4, 2010
Python 3.0 - December 3, 2008
Python 3.1 - June 27, 2009
Python 3.2 - February 20, 2011
Python 3.3 - September 29, 2012
Python 3.4 - March 16, 2014
Python 3.5 - September 13, 2015
Python 3.6 - December 23, 2016
Python 3.7 - June 27, 2018
Python 3.8- Oct 14,2019
Python 3.9 –Oct 5,2020
Current Stable version is 3.11.0
Page 7 of 118
MOHAN S. REDDY
History of PYTHON:
Page 8 of 118
MOHAN S. REDDY
Applications of PYTHON
Web Applications
Desktop GUI Applications
Network Programming
Gaming Applications
Data Analysis Applications
Console Based Applications
Business Applications
Audio and Video Based Applications
Go to Google
|
Type: python download for windows
|
Click on Python.org
|
Click on Download python 3.10.0
|
It will be download python 3.10.0.Exe
|
Open Python 3.10.0.Exe
|
Activate the Checkbox Add Python path
|
Click on Install now
|
Click on Next, Next, Install
Page 9 of 118
MOHAN S. REDDY
INERPRETER COMPILER
It will check line by line and execute. It will check Whole program at a time.
If any error occurs interpreter stops It Checks all statements in the program
Hence it shows only one error and show all errors in program
Page 10 of 118
MOHAN S. REDDY
Python Indentation:
Ex:
a=10
if a==10:
print("true")
Page 11 of 118
MOHAN S. REDDY
Python Comments:
Comments are very important while writing a program.
Python Interpreter ignores comment.
Python supports two types of comments:
Single line comment:
Identifiers:
A Name in python program is called identifier.
It can be a class name or function name or variable name.
Page 12 of 118
MOHAN S. REDDY
Python Variables:
Multiple Assignments:
Ex1:
a=b=c=10
print(a)
print(b)
print(c)
Page 13 of 118
MOHAN S. REDDY
Ex2:
a=b=c=10
print(a,b,c,sep=",")
Ex1:
a,b,c=10,20,30
print(a)
print(b)
print(c)
Ex2:
a,b,c=10,20,30
print(a,end=",")
print(b,end=",")
print(c)
Page 14 of 118
MOHAN S. REDDY
Python Keywords:
Python Keywords are special reserved words which convey a special
meaning to the interpreter.
Each keyword have a special meaning and a specific operation.
These keywords can't be used as variable. Following is the List of
Python Keywords.
import keyword
print(keyword.kwlist)
Output:
['False', 'None', 'True', ' peg_parser ',
'and', 'as', 'assert', 'async', 'await',
'break', 'class', 'continue', 'def', 'del', 'elif',
'else', 'except', 'finally', 'for',
'from', 'global', 'if', 'import', 'in', 'is',
'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise',
'return', 'try', 'while', 'with', 'yield']
Page 15 of 118
MOHAN S. REDDY
None:
When we have a variable which is not assigned any value is called
None.
Normally in any language the keyword can be use null, but in python
we use None.
Ex:
a=None
print(a)
print(type(a))
Page 16 of 118
MOHAN S. REDDY
Examples:
a=10
print(a)
print(type(a)) >>> <class ‘int’>
a=10.9
print(a)
print(type(a)) >>> <class ‘float’>
a=10j
print(a)
print(type(a)) >>> <class ‘complex’>
Page 17 of 118
MOHAN S. REDDY
a=10.8
print(a)
print(type(a))
b=int(a)
print(b)
print(type(b))
Page 18 of 118
MOHAN S. REDDY
Ex: a+bj
10+20j
a and b are integers or float values
Ex:
a=9
b=8
c=complex(a,b)
print(c)
print(type(c))
print(c.real)
print(c.imag)
Note: Complex data type has some inbuilt attributes to retrieve the
real part and imaginary part.
We can use complex type generally in scientific Applications and
electrical engineering Applications.
Page 19 of 118
MOHAN S. REDDY
Bool:
We can use this data type to represent Boolean values.
The only allowed values for this data type are: True and False
Internally Python represents True as 1 and False as 0
Ex:
a=5
b=6
c=a<b
print(c)
print(type(c))
print(int(c))
print(int(True))
print(int(False))
print(True+True)
print(4+True)
String:
Page 20 of 118
MOHAN S. REDDY
Ex:
s="durgasoft"
print(s)
print(type(s))
s='durga\'s'
print(s)
s='''durgasofthyderabadmaitrivanam'''
print(s)
List:
List is ordered collection of elements.
We can create list by using [].
List will allow duplicate elements.
List will allow different data type elements
List is mutable, once we create a list that can be modified.
Ex:
l= [10,10,"durga",23.4,20,'A']
print(l)
print(type(l))
Page 21 of 118
MOHAN S. REDDY
Tuple:
Tuple is ordered collection of elements same as list.
We can create tuple by using () but brackets are optional.
Tuple will allow duplicate elements.
Tuple will allow different data type elements
Tuple is immutable, once we create a tuple that cannot be modified.
Creating a tuple with one element is bit different, to create a tuple with
one element ,after element we have to give comma(,)
Ex1:
t=(10,10,"durga",23.4,20,'A')
print(t)
print(type(t))
Ex2:
t=(10,)
print(t)
print(type(t))
Set:
Set is unordered collection of unique elements.
We can create by using {}
Set will allow different data type elements.
Set will not allow duplicate elements.
Set is mutable, we can modify the set.
To create an empty set then we use set() function.
Page 22 of 118
MOHAN S. REDDY
Ex1:
s=set() print(s)
print(type(s))
Ex2:
s={10,"sai",12.4,'A',10}
print(s)
print(type(s))
Dict:
Dict is a collection of items.
In dict each item can be a pair i.e. key and value.
We can create dict by using {}
In dict keys are immutable and must be unique.
In dict values are mutable and no need to be unique.
In dict keys and values can be of any data type.
In dict keys cannot be modified but values can be modified.
Ex1:
d={}
print(d)
print(type(d)
Ex2:
d={1:"sai",2:"mohan",'a':'apple',3:34.5,
1:"moha n"}
print(d)
print(type(d))
Page 23 of 118
MOHAN S. REDDY
Range:
Range is used to generate range of values.
By default, range starts from 0
Range is immutable; we cannot change the range values.
Ex:
r=range(10)
print(r)
print(type(r))
r=range(list(10))
print(r)
r=range(list(2,20,2))
print(r)
Page 24 of 118
MOHAN S. REDDY
Python Operators:
Operator is a symbol which is used to perform required operations.
5+2=7, here +, = are operators and 5, 2 are operands.
Python supports the following operators
Arithmetic
Relational
Assignment
Logical
Membership
Identity
Bitwise
Arithmetic Operators:
Arithmetic operators are used to perform mathematical operations like
addition, subtraction, multiplication and division.
Operator Description
+ It perform Addition
- It Perform subtraction
* It Perform Multiplication
/ It Perform Division
Page 25 of 118
MOHAN S. REDDY
Ex:
print(2+3)
print(4-1)
print(5*2)
print(5**2)
print(5/2)
print(5//2)
print(5%2)
Relational Operators:
Relational operators are used for comparing the values. It either
returns True or False according to the condition. These operators are
also known as Comparison Operators.
Operator Description
< Less than
> Greater than
Ex:
print(35)
print(4<=4)
print(5>=5)
print(3==3)
print(3!=3)
Page 26 of 118
MOHAN S. REDDY
Assignment Operators:
Assignment Operators are used to assigning values to variables.
Operator Description
= Assignment
Ex:
a=5
print(a)
a+=2
print(a)
a*=2
print(a) a/=2
print(a) a//=2 print(a)
a=5
print(a) a**=2
print(a) a%=2
print(a)
Page 27 of 118
MOHAN S. REDDY
Logical Operators:
Operator Description
Ex:
print(2<3 and 4<5)
print(2<3 and 4>5)
print(2<3 or 4>5)
print(2<3 or 1<2)
print(1>2 or 2>3)
print(not(2<3))
print(not(1>2))
Page 28 of 118
MOHAN S. REDDY
Membership Operators:
Membership operators are used to test if a given value or object is
present in sequence or not.
Operator Description
Ex:
lst=[2,3,4,5]
print(2 in lst) print(100 in lst)
print(100 not in lst)
print(2 not in lst)
Page 29 of 118
MOHAN S. REDDY
Identity Operators:
Operator Description
Ex:
a=2
b=2
print(a is b)
print(a is not b)
a=2
b=3
print(a is b)
print(a is not b)
Page 30 of 118
MOHAN S. REDDY
Id ( ):
It is a built-in function which is used to find memory address of
variables or any object in python.
id () will return unique integer value.
Ex:
a=2b=2
print(id(a))
print(id(b))
print(id(a)==id(b))
a=2
b=3
print(id(a))
print(id(b))
a='mohan' b='Mohan'
print(id(a))
print(id(b))
print(id(a)==id(b))
Page 31 of 118
MOHAN S. REDDY
Bitwise Operators:
Page 32 of 118
MOHAN S. REDDY
Ex:
a=9
b=5
print(bin(a))
print(bin(b))
print(bin(a&b))
print(a&b)
print(a|b)
print(a^b)
print(~a) #~a=-(a+1)
print(a<<2)
print(a>>2)
Page 33 of 118
MOHAN S. REDDY
Conditional statements:
If
If else
Nested if
Elif
if : Syntax:
if condition:
Statements
Ex:
i=100
if i==100:
print("true")
Page 34 of 118
MOHAN S. REDDY
if else: Syntax:
if condition:
Statements
else:
Statements
i=int(input("Enter a number:"))
if i%2==0:
print(i,"is even")
else:
print(i,"is odd")
Ex: program to find biggest of two numbers
i=int(input("Enter num1:"))
j=int(input("Enter num2:"))
if i>j:
print(i, "is big")
else:
print(j, ”is big”)
Page 35 of 118
MOHAN S. REDDY
if condition:
Statements
else:
if condition:
Statements
else:
Statements
Ex:
i=int(input("Enter num1:"))
j=int(input("Enter num2:"))
if i>j:
print(i,"is greater than",j)
else:
if i<j:
print(i,"is less than ",j)
else:
print(i,"is equal to",j)
Page 36 of 118
MOHAN S. REDDY
elif: Syntax:
if condition1:
Statements
elif condition2:
Statements
elif condition3:
Statements
else:
Statements
i=int(input("Enter num1:"))
j=int(input("Enter num2:"))
k=int(input("Enter num3:"))
Page 37 of 118
MOHAN S. REDDY
Ex:
n=int(input("Enter number:"))
if n==1:
print("ONE")
elif n==2:
print("TWO")
elif n==3:
print("THREE")
elif n==4:
print(“FOUR”)
else:
print("Invalid number")
Ex:
n=int(input("Enter number:"))
if n==1:
print("ONE")
else:
if n==2:
print("TWO")
else:
if n==3:
print("THREE")
else:
if n==4:
print("FOUR")
else:
print("Invalid number")
Page 38 of 118
MOHAN S. REDDY
Iterative statements:
If we want to execute a group of statements multiple times then we
should go for iterative statements.
For loop
While loop
For loop:
For loop is used to iterate the elements of collection or sequence what
the order they appear.
Ex1:
l=[10,20,30,40,50,60]
for i in l:
#print(i)
print(i,end=' ')
Ex2:
for i in [10,"sai",23.4,50,'A']:
print(i,type(i))
Ex3:
for i in range(10):
print(i)
Page 39 of 118
MOHAN S. REDDY
for i in range(21):
if i%2==0:
print(i)
n=int(input("Enter number:"))
sum=0
for i in range(n+1):
sum=sum+i
print("sum of first",n,"numbers:",sum)
Note: For every iteration of outer loop, inner loop should finish its all iterationsthen only the
outer loop starts with its next iteration.
Page 40 of 118
MOHAN S. REDDY
Ex:
numlsit=[1,2,3]
charlist=['a','b']
for n in numlsit:
print(n)
for c in charlist:
print(c)
While loop:
If we want to execute a group of statements iteratively until some
condition false, then we should go for while loop.
Ex:
i=1
while i<=10:
print(i)
i+=1
n=int(input("Enter number:"))
sum=0
i=1
while i<=n:
Page 41 of 118
MOHAN S. REDDY
sum=sum+i
i+=1
print("Sum of first",n,"numbers is:",sum)
Ex: Infinite loop
i=0
while True:
i+=1
print("Hello",i)
Transfer statements:
Transfer statements alter the way a program gets executed. These
statements are often used in loop statements.
Break
Continue
Pass
Break:
We can use this inside loops to stop the execution based on condition.
Ex:
for i in range(10):
if i==5:
break
print(i)
Ex:
i=1
while i<=10:
Page 42 of 118
MOHAN S. REDDY
print(i)
i = i + 1
if i == 5:
break
Continue:
We can use this to skip the current iteration and continue with next
iteration.
Ex:
for i in range(10):
if i==5:
continue
print(i)
Ex:
for i in range(10):
if i==5 or i==7:
continue
print(i)
Ex:
i=1
while i<=10:
print(i)i+=1
if i==5:
i+=1
continue
Page 43 of 118
MOHAN S. REDDY
Pass:
It is a keyword in python.
If we want to define the empty block then we use pass keyword.
Ex:
i=10
if i==10:
pass
else:
pass
Ex:
for i in range(10):
pass
String functions:
To get complete string functions
Ex:
print(dir(str))
Ex:
help(str)
Page 44 of 118
MOHAN S. REDDY
Ex:
# -9 -8 -7 -6 -5 -4 -3 -2 -1
# d u r g a s o f t
# 0 1 2 3 4 5 6 7 8
s="hyderabad"
print(s[0])
print(s[-1])
print(s[8])
print(s[12])#index error:string index out ofrange
s="hyderbad"
print(s[2:7])
print(s[:6])
print(s[1:])
print(s[:])
print(s[0:9:1])
print(s[::-1])
print(s[7:1]) #empty stringprint(s[-1:-5])
print(s[-5:-1])
Page 45 of 118
MOHAN S. REDDY
Ex:
s1="durga"
s2="soft"
print(s1+s2)
print(s1+" "+s2)
print("mohan"+" "+"kumar")
Ex:
print(s1*3)
print((s1+" ")*3)
print(("mohan"+" ")*3)
Page 46 of 118
MOHAN S. REDDY
Ex:
#s="d u r g a s o f t"
s="python is very easy and it is oop and it is
interpreter"
print(s)
s1=s.split(" ",3)
print(s1)
print(type(s1))
Ex:
for i in s1:
print(i)
Ex:
s="durgasoft"
print(s)
print(s.upper())
s="DURGASOFT"
print(s)
print(s.lower())
String count
Count method is used to count the no of occurrences of substring
which is present in given string.
Ex:
s="python is very easy and it is oop and it is
interpreter"
substring="is"
print(s.count(substring))
print(s.count("and"))
print(s.count("is"))
print(s.count("x"))
print(s.count(" "))
print(s.count('a'))
Page 48 of 118
MOHAN S. REDDY
String replace:
Replace method is used to replace the string.
As we know that string is immutable, so that after replace the string
better to
Store a new string into a separate variable.
Ex:
s="my name is durga"
print(s)
s1=s.replace("durga","mohan")
print(s1)
#or #print(s.replace("durga","mohan"))
String join
Join method is used to concatenate a string
Join method will return a string.
Ex:
print(",".join("MOHAN"))
print(" ".join(["sai","mohan","raj","durga"]))
String reverse
Using reversed method of join, we can reverse the string.
Ex:
print(" ".join(reversed("SAI")))
#or
s="SAI"
print(s[::-1])
Page 49 of 118
MOHAN S. REDDY
String sort
There is no sort method in string
Use the list sort for sorting string.
Ex:
s="python is very easy"
print(s)
s1=s.split(" ")
print(s1)
print(type(s1))
s1.sort()
print(s1)
s1.sort(reverse=True)
print(s1)
Ex:
s="DuRgAsOfT"
print(s)
print(s.swapcase())
Page 50 of 118
MOHAN S. REDDY
Ex:
s=" durga "
print(s)
print(s.strip(" "))
Ex:
s="adurga"
print(s)
print(s.strip('a'))
print(s.lstrip('a'))
print(s.rstrip('a'))
String length
Len is a built-in function and it is used to find length of the string.
Ex:
print(len("durga soft"))
Page 51 of 118
MOHAN S. REDDY
print(s.find("is"))
print(s.find("x"))
print(s.index("is"))
#print(s.index("x"))
print(s.rindex("is"))
Page 52 of 118
MOHAN S. REDDY
Ex:
print(ord(‘A’))
Ex:
s="durgasoft"
print(max(s))
print(min(s))
Ex:
s="DURGASOFT"
print(max(s))
print(min(s))
String partition
Splits the string at the first occurrence of the separator and returns a
tuple.
Ex:
s="python is very easy and it is oop"
s1=s.partition("is")
print(s1)
print(type(s1))
Page 53 of 118
MOHAN S. REDDY
Ex:
s="durgasoft"
print(s.startswith('a'))print(s.startswith('D'))
print(s.startswith('d'))
print(s.endswith('T'))
print(s.endswith('t')
Page 54 of 118
MOHAN S. REDDY
s="12345"
print(s.isdigit())s="12345a"
print(s.isdigit())
s="abcd"
print(s.isalpha())
s='abcd12'
print(s.isalpha())
s="abcd"
print(s.isalnum())
s="1234"
print(s.isalnum())
s="123abc"
print(s.isalnum())
s="$%#%"
print(s.isalnum())
Page 55 of 118
MOHAN S. REDDY
List functions:
List index
List is zero based index; string index starts with 0
List supports positive and negative index
Positive index is from left to right and starts with 0
Negative index from right to left and starts with -1
Ex:
# 0 1 2 3 4 5 6 7 8 9
l=[10,20,"sai",30,40,"durga",'A',23.4,50,60]
print(l[1])
print(l[-1])
print(l[-4])
#print(l[10])#Index Error: list index out of
range
print(l[1:6])
#nested list
# 0 1 2 3 4 5 6 7
# 0 1 2
l=[10,20,"sai",[30,40,"durga"],'A',23.4,50,60]
print(l[3])
print(l[3][1])
print(l[-5][-2])
Page 56 of 118
MOHAN S. REDDY
List slice
List slice means to get some part of the list
Slice operator [:]
Ex:
# 0 1 2 3 4 5 6 7 8 9
l=[10,20,"sai",30,40,"durga",'A',23.4,50,60]
print(l[1:5])
print(l[:4])
print(l[1:])
print(l[:])
Page 57 of 118
MOHAN S. REDDY
Ex:
l=[2,3,4]
print(l)
l[1]=33# 1 is index and 33 is value
print(l)
l=[2,3,4]
print(l)
l.insert(1,33)# 1 is index and 33 is value
print(l)
l=[2,3,4]
print(l) l.append(33)
l.extend([45,67,89,"sai"]) print(l)
Page 58 of 118
MOHAN S. REDDY
Ex:
l=[10,20,30,40,50]
print(l)
l.remove(20)
#l.remove(33) #ValueError: list.remove(x): x not in
list
l=[10,20,30,40,50]
print(l)
l.pop(2)
l.clear()
del l print(l)
Page 59 of 118
MOHAN S. REDDY
List sort
Sort method is used to display the list values ascending or descending
order.
By default sort method will display the list elements in ascending
order.
to display descending order then we use reverse = True.
Ex:
l=[2,6,9,4,3,5,7,1]
print(l)
l.sort()
print(l)
l.sort(reverse=True)print(l)
List copy
Shallow Copy reflects changes made to the new/copied object in the
original object.
Deep copy doesn’t reflect changes made to the new/copied object in
the original object.
Shallow copy is faster. Deep copy is comparatively slower.
Ex:
l1=[10,20,30,40,50]
print(l1)
#l2=l1
l2=l1.copy()
l1[1]=33
print(l1)print(l2)
print(id(l1))
print(id(l2))
Page 60 of 118
MOHAN S. REDDY
'''l.append(item1)
l.append(item2)
l.append(item3)'''
l.extend([item1,item2,item3])
print(l)
Page 61 of 118
MOHAN S. REDDY
Page 62 of 118
MOHAN S. REDDY
tuple functions:
Ex:
t=(10,20,30)
print(t) print(type(t))
#t[1]=33 #TypeError: 'tuple' object does not support
item assignment
del t print(t)
Page 63 of 118
MOHAN S. REDDY
Ex:
t=(10,20,-34,23.4,50)
print(len(t))
print(max(t))
print(min(t))
print(sum(t))
print(sum(t,4))
t=tuple(s)
print(t)
print(type(t))
Page 64 of 118
MOHAN S. REDDY
t=a,b,c
print(t)
print(type(t))
#unpacking
t=(100,200,300)
a,b,c=t
print("a=",a)
print("b=",b)
print("c=",c)
Page 65 of 118
MOHAN S. REDDY
set functions:
Creating a set
Ex:
s=set()
print(s)
print(type(s))
Ex:
s={10,20,30,"sai",45.7,10}
print(s)
s.add(33)
print(s)
s.update([44,55,78,"durga"])
print(s)
Page 66 of 118
MOHAN S. REDDY
Ex:
s={10,20,30,40,50}
print(s) #s.discard(10)#s.remove(10)
s1=s.discard(100) #none
print(s1)
#s.remove(100) #KeyError: 100
s.clear()
print(s)
Deleting a set
Ex:
s={10,20,30,40,50}
print(s)
del s
print(s) #NameError: name 's' is not defined
Page 67 of 118
MOHAN S. REDDY
print(A|B) print(A.union(B))
print(A&B)
print(A.intersection(B))
print(A-B)
print(A.difference(B))
print(B-A)
print(A^B)
print(A.symmetric_difference(B))
Page 68 of 118
MOHAN S. REDDY
dictionary functions:
Creating a dict
Ex:
d={}
print(d)
print(type(d))
d={"eid":1234,"ename":"sai"}
print(d)
Page 69 of 118
MOHAN S. REDDY
print(d["ename"])
print(d.get("ename"))
#print(d["age"])#KeyError: 'age'
print(d.get("age")) #none
d["ename"]="mohan"
print(d)
d["age"]=37
print(d)
Page 70 of 118
MOHAN S. REDDY
Deleting a dict
Del key word is used to delete entire the dict.
Ex:
d={"eid":123,"ename":"sai"}
print(d)
del d["ename"]
print(d)
#del d
#print(d) #NameError: name 'd' is not defined
Dict copy
To copy the elements from one dict to another then we use copy
method.
Copy method is used to make a deep copy.
Ex:
d={1:"sai",2:"mohan",3:"raja"}
print(d)
#d1=d
d1=d.copy()
print(d1)
d[1]="durga"
print(d)
print(d1)
print(id(d1))
print(id(d))
Page 71 of 118
MOHAN S. REDDY
Ex:
d={1:"sai",2:"mohan",3:"raja"}
print(d)
print(d.items())
print(d.keys())
print(d.values())
Ex:
d={1:"sai",2:"mohan",3:"raja"}
print(1 in d)
print("sai" in d)
print(len(d))
Page 72 of 118
MOHAN S. REDDY
Page 73 of 118
MOHAN S. REDDY
Ex:
x=[10,20,30,40,255]
print(x)
print(type(x))
#b=bytes(x)
b=bytearray(x)
print(b)
print(type(b))
'''print(b[0])print(b[1])
print(b[2]) print(b[3])'''
b[1]=33
for i in b:
print(i)
Page 74 of 118
MOHAN S. REDDY
frozen set:
Set and frozen set is almost same but only the difference is ,set is
mutable Whereas frozen set is immutable.
We cannot change frozen set once create it.
Ex:
s={10,20,30,40}
print(s)
print(type(s))
s.add(34)
print(s)
fs=frozenset(s)
print(fs)
print(type(fs))
Page 75 of 118
MOHAN S. REDDY
Python Functions:
If a group of statements is repeatedly required then it is not
recommended to write these statements every time separately.
We have to define these statements as a single unit and we can call
that unit any number of times based on our requirement without
rewriting. This unit is nothing but function.
Function is a group of related statements that perform a specific task.
Functions help break our program into smaller and modular chunks.
As our program grows larger and larger, functions make it more
organized and manageable.
Furthermore, it avoids repetition and makes code reusable
The main advantage of functions is code Reusability.
Functions will provide improve readability of the program.
Built in Functions:
The functions which are coming along with Python software
automatically are called built in functions or pre-defined functions
Ex: print (), id (), type () etc.
Page 76 of 118
MOHAN S. REDDY
def function_name(parameters) :
""" doc string"""
Statements…
return value
Page 77 of 118
MOHAN S. REDDY
Creating a function
Ex:
#creating a function
def f1():
for i in range(10):
print("Hello")
#calling a function
f1()
Parameters:
Parameters are inputs to the function. If a function contains
parameters, then at the time of calling, compulsory we should provide
parameter values otherwise we will get error.
Create a function to find square of given number
Ex:
def square(n):
print("square is:",n*n)
Page 78 of 118
MOHAN S. REDDY
def iseven(n):
if n%2==0:
print(n,"is even")
else:
print(n,"is odd")
iseven(10)
iseven(n=int(input("Enter a number:")))
def biggest(a,b):
if a>b:
print(a,"is big")
else:
print(b,"is big")
biggest(23,45)
Page 79 of 118
MOHAN S. REDDY
def biggest(a,b,c):
if a>b and a>c:
print(a,"is big")
elif b>c:
print(b,"is big")
else:
print(c,"is big")
biggest(2,3,4)
biggest(4,3,2)
biggest(3,4,2)
biggest(4,2,3)
sum(10,20)
sum(23.4,56.7)
sum(a=int(input("Enter Num1:")),
b=int(input("Enter Num2:")))
Page 80 of 118
MOHAN S. REDDY
Return Statement:
r=add(10,20)
print("sum is:",r)
Ex:
def sum_sub(a,b):
sum=a+b
sub=a-b
return sum,sub
x,y=sum_sub(20,10)
print("sum is:",x)
print("sub is:",y)
Page 81 of 118
MOHAN S. REDDY
Page 82 of 118
MOHAN S. REDDY
Function Variables:
Python supports 2 types of variables
1. Local variables
2. Global variables
Local Variables:
The variables which are declared inside a function are called local
variables.
Local variables are available only for the function in which we
declared it, from outside of function we cannot access.
Ex:
def f1():
a=10
print(a)
#print(b)#NameError: name 'b' is notdefined
def f2():
b=20
print(b)
#print(a)#NameError: name 'a' is notdefined
f1()
f2()
Page 83 of 118
MOHAN S. REDDY
Global Variables:
The variables which are declared outside of function are called global
variables. These variables can be accessed in all functions of that
module or program.
Ex:
a=10 #global variable
def f1():
print(a)def f2():
print(a)
f1()
f2()
global keyword:
Ex:
a=10
def f1():
global a
a=99
print(a)
Page 84 of 118
MOHAN S. REDDY
def f2():
print(a)
f1()
f2()
def f1():
global a
a=99
print(a)
def f2():
print(a)
f1()
f2()
Note: If global variable and local variable is having the same name then
we can access global variable inside a function as follows.
Ex:
a=10
def f1():
a=20
print(a)
print(globals()['a'])
def f2():
print(a)
f1()
f2()
Page 85 of 118
MOHAN S. REDDY
Types of arguments:
def f1(a,b):
print(a+b)
f1(10,20)
1. positional arguments
2. keyword arguments
3. default arguments
4. Variable length arguments
Positional arguments:
Ex:
def sub(a,b):
print("sub is:",a-b)
sub(20,10)
sub(10,20)
sub(10,20,30) #TypeError: sub() takes 2positional
arguments but 3 were given
Page 86 of 118
MOHAN S. REDDY
Keyword arguments:
def f1(name,msg):
print("Hello:",name,msg)
#Keyword arguments
f1(name="mohan", msg="Good morning")
#Positional arguments
f1(msg="Good morning", name="mohan")
Page 87 of 118
MOHAN S. REDDY
Ex:
def f1(name,msg):
print("Hello:",name,msg)
#keyword arguments
f1(name="mohan",msg="Good morning")
f1(msg="Good morning",name="mohan")
#we can use one positional and one keyword arguments
#but make sure that positional arguments should be
first then after keyword arguments
f1("mohan",msg="Good morning")
#f1(name="mohan","Good morning") #SyntaxError:
positional argument follows keyword argument
Default arguments:
def f1(cource="python"):
print("course is:",cource)
f1("c")
f1()
If we are not passing any course then only default value will be
considered
After default arguments we should not take non default arguments
Page 88 of 118
MOHAN S. REDDY
Ex:
#def f1(cource="python",name): #SyntaxError: non-
default argument follows default argument
def f1(name,cource="python"):
print(name,"course is:",cource)
f1("sai","c")f1("mohan")
f1("ram")
Ex:
def f1(*a):
print(a)
f1()
f1(10) f1(10,20)
f1(10,20,30)
Page 89 of 118
MOHAN S. REDDY
Ex:
def add(*n):s = 0
for i in n:
s=s+i
print("sum is:",s)
Ex:
def add(*args):s = 0
for i in args:s=s+i
print("sum is:",s)
add(10,20) add(2,3,4)
add(2,3,4,5,6,7)
add(10,20,30,40,50,60,70)
Page 90 of 118
MOHAN S. REDDY
Ex:
def f1(**kwargs):
print(kwargs)
for k,v in kwargs.items():
print(k,"=",v)
f1(a=10,b=20,c=30)
f1(eid=1234,ename="sai",eaddress="hyd",esal=45000)
Ex:
def add(a,b,/):
print("sum is:",a+b)
add(10,20)
#add(a=10,b=20) #TypeError: add() got some
positional-only a
Page 91 of 118
MOHAN S. REDDY
Function Aliasing:
For the existing function we can give another name, which is nothing
but function aliasing.
If we delete a name of the function still we can call a function with
alias name.
Ex:
def f1():
print("Hello")
f2=f1
#del f1
f2()
print(id(f1))
print(id(f2))
Page 92 of 118
MOHAN S. REDDY
Nested Function:
def f1():
print("hello")
def f2():
print("Hai")
def f3():
print("welcome")
f3()
f2()
f1()
Ex:
def multi(a):
def mul(b):
def mu(c):
return a*b*c
return mu
return mul
y=multi(10)(20)(2)
print(y)
Page 93 of 118
MOHAN S. REDDY
Recursive Function:
Ex:
factorial(3)=3*factorial(2)=3*2*factorial(1)
=3*2*1*factorial(0)=3*2*1*1=6
def factorial(n):
if n==0:
result=1
else:
result=n*factorial(n-1)
return result
print("Factorial of 4 is:",factorial(4))
print("Factorial of 5 is:",factorial(5))
Page 94 of 118
MOHAN S. REDDY
s=lambda n:n*n
print(s(4))
s=lambda a,b:a+b
print(s(10,20))
Page 95 of 118
MOHAN S. REDDY
Page 96 of 118
MOHAN S. REDDY
Filter ():
This function is used to filter the values from given sequence based
on condition.
syntax: filter(function, sequence)
here first parameter function is for conditional check
here second parameter sequence can be a list or tuple or set
Ex:
#without lambda
def iseven(x):
if x%2==0:
return Trueelse:
return False
L=[2,3,4,5,6,7,8,9,10]
L1=list(filter(iseven,L))
print(L1)
#with lambda
L=[2,3,4,5,6,7,8,9,10]
L1=list(filter(lambda x:x%2==0,L))print(L1)
Page 97 of 118
MOHAN S. REDDY
Map ():
for every element present in sequence, apply some condition and
Return the new sequence of elements for this purpose we use map
function.
syntax: filter(function, sequence)
here first parameter function is for conditional check
here second parameter sequence can be a list or tuple or set
Ex:
#without lambda
def dbl(x):
return 2*x
L=[2,3,4,5,6,7,8,9,10]
L1=list(map(dbl,L))
print(L1)
#with lambda
L=[2,3,4,5,6,7,8,9,10]
L1=list(map(lambda x:2*x,L))
print(L1)
We can apply map () function on multiple lists also, but make sure all
list should have same length.
Ex:
L1=[2,3,4,5,7]
L2=[5,6,7,8,9]
L3=list(map(lambda x,y:x+y,L1,L2))
print(L3)
Page 98 of 118
MOHAN S. REDDY
Reduce ():
Reduce () function reduces sequence of elements into a single
element by applying the specified function.
syntax: filter(function, sequence)
Reduce () function present in functools module and hence we should
write import statement.
Ex:
#without lambda
from functools import reduce
def f1(x,y):
return x+y
L=[10,20,30,40,50,60,70]
result=reduce(f1,L)
print(result)
Ex:
#without lambda
from functools import reduce
L=[10,20,30,40,50,60,70]
result=reduce(lambda x,y:x+y,L)
print(result)
Page 99 of 118
MOHAN S. REDDY
Modules in Python:
A group of functions, variables and classes saved to a file, which is
nothing but module.
Every Python file (.py) acts as a module.
Module is for reusability of the program code into other program.
Once we write logic in one program that logic we can use into any
other program by importing the program name as module.
In python modules can be of two types
1. User defined modules
2. Predefined or built-in modules
Sample.py :
x=123
def add(a,b):
print("sum is:",a+b)
def mul(a,b):
print("Product is:",a*b)
Test.py:
import sample
print(sample.x)
sample.add(10,20)
sample.mul(30,20)
import sample as sm
print(sm.x)
sm.add(10,20)
sm.mul(30,20)
Test.py:
Ex:
x=123
def add(a,b):
print("sum is:",a+b)
def mul(a,b):
print("Product is:",a*b)
Sample1.py:
x=200
def sub(a,b):
print("mul is:",a*b)
Test.py:
Note: in the above program we notice that the value of x is 200 for
two times, the reason is recent module value only effect that is from
sample1, to avoid this try to change the program like below.
Test.py :
Sample.py :
def f1():
if name ==' main ':
print("Executed as an individual program")
else:
print("Executed from some other program")
f1()
Test.py :
import sample
sample.f1()
Test.py :
import sample
help(sample)
math module:
Ex:
from math import *
print(factorial(3))
print(sqrt(4))
print(pow(3,2))
print(log(10,2))
print(ceil(34.2))
print(floor(34.9))
random module:
Random () :
This function always generate some float value between 0 and 1 ( not
inclusive)
for i in range(5):
print(random())
Randint () :
This function always generate random integer values between two
given numbers ( inclusive)
for i in range(10):
#print(randint(2,21))
print(randint(1000,2000))
Uniform () :
This function always generate some float value between two given
numbers ( not inclusive)
for i in range(10):
print(uniform(2,21))
Randrange () :
This function always generates random range values.
Syntax: randrange(start,stop,step)
for i in range(10):
print(randrange(2,21,3))
Choice ():
This function will not generate random values but it return random
object.
l=["sai","mohan","raj","ram",10,34.5,"manoj"]
x=choice(l)
print(x)
print(type(x))
#in python everything is called as object
This module is used to work with date and time related tasks.
import datetime
x=datetime.datetime.now()
print(x)
import datetime as dt
x=dt.datetime.now()
print(x)
strftime () function :
This function is used to display date objects into string format
x=datetime.now()print(x)
Calendar module:
#y---year
#w---width of the characters#l---lines per week
#c---column separation
Arrays in Python:
Array:
Array is a user defined collection of similar data type elements.
Array index always starts with zero and ends with size – 1
In general arrays are two types
1. Single dimension array
2. Two dimension array
In python we can create single dimension array by using array
module.
Using array module we cannot create two dimension array.
To create single and two dimension arrays then we use numpy
module.
import array
# 0 1 2 3
A=array.array('i',[10,20,30,40])
print(A)
print(type(A))
A=array.array('f',[12.3,45.6,78.9,45.2])
print(A)
print(type(A))
Note: to create arrays in python using array module then we use type code
for i in range(len(A)):
print(A[i])
for i in range(n):
x=int(input("Enter value:"))
A.append(x)
print(A)
Numpy:
Numpy methods:
1. Array()
2. Linespace()
3. Logspace()
4. Arange()
5. Zeros()
6. Ones()
Ex1:
import numpy
#A=numpy.array([10,20,30,40,50])
A=numpy.array([10,20,30,40,50.8],int)
print(A)
print(type(A))
print(A.dtype)
print(A.ndim)
print(A.size)
print(A.shape)
Ex2:
A=arange(2,20,3)#start,stop,step
print(A)
A=zeros(6,int)
print(A)
A=ones(6,int)
print(A)
Page 116 of 118
MOHAN S. REDDY
Ex3:
import numpy as np
A=np.array([[10,20,30],[34,56,78],[78,23,45]])
print(A.dtype)
print(A.ndim)
print(A.shape)
print(A.size)
print(A[1][2])
Ex4:
import numpy as np
A=np.array([[-10,20,30],[34,-56,78],[78,23,-45]])
Note: in numpy arrays dimensions are called axis axis 0 means columns,
axis 1 means rows
flatten () method:
This method is used to collapse all rows from two dimension array into
a single row.
import numpy as np
A=np.array([[-10,20,30],[34,-56,78],[78,23,-45]])
print(A)
print(A.ndim)
B= A.flatten()
print(B)
print(B.ndim)
THANK YOU