Core Python
Core Python
REDDY
CORE PYTHON
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.
2. Expressive Language
1
MOHAN S.REDDY
3. Interpreted Language
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.
6. Object-Oriented Language
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.
Python has a large and broad library and provides rich set of module and
functions for rapid application development.
10. Integrated
It can be easily integrated with languages like C, C++, and Java etc.
2
MOHAN S.REDDY
Versions of PYTHON:
3
MOHAN S.REDDY
History of PYTHON:
ABC language.
Modula-3
Web Applications
Desktop GUI Applications
Network Programming
Gaming Applications
Data Analysis Applications
Console Based Applications
Business Applications
Audio and Video Based Applications
4
MOHAN S.REDDY
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
5
MOHAN S.REDDY
Python Indentation:
6
MOHAN S.REDDY
A code block (body of a function, loop etc.) starts with indentation and ends
with the first un- indented line. The amount of indentation is up to you, but
it must be consistent throughout that block.
Generally four whitespaces are used for indentation and is preferred over
tabs. Here is an example.
a=10
if a==10:
print("true")
The indentation in Python makes the code look neat and clean.
Indentation can be ignored in line continuation.
But it makes the code more readable.
Python Comments:
Comments are very important while writing a program.
7
MOHAN S.REDDY
Digits(0 to 9)
Underscore symbol(_)
Multiple Assignments:
Python allows us to assign a value to multiple variables in a single
statement which is also known as multiple assignment
Ex1:
a=b=c=10
print(a)
print(b)
print(c)
8
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)
Python Keywords:
Python Keywords are special reserved words which convey a special
meaning to the interpreter.
import keyword
print(keyword.kwlist)
9
MOHAN S.REDDY
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']
1. None
2. Numeric
3. List
4. Tuple
5. Set
6. String
7. Range
8. Dictionary or Mapping
9. Bytes
10.Bytearray
11.Frozenset
10
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))
1. Int
2. Float
3. Complex
4. Bool
Examples:
a=10
print(a)
print(type(a))
a=10.9
print(a)
print(type(a))
11
MOHAN S.REDDY
a=10
print(a)
print(type(a))
b=float(a)
print(b)
print(type(b))
a=10.8
print(a)
print(type(a))
b=int(a)
print(b)
print(type(b))
a=input("Enter Num1:")
b=input("Enter Num2:")
print("result is:",a+b)
Note: by default the values entered by user at runtime will be treated as string
a=input("Enter Num1:")
print(type(a))
b=input("Enter Num2:")
print(type(b))
print("result is:",a+b)
12
MOHAN S.REDDY
a=input("Enter Num1:")
print(type(a))
x=int(a)
b=input("Enter Num2:")
print(type(b))
y=int(b)
print("result is:",x+y)
Complex Data Type: A complex number is in the form of real and imaginary
Ex: a+bj
10+20j
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.
Bool:
13
MOHAN S.REDDY
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:
Ex:
s="durgasoft"
print(s)
print(type(s))
s='durga\'s'
print(s)
s='''durgasoft
hyderabad
14
MOHAN S.REDDY
maitrivanam'''
print(s)
s="""durgasoft
hyderabad
maitrivanam"""
print(s)
List:
Ex:
l= [10,10,"durga",23.4,20,'A']
print(l)
print(type(l))
Tuple:
Ex1:
t=(10,10,"durga",23.4,20,'A')
print(t)
15
MOHAN S.REDDY
print(type(t))
Ex2:
t=(10,)
print(t)
print(type(t))
Set:
Ex1:
s=set()
print(s)
print(type(s))
Ex2:
s={10,"sai",12.4,'A',10}
print(s)
print(type(s))
Dict:
16
MOHAN S.REDDY
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))
Range:
Ex:
r=range(10)
print(r)
print(type(r))
r=range(list(10))
print(r)
r=range(list(2,20,2))
print(r)
17
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
1. Arithmetic
2. Relational
3. Assignment
4. Logical
5. Membership
6. Identity
7. Bitwise
Arithmetic Operators:
Operator Description
+ It perform Addition
- It Perform subtraction
* It Perform Multiplication
/ It Perform Division
Ex:
18
MOHAN S.REDDY
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
== Equal to
!= Not Equal to
Ex:
print(3<4)
print(4>5)
print(4<=4)
print(5>=5)
print(3==3)
print(3!=3)
19
MOHAN S.REDDY
Assignment Operators:
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//=2
print(a)
20
MOHAN S.REDDY
a=5
print(a)
a**=2
print(a)
a%=2
print(a)
Logical Operators:
Operator Description
Ex:
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))
21
MOHAN S.REDDY
Membership Operators:
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)
Identity Operators:
These operators are used to check whether the variables or objects are
having same identity or different identity.
Operator Description
22
MOHAN S.REDDY
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)
Id ( ):
Ex:
a=2
b=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'
23
MOHAN S.REDDY
print(id(a))
print(id(b))
print(id(a)==id(b))
Bitwise Operators:
2. Bitwise OR (|)
24
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)
25
MOHAN S.REDDY
Conditional statements:
If
If else
Nested if
elif
if :
Syntax: if condition:
Statements
If condition is true then statements will be executed.
Ex:
i=100
if i==100:
print("true")
if else:
Syntax: if condition:
Statements
else:
Statements
If condition is false then statements of else block will be executed.
Else will execute only if the condition is false.
Ex:
26
MOHAN S.REDDY
i=100
if i==100:
print("true")
else:
print("false")
i=int(input("Enter a number:"))
if i%2==0:
print(i,"is even")
else:
print(i,"is odd")
i=int(input("Enter num1:"))
j=int(input("Enter num2:"))
if i>j:
print(i,"is big")
else:
print(j,"is big")
n=int(input("Enter number:"))
if n>=1 and n<=100:
print("The number",n,"is in between 1 to
100")
else:
print("The number", n, "is not in between 1
to 100")
nested if:
27
MOHAN S.REDDY
Syntax: 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)
elif:
Syntax: if condition1:
Statements
elif condition2:
Statements
elif condition3:
Statements
else:
Statements
28
MOHAN S.REDDY
i=int(input("Enter num1:"))
j=int(input("Enter num2:"))
k=int(input("Enter num3:"))
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:
29
MOHAN S.REDDY
if n==4:
print("FOUR")
else:
print("Invalid number")
Iterative statements:
For loop:
For loop is used to iterate the elements of collection or sequence what the
order they appear.
l=[10,20,30,40,50,60]
for i in l:
#print(i)
print(i,end=' ')
Ex:
for i in [10,"sai",23.4,50,'A']:
print(i,type(i))
Ex:
for i in range(10):
print(i)
30
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)
A for loop which is having one more for loop within it is called nested for
loop.
A for loop inside another for loop is called nested for loop.
Note: For every iteration of outer loop, inner loop should finish its all iterations
then only the outer loop starts with its next iteration.
Ex:
numlsit=[1,2,3]
charlist=['a','b']
for n in numlsit:
print(n)
31
MOHAN S.REDDY
for c in charlist:
print(c)
While loop:
Ex:
i=1
while i<=10:
print(i)
i+=1
Ex: program to display sum of first n numbers
n=int(input("Enter number:"))
sum=0
i=1
while i<=n:
sum=sum+i
i+=1
print("Sum of first",n,"numbers is:",sum)
i=0
while True:
i+=1
print("Hello",i)
Transfer statements:
32
MOHAN S.REDDY
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:
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:
33
MOHAN S.REDDY
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
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
Ex:
34
MOHAN S.REDDY
print(dir(str))
Ex:
help(str)
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 of
range
s="hyderbad"
print(s[2:7])
print(s[:6])
print(s[1:])
print(s[:])
print(s[0:9:1])
print(s[::-1])
35
MOHAN S.REDDY
Ex:
s1="durga"
s2="soft"
36
MOHAN S.REDDY
print(s1+s2)
print(s1+" "+s2)
print("mohan"+" "+"kumar")
print(s1*3)
print((s1+" ")*3)
print(("mohan"+" ")*3)
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))
for i in s1:
print(i)
Ex:
s="pyThon is vEry eaSy"
37
MOHAN S.REDDY
print(s)
s1=s.capitalize()
print(s1)
#or
print(s.capitalize())
print(s.title())
Ex:
s="durgasoft"
print(s)
38
MOHAN S.REDDY
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:
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
39
MOHAN S.REDDY
Ex:
print(",".join("MOHAN"))
print(" ".join(["sai","mohan","raj","durga"]))
String reverse
Using reversed method of join, we can reverse the string.
40
MOHAN S.REDDY
Ex:
print(" ".join(reversed("SAI")))
#or
s="SAI"
print(s[::-1])
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())
41
MOHAN S.REDDY
Ex:
s=" durga "
print(s)
print(s.strip(" "))
s="adurga"
print(s)
print(s.strip('a'))
42
MOHAN S.REDDY
print(s.lstrip('a'))
print(s.rstrip('a'))
String length
Ex:
print(len("durga soft"))
If substring found then it will return the index of the substring else it will
return -1.
If substring found then it will return the index of the substring else it will give
value error.
Ex:
s="python is very easy and it is oop and it is
interpreter"
print(s.find("is"))
print(s.find("x"))
print(s.index("is"))
#print(s.index("x"))
print(s.rindex("is"))
Ex: print(ord(‘A’))
Ex:
s="durgasoft"
print(max(s))
print(min(s))
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")
44
MOHAN S.REDDY
print(s1)
print(type(s1))
Ex:
s="durgasoft"
print(s.startswith('a'))
print(s.startswith('D'))
print(s.startswith('d'))
print(s.endswith('T'))
print(s.endswith('t')
Ex:
s="12345"
print(s.isdigit())
s="12345a"
print(s.isdigit())
s="abcd"
print(s.isalpha())
s='abcd12'
print(s.isalpha())
45
MOHAN S.REDDY
s="abcd"
print(s.isalnum())
s="1234"
print(s.isalnum())
s="123abc"
print(s.isalnum())
s="$%#%"
print(s.isalnum())
46
MOHAN S.REDDY
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])
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]
47
MOHAN S.REDDY
print(l[1:5])
print(l[:4])
print(l[1:])
print(l[:])
Ex:
l=[2,3,4]
print(l)
l[1]=33# 1 is index and 33 is value
48
MOHAN S.REDDY
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)
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)
Ex:
l1=["sai","durga","ram"]
l2=[10,20,30]
print(l1+l2)
print(l1*3)
50
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))
Ex:
l=[10,20,30,10,20,10,10,20,10,20]
print(l.count(10))
print(l.count(100))
print(l.index(30))
Ex:
52
MOHAN S.REDDY
l=[]
'''l.append(item1)
l.append(item2)
l.append(item3)'''
l.extend([item1,item2,item3])
print(l)
Ex:
l=[]
for i in range(n):
x=int(input("Enter a value:"))
l.append(x)
print(l)
Ex:
print(list(range(10)))
print(list(range(2,20)))
print(list(range(2,21,3)))#start,stop,step
53
MOHAN S.REDDY
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)
Ex:
print(10 in t)
print(100 in t)
print(100 not in t)
Ex:
t=(10,20,-34,23.4,50)
print(len(t))
print(max(t))
print(min(t))
print(sum(t))
print(sum(t,4))
54
MOHAN S.REDDY
Ex:
s="durgasoft"
print(s)
print(type(s))
t=tuple(s)
55
MOHAN S.REDDY
print(t)
print(type(t))
Ex:
l=[10,20,30,40]
print(l)
print(type(l))
t=tuple(l)
print(t)
print(type(t))
Ex:
#packing
a=10
b=20
c=30
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)
56
MOHAN S.REDDY
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)
Ex:
s={10,20,30,40,50}
print(s)
57
MOHAN S.REDDY
#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
58
MOHAN S.REDDY
Ex:
s={10,20,30,40,50}
print(s)
del s
print(s) #NameError: name 's' is not defined
Ex:
A={1,2,3,4,5}
B={4,5,6,7,8}
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))
Ex:
s={10,34.5,-45,89,99}
print(len(s))
print(max(s))
print(min(s))
print(sum(s))
print(sum(s,9))
60
MOHAN S.REDDY
Ex:
s={10,34.5,-45,89,99}
print(10 in s)
print(9 in s)
print(99 not in s)
Creating a dict
Ex:
d={}
print(d)
print(type(d))
d={"eid":1234,"ename":"sai"}
print(d)
We can also pass key by using get function; if the key is not present then it
will return none.
Ex:
d={"eid":1234,"ename":"sai"}
print(d)
print(d["ename"])
61
MOHAN S.REDDY
print(d.get("ename"))
#print(d["age"])#KeyError: 'age'
print(d.get("age")) #none
Ex:
62
MOHAN S.REDDY
d={"eid":123,"ename":"sai"}
print(d)
d["ename"]="mohan"
print(d)
d["age"]=37
print(d)
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"
63
MOHAN S.REDDY
print(d)
print(d1)
64
MOHAN S.REDDY
print(id(d1))
print(id(d))
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))
Ex:
d={1:"sai",2:"mohan",3:"durga"}
print(d)
65
MOHAN S.REDDY
#print(d.pop(1))
#print(d)
print(d.popitem())
print(d)
66
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)
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:
67
MOHAN S.REDDY
s={10,20,30,40}
print(s)
print(type(s))
s.add(34)
print(s)
fs=frozenset(s)
print(fs)
print(type(fs))
Python Functions:
Built in Functions
User Defined Functions
1. Built in Functions:
68
MOHAN S.REDDY
The functions which are coming along with Python software automatically
are called built in functions or pre-defined functions
Ex: print (), id (), type () etc.
Syntax :
def function_name(parameters) :
Statements…
return value
Creating a function
Ex:
69
MOHAN S.REDDY
#creating a function
def f1():
for i in range(10):
print("Hello")
#calling a function
f1()
f1()
Parameters:
Ex:
def square(n):
print("square is:",n*n)
Ex:
def iseven(n):
if n%2==0:
print(n,"is even")
else:
print(n,"is odd")
70
MOHAN S.REDDY
iseven(10)
iseven(n=int(input("Enter a number:")))
Ex:
def biggest(a,b):
if a>b:
print(a,"is big")
else:
print(b,"is big")
biggest(23,45)
Ex:
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)
71
MOHAN S.REDDY
Ex:
def sum(a,b):
print("sum is:",a+b)
sum(10,20)
sum(23.4,56.7)
sum(a=int(input("Enter
Num1:")),b=int(input("Enter Num2:")))
Return Statement:
Create a function to find sum of two numbers and return the result
Ex:
def add(a,b):
#print("sum is:",a+b)
return a+b
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)
72
MOHAN S.REDDY
print("sum is:",x)
print("sub is:",y)
Ex:
73
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 not
defined
def f2():
b=20
print(b)
#print(a)#NameError: name 'a' is not
defined
f1()
f2()
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:
def f1():
print(a)
74
MOHAN S.REDDY
def f2():
print(a)
f1()
f2()
global keyword:
Ex:
a=10
def f1():
global a
a=99
print(a)
def f2():
print(a)
f1()
f2()
Ex:
def f1():
global a
a=99
print(a)
def f2():
print(a)
75
MOHAN S.REDDY
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()
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
76
MOHAN S.REDDY
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 2
positional arguments but 3 were given
Keyword arguments:
def f1(name,msg):
print("Hello:",name,msg)
#keyword arguments
f1(name="mohan",msg="Good morning")
f1(msg="Good morning",name="mohan")
#positional arguments
f1("mohan","Good morning")
f1("Good morning","mohan")
77
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:
Ex:
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
78
MOHAN S.REDDY
Ex:
f1("sai","c")
f1("mohan")
f1("ram")
Ex:
def f1(*a):
print(a)
f1()
f1(10)
f1(10,20)
f1(10,20,30)
Ex:
def add(*n):
s = 0
for i in n:
s=s+i
79
MOHAN S.REDDY
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)
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)
Ex:
def f1(**kwargs):
print(kwargs)
for k,v in kwargs.items():
80
MOHAN S.REDDY
print(k,"=",v)
f1(a=10,b=20,c=30)
f1(eid=1234,ename="sai",eaddress="hyd",esal=450
00)
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
Ex:
def add(*,a,b):
print("sum is:",a+b)
81
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))
Nested Function:
def f1():
print("hello")
def f2():
print("Hai")
def f3():
print("welcome")
f3()
f2()
82
MOHAN S.REDDY
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)
Recursive Function:
factorial(3) =3*factorial(2)
=3*2*factorial(1)
=3*2*1*factorial(0)
=3*2*1*1
=6
Ex:
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))
83
MOHAN S.REDDY
s=lambda n:n*n
print(s(4))
s=lambda a,b:a+b
print(s(10,20))
84
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 True
else:
return False
L=[2,3,4,5,6,7,8,9,10]
L1=list(filter(iseven,L))
print(L1)
Ex:
#with lambda
L=[2,3,4,5,6,7,8,9,10]
85
MOHAN S.REDDY
L1=list(filter(lambda x:x%2==0,L))
print(L1)
Map ():
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)
Ex:
#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)
86
MOHAN S.REDDY
Reduce ():
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)
Modules in Python:
87
MOHAN S.REDDY
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)
88
MOHAN S.REDDY
import sample as sm
print(sm.x)
sm.add(10,20)
sm.mul(30,20)
Test.py:
Test.py:
89
MOHAN S.REDDY
Test.py:
Sample.py :
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:
print(x)
sub(7,3)
90
MOHAN S.REDDY
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 :
print(x)
add(2,3)
mul(3,6)
Sample.py :
def f1():
if name ==' main ':
print("Executed as an individual
program")
else:
print("Executed from some other
91
MOHAN S.REDDY
program")
f1()
Test.py :
import sample
sample.f1()
Test.py :
import sample
help(sample)
This module defines several functions which can be used for mathematical
operations.
Ex:
print(factorial(3))
print(sqrt(4))
print(pow(3,2))
print(log(10,2))
print(ceil(34.2))
print(floor(34.9))
92
MOHAN S.REDDY
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)
93
MOHAN S.REDDY
for i in range(10):
print(uniform(2,21))
Randrange () :
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.
94
MOHAN S.REDDY
import datetime
x=datetime.datetime.now()
print(x)
import datetime
x=datetime.datetime.now()
print(x)
import datetime as dt
x=dt.datetime.now()
print(x)
strftime () function :
x=datetime.now()
print(x)
print(x.strftime('%A')) #weekday full version
print(x.strftime('%a')) #weekday short version
print(x.strftime('%Y')) #year full version
print(x.strftime('%y')) #year short version
95
MOHAN S.REDDY
y=1947
m=8
print(month(y,m))
print(month(2021,11))
#y---year
#w---width of the characters
#l---lines per week
#c---column separation
print(leapdays(1980,2021))
print(isleap(2020))
print(isleap(2022))
Arrays in Python:
Array:
96
MOHAN S.REDDY
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
97
MOHAN S.REDDY
print(A.typecode)
print(A[2])
A.insert(1,34)
print(A)
A.append(45)
print(A)
A.extend([67,89,90])
print(A)
A.remove(30)
print(A)
A.reverse()
print(A)
A=array('i',[100,200,300,400,500,600])
for i in A:
print(i)
for i in range(len(A)):
print(A[i])
A=array('i',[2,3,4,5,6])
print(A)
#B=A
#print(B)
B=array(A.typecode,[i*2 for i in A])
print(B)
98
MOHAN S.REDDY
A=array('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=linspace(2,20,7)#start,stop,no of parts
print(A)
A=logspace(3,15,6)
print(A)
A=arange(2,20,3)#start,stop,step
print(A)
A=zeros(6,int)
print(A)
A=ones(6,int)
print(A)
Ex3:
import numpy as np
A=np.array([[10,20,30],
10
0
MOHAN S.REDDY
[34,56,78],
[78,23,45]])
print(A)
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]])
print("max element is:",A.max())
print("min element is:",A.min())
flatten () method:
This method is used to collapse all rows from two dimension array into a
single row.
import numpy as np
10
1
MOHAN S.REDDY
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
10
2