Python Programming Language Features
Python Programming Language Features
Features Of Python
2. Easy to Learn: Python program is clearly defined and easily readable. The
structure of the program is simple. It uses few keywords and clearly defined
syntax.
4. Free and Open Source: It is a Open Source Software. So, anyone can freely
distribute it, read the source code, edit it, and even use the code to write new
(free) programs.
1
5. High-level Language: While writing programs in Python we do not worry
about the low-level details like managing memory used by the program.
simple
Easy to
Inter-preter
learn
Features
of
object
oriented
Python High level
programming language
portable Dynamic
7. Portable: It is a portable language and hence the programs behave the same
on wide variety of hardware platforms with different operating systems.
2
9. Interpreted: Python is processed at runtime by interpreter. So, there is no
need to compile a program before executing it. You can simply run the
program. Basically python converts source program into intermediate form
called byte code.
[Link]: Since Python is an open source software, anyone can add low-
level modules to the python interpreter. These modules enable programmers
to add to or customize their tools to work more efficiently.
13. Extensive Libraries: Python has huge set of libraries that is easily portable
across different .
3
Tokens
Data
Literals Identifiers keyWords Operators
Types
❖ Literals:
In programming constants are referred to variables that cannot be Changed.
Note:
For c precision part is 6 decimals.
For java and python precesion part is 15 decimals.
• String literal:
4
Examples of string literals include:
1. 'Hello, World!'
2. "This is a string"
3. 'a' (a single character string)
4. '123' (a string, not a number)
❖ Identifiers:
Identifiers are names given to identify something. This something can be a variable,
function, class, module or other object. For naming any identifier, there are some
basic rules.
Rules of Identifiers:-
[Link] first character of an identifier must be an underscore ('_') or a letter (upper or
lowercase).
[Link] rest of the identifier name can be underscores ('_'), letters (upper or lowercase),
or digits (0- 9).
[Link] names are case-sensitive.
For example, myvar and myVar are not the same.
[Link] characters such as @, $, and % are not allowed within identifiers.
Examples of valid identifier names are sum, __my_var, num1, r, var_20, First,
etc…
Examples of invalid identifier names are 1num, my-var, %check, Basic Sal,
H#R&A, etc…
5
❖ Data types:
The variables can hold values of different type called Data type.
They are classifies into two type:
[Link] data type:An immutable data type is a type of data that cannot be
changed or modified once it is created. In other words, its state is immutable, meaning
it cannot be altered after it is initialize.
→ In python int,float,bool,String,tuple are the Immutable data type.
→ In immutable data types, when you change the value of a variable, both the
value and the memory location change.
[Link] datatype: Mutable data type means that the value of the data can be
changed (mutated) after it is created.
→ In python list,dict,set are called mutable data type.
→ In mutable data type when we change the value of variable only the value chages
but location not changes.
❖ Keywords:
Python Keywords
True , False, None , 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, with, while, yield.
6
[Link] : Write a program to print all keywords in python.
Code:
import keyword
print([Link])
❖ Operators:
1. Arithmetic Operators
2. Relational Operator
3. Bitwise Operator
4. Shift Operator
5. Logical Operator
6. Membership Operator
7. Identity Operator
8. Assignment Operator
9. Comma Operator
[Link] Operator:
7
Example: Write a program to perform all arithmetic Operations.
Code:
a=10
b=5
print(“add:”,a+b)
print(“sub:”.a-b)
print(“mul:”a*b)
print(“div:”a//b)
print(“mod:”a%b)
Print(“power:”a**2)
output:
add:15
sub:5
mul:50
div:2
mod:0
power:100
[Link] operator:
8
For Example assuming a=100 and b=2000
we can use the comparison operators on them as specified in the following
[Link] operator:
As the name suggests, bitwise operators perform operations at the bit level.
These operators include bitwise AND, bitwise OR, bitwise XOR, and shift operators.
Bitwise operators expect their operands to be of integers and treat them as a sequence
of bits.
• If a number can be expressed in powers of 2 the binary number is 1 followed by
x [Link] zeroes.
eg: Let x=9 then 2**9=512 in bits 1000000000
• If a number is expressed 2**x-1 the binary value is x [Link] ones.
eg: Let x=9 then 2**x-1 in bits 0111111111
→ If n&n-1= = 0 the n can be expressed in powers of 2 otherwise n can’t be
expressed in powes of 2
[Link] Operators:
Python supports two bitwise shift operators. They are shift left (<<) and shift right (>>).
These operations are used to shift bits to the left or to the right.
Left shift(<<): In left shift we move the bit values by one place towards left
9
We neglect MSB and add 0 to LSB
eg: Let a=12 i.e 00001100 a<<i =a*(2**i)
If i=1 then a<<1=12*(2**1)=24
⸫ a=00001100 then a<<1 is 00011000 i.e 24
Right shift(>>): In right shift we move bit value by one towards rightside
We neglect LSB and add 0 to MSB.
eg: Let a=12 i.e 00001100 a>>i=a//(a**i)
If i=1 then a>>1=12//(2**1)=6
⸫ a=00001100 then a>>1 is 00000110 i.e 6
[Link] operators:
Logical operators are used to simultaneously evaluate two conditions or expressions
with relational operators.
→ Logical And(and): If the first condition false it does not evaluate the second
condition it directly gives false when the both conditions are true it gives true.
→ Logical OR(or): If one or both conditions are true it gives true.
in: This operator gives true if the searching element is found in the given sequence or
iterable otherwise it gives false.
not in: This operator gives true if the searching element is not found in given sequence
or iterable otherwise it gives true.
is:This operator gives true if both the variable shares the same memory location
otherwise it gives false
In immutable if the values are same then location also same
eg:
a=5
b=5
print(a is b)
10
Output:
True
not is:This operator gives true if both variables not sharing same memory location
otherwise it gives false
[Link] Operator:
Assignment operators are used in Python to assign values to variables.
Expression is evaluated and result is stored in LHS i.e variable
Additional/Shortcut assign:
+= , - = ,*=,/=,//=,**=
Multiple assignment :
Var1,var2,var3...varn=val1,val2,val3...valn
[Link] operator(,):
Variable separator and value separator
Character Set
11
Example:
print(ord(“a”))
print(chr($))
Output:
97
36
Indentation
Whitespace at the beginning of the line is called indentation. These white spaces or the
indentation are very important in Python.
In a Python program, the leading whitespace including spaces and tabs at the beginning
of the logical line determines the indentation level of that logical line.
Once we keep ‘:’ at the end of selection or loop statement then the body of selection or
loop statement will have tab space as identation.
Comments
These are non executable statements in python it is also used to understand the program
in easier manner.
# - It is the single line comment.
‘‘‘ ’’’ - It is the multi line comment.
Statements
12
[Link] Statements:
if-else: If the condition is true statement1 is evaluated otherwise else part statement2 is
evaluated.
Syntax:
if condition:
statement1
else:
statement2
Example:
Code:
n=int(input())
s=(int(n**0.5))
If p*p==n :
print(‘Yes’)
else:
print(‘No’)
Output:
9
Yes
Code:
c=input()
p=ord(c)
if p>=65 and p<=90:
13
print(‘Yes’)
else:
print(‘No’)
Output:
A
Yes
Code:
c=input()
p=ord(c)
if p>=97 and p<=122:
print(‘Yes’)
else:
print(‘No’)
Output:
Z
Yes
String modules
1. ascii_lowercase
2. ascii_uppercase
3. ascii_letters
4. digits
5. octdigits
6. hexdigits
14
Examples:
Code:
import string
c=input()
if c in string.ascii_letters:
print(‘Yes’)
else:
print(‘No’)
Output:
a
Yes
Synatx:
if condition1:
statement1
elif condition2:
statement2
else:
statement3
15
Examples:
[Link] a program to read a number and check whether it is single digit or double
digit or 3 digits or 4 digit or greater than 4.
Code:
n=int(input())
if n<10:
print(1)
elif n<100 :
print(2)
elif n<1000:
print(3)
elif n<10000
print(4)
else
print(‘>4’)
Output:
1)5
1
2)2000
4
Code:
import string
c=input()
v=’aeiouAEIOU’
16
l=string.ascii_lowercase
u=string.ascii_uppercase
if c in l and c in v:
print(‘Lower case vowel’)
elif c in l and c not in v:
print(‘Lower case consonent’)
elif c in u and c in v:
print(‘Upper case vowel’)
elif c in u and c not in v:
print(‘Upper case consonent’)
elif c in [Link]:
print(‘Digits’)
else:
print(‘Symbol’)
Output:
1)a
Lower case vowel
2)$
Symnbol
[Link] a program to read 3 numbers and arrange in descending order (With out
using built in function)
Code:
a,b,c=map(int,input().split())
if a>b and a>c:
if b>c:
print(a,b,c)
else:
print(a,c,b)
elif b>c:
if a>c:
print(b,a,c)
else:
17
print(b,c,a)
else:
if a>b:
print(c,a,b)
else:
print(c,b,a)
output:
1)5 4 10
4 5 10
2)10 8 3
3 8 10
LOOP STATEMENTS
for loop:
syntax:
for var in range(start,stop,step):
statement1
else:
18
statement2
range() deals only with numbers
start means initialization(starting value)
stop means condition (last value)
step means incr/decr
➢ start and step are optional.
if start is not given, its default value is 0.
if step is not given its default value is 1.
→ stop is mandatory and it always executes till its previous value.
if start <stop then stop works till stop-1.
if start>stop then stop works till stop+1
Examples
Code:
n=int(input())
for i in range(1,n+1):
if n%i==0:
print(i,end=' ')
n=int(input())
for i in range(1,int(n**0.5)+1):#1
if n%i==0:#2
print(i,end=' ')
if i*i!=n:#3
print(n//i,end=' ')
Output:
100
1 100 2 50 4 25 5 20 10
19
2. Write a program to display the count of even factors of a given number.
Code:
n=120
c=0
for i in range(1,int(n**0.5)+1):
if n%i==0:
if i%2==0:
c+=1
if (n//i)%2==0 and i*i!=n:
c+=1
print(c)
Output:
12
Code:
n=int(input())
for i in the range(2,int(n**0.5)+1):
if n%i==0:
print(‘No’)
break
else:
print(‘Yes’)
Output:
17
Yes
20
[Link] a program to check given number is perfect number or not.
Code:
n=int(input())
s=0
for i in the range (1,int(n**0.5)+1)
if n%i==0:
s+=i
if i!=1:
s+=n//i
if s==n:
print(‘Yes’)
else:
print(‘no’)
Output:
6
Yes
Code:
n=int(input())
c=0
while n!=0;
c+=n%10
n//=10
print(c)
Output:
6545234
29
21
[Link] a program to read and check whether it is strong number or not.
Code:
import math
n=int(input())
c=0
m=n
while n>o:
r=n%10
c+=[Link](r)
n//=10
print(‘yes’ if c==m else ‘No’)
Output:
145
Yes
7. 654321 Code:
6+5+4+3+2+1+ n=int(input())
5+4+3+2+1+ c=0
4+3+2+1+ d=0
3+2+1+ m=n
2+1+ while m>9:
1 d+=1
m//=10
while n>0:
m=n
while m>0:
r=m%10
c+=r
m//=10
n%=100**d
d-=1
print(c)
22
[Link] a program to check whether the given number is palindrome or not.
Code:
n=int(input())
c=0
m=n;
while n>0:
r=m%10
c=c*10+r
n//=10
print(‘Yes’ if c==m else ‘No’)
Code:
n=int(input())
r=m=n
p=0
c=0
while r>0:
p=p+r
r//=10
while n>0:
r=n%10
c=c+r**p
n//=10
print(‘Yes’ if c==m else ‘No’)
23
9.
4 Code:
#### n=int(input())
# # for i in range (1,n+1):
# # for j in range(1,n+1):
#### if i==1 or i==n or j==1 or j==n:
print(‘#’,end=’ ‘)
else:
print(‘ ’,end=’ ‘)
print()
10.
6 Code:
****** n=int(input())
** ** for i in range(1,n+1):
* ** * for j in range(1,n+1):
* ** * if i=-1 or i==n or j==1 or j==n or i==j or i+j=n+1:
** ** print(‘*’,end=’ ‘)
****** else:
print(‘ ’,end=’ ‘)
print()
24
STRINGS
String represents a group of character's. These are very important because most of
the data that we use in daily life in the form of string
➢ Operations:
[Link](+):Merging of two string
It is homogeneous that means string only concatinate
[Link]([ : : :]):
syntax:
strvar[start:stop:step]
start,stop and step are all optional.
→ if step is not given, its default value is 1.
→ If start, stop are not given, their default value depends on the value of step.
→ If step is empty(1) or +ve, start default value is 0. stop default value is
len(str)[number of characters] and stop works till stop-1.
→ If step is negative, start default value is -1 and stop default value is -
(len(str)+1) and stop works till stop+1.
where to use slicing:
If we wanted to extract a substring or subsequence we have to go for slicing.
Substitute string.
25
Example:
committment 3
output1: mittmentcom
output2: entcommittm
Code:
s=’commitment’
k=3
print(s[k: ]+s[ :k])
print(s[-k: ]+s[ :-k])
String Functions
len() count() find() index() rfind()
rindex() center() ljust() rjust() zfill()
lstrip() rstrip() strip() split() rsplit()
splitness() format() replace() upper() lower()
casefold() title() capitalize() swapcase() isalpha()
isalnum() isspace() isidentifier() isprintable() isascii()
isupper() islower() istitle() isdigit() isdecimal()
isnumeric() startswith() endswith() max() min()
expandtabs() join() chr() ord() str()
Functions:
count() :It gives the frequency of the specified pattern(either single character or a
string) in the given string.
[Link](pattern)
26
find(): it gives the first occurrence of the specified pattern in the given string.
[Link](pattern)
[Link](pattern,startIndex)
[Link](pattern,startIndex,stopIndex)
iffind() is unsuccessful, it gives -1.
It works from left to right.
index(): it gives the first occurrence of the specified pattern in the given string.
It works from left to right.
ifindex()is unsuccessful, it raises an exception called ValueError.
rfind():it gives the last occurrence of the specified pattern in the given string.
[Link](pattern)
[Link](pattern,startIndex)
[Link](pattern,startIndex,stopIndex)
it works from right to left.
if rfind() is unsuccessful, it gives -1.
center(): it aligns the string as center aligned in a larger width, the remaining width
is filled by default with spaces or a given single fillchar.
[Link](width)
[Link](width,fillchar)
ljust(): it aligns the string as left justified in a larger width, the remaining width is
filled by default with spaces or a given single fillchar.
rjust(): it aligns the string in right justified in a larger width, the remaining width is
filled by default with spaces or a given single fillchar.
27
➢ HOW MANY TYPES OF SPACES IN PROGRAMMING LANGUAGE:
istrip(): it removes the leading(before the start of the string) spaces or any specified
character in the given string
[Link]() : it removes all spaces
[Link](char): it removes all chars
rstrip(): it removes the trailing(after the end of the given string) spaces or any
specified character in the given string.
[Link]() : it removes all spaces
[Link](char): it removes all chars
strip(): it removes both leading and trailing spaces or specific characters from the
given string.
split(): it divides the given string into multiple strings(list of strings) based on the
specified delimiter(by default it is space)
rsplit(): it divides the given string into multiple strings(list of strings) based on the
specified delimiter(by default it is space)
split() Vs rsplit(): when we customize the splittings, then split() works from left to
right and rsplit() works from right to left.
upper():it converts the entire string to uppercase(it does not consider digits or
symbols)
28
lower():it converts all the uppercase letters to lowercase.
Code:
a=5.6
b=7.0
c=’hello’
s=’{ } { } { }’.format(a,b,c)
t=’%d %f %s’%(a,b,c)
r=f’{a} {b} {c}’
print(s)
print(t)
print(r)\
replace(): it replaces by default all the occurrences of the specified pattern with the
new pattern in the given string.
[Link](old,new)
isalpha(): it gives True, if the string contains only alphabet(A_Z a_z), if the string
contains one non alphabet it gives False.
29
isalnum(): it gives True, if the string contains only either alphabet or digits, if the
string contains atleast one symbol it gives False.
isspace(): it gives True, if the string contains only spaces(all types of spaces), if the
string contains atleast one non space character, it gives False.
isidentifer(): it gives True, if the string contains a valid identifier(based on the rules)
otherwise it gives False.
isprintable(): it gives True, if the string contains only printable characters, otherwise
it gives False.
isascii(): it gives True, if the string contains characters with valid ASCII values(0-
127) otherwise it gives False.
isupper(): it gives True, if the string contains only uppercase letters, if the string
contains atleast one lowercase letter it gives False.
islower(): it gives True, if the string contains only lowercase letters, if the string
contains atleast one uppercase letter, it gives False.
istitle(): it gives True, if the string is in titlecase(every words starting letter is only
uppercase), otherwise it gives False.
isdigit():it gives True, if the string contains digits or unicode digits(Ex: '\u00B2'),
otherwise it gives False.
isdecimal():it gives True, if the string contains digits otherwise it gives False.
isnumeric():it gives True, if the string contains digits or unicode digits or other
linguistic digits, otherwise it gives False.
startswith():it gives True, if the string is started with the specified pattern, otherwise
it gives False.
30
endswith():it gives True, if the string ends with the specified pattern, otherwise it
gives False.
Example:
s='this is a test'
print([Link]('thi'))
print([Link]('tst'))
output:
True
False
Examples:
Code:
s=input()
print(‘Yes’ if s==s[::-1] else ‘No’)
Output:
4567654
Yes
31
2. Write a program to count the number of characters in the string without
using builtin functions.
Code:
s=input()
c=0
for i in s:
c+=1
print(c)
Output:
Abhi
4
Code:
s=input()
dup=’‘
for i in s:
if i not in dup:
dup+=i
print(dup)
Output:
yddyuewie
yduewi
32
LISTS
Method1:
p=[]
n=int(input())
for i in range(n):
[Link](int(input()))
print(p)
Output:
4
5
1
2
3
[5,1,2,3]
Method2(list comprehension):
n=int(input())
p=[int(input()) for i in range(n)]
print(p)
Output:
3
1
5
8
[1,5,8]
33
Type-2: the array elements are in a single line separated by a space.
Code:
n=int(input())
p=list(map(int,input().split()))[:n]
print(p)
Output:
3
123456
[1,2,3]
method2(list comprehension)
n=int(input())
p=[int(x) for x in input().split()][:n]
print(*p)
Output:
5
12345
12345
➢ Operations:
1. concatenation(+)
2. repetition(*)
3. indexing([])
4. slicing([::])
List Functions
len() count() index() clear()
copy() append() insert() pop()
remove() sort() sorted() min()
max() sum() reverse() extend()
34
Functions:
[Link](): it gives the first occurrence of the specified element in the given list. if
the element is not found, it raises an exception called ValueError.
5. copy(): it copies only values from one list to another list(it does not share location).
Example:
p=[1,2,3]
q=[Link]()
print(p,q)
Output:
[1,2,3] [1,2,3]
8. pop(): it removes an element specified by the index, by default it removes the last
element,
if the index specified is not available, it raises an exception called IndexError.
[Link](): it removes the specified element from the list. if the element is not
available, it raises an exception called ValueError.
TIM SORT(insertion +merge)
35
[Link](): the elements are sorted in ascending order.
[Link]()
[Link](): it gives the element with maximum value. to apply max() elements must
be of same type.
[Link](): it gives sum(total) of the elements of the list. to apply sum() elements
must be of number type.
Example:
p=[1,2,3]
[Link](84)
print(p)
[Link](64387438,666)
print(p)
[Link]([23,56])
print(p)
Output:
[1,2,3,84]
[1,2,3,84,666]
[1,2,3,84,666,23,56]
36
TUPLES
Example:
Code:
t= (1,2,3)
a=(1,’String’,[1,2,3])
print(t)
print(a)
Output:
(1,2,3)
(1,’String’,[1,2,3])
• Operations:
1. concatenation
2. repetition
3. indexing
4. slicing
Tuple Functions
len() Count() Index() Max()
Min() Sum() Sorted()
➢ Tuples are utilized by functions in python when they return multiple values.
37
DICTIONARY
➢ It is a mutable data type where each element has a pair of objects called Key
and Value separated by a ':'.
➢ where Keys are unique(no duplicates) and immutable(we cannot use list or
dict or set as keys).
➢ values may be immutable or mutable.
➢ Dictionaries does not have any order, because order is decided by hashing
technique, that is the reason dictionary in Python is unordered Dictionary.
➢ How to create a dictionary.
d={}
d=dict()
➢ Operations:
1. indexing: indexing can be done that too key is the index of the dictionary.
Dictionary Functions
len() max() min() sum()
clear() copy() sorted() updated()
setdefault() pop() popitem() keys()
values() items() fromkeys() get()
Functions:
38
6. copy():to insert elements into dictionary we have three ways.
if the key is already available in the dictionary, then setdefault() does nothing.
if the key is not avaialable, then key,value pair will be inserted.
dictvar[key]=value
39
[Link](): the value of the particular key will be retrieved.
[Link](key): if the key is not available, it returns None
[Link](key,value) : if the key is not available, it returns the default value
specified.
Example:
[Link] a program to create a dictionary where keys are 'a' to 'z' and values
are 1 to 26.
Code:
d={}
import string
p=string.ascii_lowercase
d=[Link](p,0)
for i in range(1,27):
d[p[i-1]]=i
print(d)
Output:
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9, 'j': 10, 'k': 11, 'l': 12, 'm': 13,
'n': 14, 'o': 15, 'p': 16, 'q': 17, 'r': 18, 's': 19, 't': 20, 'u': 21, 'v': 22, 'w': 23, 'x': 24, 'y':
25, 'z': 26}
2. Given a string display the count of every letter of the string using dictionary.
Code:
s=input()
d={}
for i in s:
d[i]=[Link](i,0)+1
40
for i,j in [Link]():
print(i,’occurs’,j,’times’)
Output:
hello world
h occurs 1 times
e occurs 1 times
l occurs 3 times
o occurs 2 times
w occurs 1 times
r occurs 1 times
d occurs 1 times
Code:
s=input().lower()
import string
d={}
d=[Link](string.ascii_lowercase,0)
for i in s:
d[i]=[Link](i,0)+1
p=list([Link]())
print(‘Pangram’ if 0 not in p else ‘Not Pangram’)
Output:
41
SETS
• Set is a mutable data type where it does not allow duplicates. set is mutable,
but set elements are immutable.
• set in Python is unordered, because order is decided by hash function.
we need to use set when we need to remove duplicates but there is no issue
with the order.
p=set()
• Operations:
1. union
2. intersection
Sets Functions
Len() Max() Min() Sum()
Copy() Clear() Sorted() Update()
Add() Pop() Remove() Discard()
Functions:
42
[Link](): we can insert one or more elements into set at a time(if duplicates are
given it will ignore)
[Link]({ele1,ele2,...elen})
[Link](): it removes a specific element from the set. if the element is not
avaiable, it raises KeyError.
[Link](element)
[Link](): it is same as remove() but if the element is not available, it does not
raise any exceptions.
Example:
1.
p=set(‘artificial’)
print(p)
[Link]({‘n’, ‘o’, ‘l’, ‘e’})
[Link](‘h’)
print(p)
[Link](‘t’)
print(p)
Output:
{'a', 'r', 't', 'i', 'f', 'c', 'l'}
{'a', 'r', 't', 'i', 'f', 'c', 'l', 'n', 'o', 'e', 'h'}
{'a', 'r', 'i', 'f', 'c', 'l', 'n', 'o', 'e', 'h'}
43
2.
s={2,3,4,5,6}
t={1,7,6,5,9}
r={34,45,76,87}
print(s|t)
print([Link](t))
print(s&t)
print([Link](t))
print(s-t)
print([Link](t)
print((s-t)|(t-s))
print(s^t)
print(s.symmetric_diffrence(t))
print([Link](t))
print([Link](s))
print([Link](r))
Output:
{1, 2, 3, 4, 5, 6, 7, 9} (union)
{1, 2, 3, 4, 5, 6, 7, 9} (union)
{5, 6} (intersection)
{5, 6} (intersection)
{2, 3, 4} (difference)
{1, 7, 9} (difference)
{1, 2, 3, 4, 7, 9} (symmetric difference)
{1, 2, 3, 4, 7, 9} (symmetric difference)
False (issuperset)
False (issubset)
True (isdisjoint)
44
FUNCTIONS
• Function is set of statements which has self defined task, which is executed
upon access or call or request.
• Functions are two types:
[Link]-in functions(pre-defined functions)
factorial(), gcd(), sqrt(), print()
[Link]-defined functions:
NOTE:
The function definition must be placed above the function call and in the same
indentation.
specific features of functions in Python:
1. A function can be assigned to a variable.
2. A function can return multiple values at a time
3. Nested functions are possible.
4. A function can return another function(it avoids the problem in nested functions)
5. Afunction can be used as an argument to another function.
45
The communication between actual and formal arguments is called as parameter
passing mechanism.
Based on actual and formal arguments our functions are categorised into
[Link] arguments
[Link] arguments
[Link] arguments
[Link] length arguments
[Link] length keyword arguments
Anonymous functions
NOTE: lambda functions are used to implement one liner logics only.
46
Example for lambda Functions:
1.
p=[i for i in range(1,21)]
p=list(map(lambda x:x**3,p))
print(p)
Output:
1 8 27 81
2.
Output:
0,2,4,6,8
3.
Output:
720
47
RECURSIVE FUNCTIONS:
When a function calls itself, it is known as Recusion.
We need to go for recursive function when we can divide a problem into sub
problems.
Problems:
Code:
def add(n):
if n==1:
return 1
return n+add(n-1)
n=int(input())
print(add(n))
Output:
n=5
15
Code:
def add(n):
if n<=1:
return n*add(n-1)
n=int(input())
print(add (n))
output:
n=5
120
48
[Link] a program to compute LCM of two numbers using recursion.
Code:
Output:
a,b= 12,15
60.
Code:
Output:
a,b= 2,3
8
49
[Link] a program to delete duplicate characters of a string using recursion.
Code:
def remove(s):
global op
if len(s) == 0:
return op
if s[0] not in op:
op += s[0]
return remove(s[1:])
s = input(“Enter a string: “)
op = ‘’
print(remove(s))
Output:
S=apple
apl
Code:
def remove(s):
if len(s) < 2:
return s
if s[0] == s[1]:
return remove(s[1:])
return s[0] + remove(s[1:])
s = input(“Enter a string: “)
print(remove(s))
50
Output:
aabbccdd
abcd
Code:
def fib(n):
p = [0] * (n + 1)
p[1] = 1
return p[n]
Output:
n=5
5
51
OOPS IN PYTHON
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
1)Class:
Class is a blue print from which objects are created. Class contains data members to
store information and member functions to operate upon data members.
Syntax for class in python: class classname(super class name):
2)Object:
Object is an instances of a class. It is basically a real world implementation of the
class having all those property values which are define or structured in the class.
Syntax for object creation: object name = classname(parameters)
52
3)Encapuslation:
Acquiring properties from one class to another class, the class which gives
Inheritance is called super class or base class or parent class.
The class which gets inheritance is called sub class or derived or child class.
Types of Inheritance:
[Link] or simple Inheritance
[Link] inheritance
[Link] Inheritance
[Link] level Inheritance
[Link] or Multipath Inheritance
[Link] or simple Inheritance: One base class and one derived class .
[Link] inheritance: One derived class and two or more base classes.
[Link] Inheritance: One base class and two or more derived classes.
[Link] level Inheritance: One base class(A), one derived class(B) which in turn
serves as a base class for one more derived(C) class.
[Link] or Multipath Inheritance: Combination of two or more inheritance.
Self: Self is a memory variable, which stores the reference of the current calling
object.
Self is used to:
1)To access the class variable or members of the class inside the class.
2)To differentiate class variable and local variable if names are same.
53
eg:
Code
class A:
A = 78
B = 89
p = A()
[Link](24, 7)
Output:
78 89 24 7
2)Instance variable: The variables created or defined inside the constructor of the
class.
6)Methods:
1)Instance method.
2)Class method.
3)Static method.
54
Instance method:
class A:
a = 78
b = 89
def disp(self):
self.a += 22
self.b += 12
p = A()
print(p.a, p.b)
[Link]()
print(p.a, p.b)
q = A()
print(q.a, q.b)
Class method:
class A:
a = 78
b = 89
@classmethod
def disp(cls):
cls.a += 22
cls.b += 12
p = A()
print(p.a, p.b)
[Link]()
print(p.a, p.b)
q = A()
print(q.a, q.b)
55
Static method:
Code:
class A:
a = 78
b = 89
@staticmethod
def disp():
A.a += 32
A.b += 12
p = A()
print(p.a, p.b)
[Link]()
print(p.a, p.b)
q = A()
print(q.a, q.b)
static method is same as class method it does not have any default positional
argument called self class method and static method can be called using object of
the class or class name also but not instance methods.
56
7)Constructor:
Constructor is a special method which is executed when we create object for the
class.
• The rule in java or c++ is constructor name is same as the classname and there
is no return type for constructor.
• In python __init__() is the constructor.
1)Default constructor: The constructor without any arguments other than self.
NOTE:
i)In python, we cannot define multiple methods with same name (either constructors
also or functions also).
ii)We cannot define multiple constructors in the same class (only one constructor
will be executed).
57
INHERITANCE
[Link] Inheritance: One super class gives inheritance to one sub class.
Code:
class A:
def sound(self):
print("Sound")
class B(A):
def speed(self):
print("Speed")
b = B()
[Link]()
[Link]()
Output:
Sound
Speed
Uses of super():
Super() also differentiates super class variable and class variable if names are same.
Like object is superclass of all classes In java,object in the super class of all classes
in python.
58
[Link] Inheritance: One derived class and two or more base classes.
Code:
class A:
def sound(self):
print("Sound")
class B:
def speed(self):
print("Speed")
c = C()
[Link]()
[Link]()
[Link]()
Output:
Sound
Speed
Feature
59
[Link] Inheritance: One base class and two or more derived classes.
Code:
class A:
def sound(self):
print("Sound")
class B(A):
def speed(self):
print("Speed")
class C(A):
def feature(self):
print("Feature")
b = B()
c = C()
[Link]()
[Link]()
[Link]()
[Link]()
Output:
Sound
Speed
Sound
Feature
60
[Link]-level Inheritance: One base class(A), one derived class(B) which in turn
serves as a base class for one more derived(C) class.
Code:
class A:
def sound(self):
print("Sound")
class B(A):
def speed(self):
print("Speed")
class C(B):
def feature(self):
print("Feature")
c = C()
[Link]()
[Link]()
[Link]()
Output:
Sound
Speed
Feature
61
Hybrid Inheritance: Combination of two or more inheritance.
Code:
class A:
def sound(self):
print("Sound")
class B(A):
def speed(self):
print("Speed")
class C(A):
def feature(self):
print("Feature")
Output:
Sound
Speed
Feature
Extra
62
Method Overriding:
When a super class method’s name is same as the method name in sub class,
irrespective of the parameters subclass method will always override superclass
method.
Operator Overloading:
Allows you to define custom behavior for operators when they are used with user-
defined objects. This means you can extend the meaning of operators beyond their
predefined operational meaning. For example, the + operator can be used to add two
integers, concatenate two strings, or merge two lists.
Operator Overloading
Pre-defined method for
Operator
Overloading
+ __add__()
- __sub__()
* __mul__()
/ __truediv__()
// __floordiv__()
% __mod__()
** __pow__()
< __lt()__()
> __gt__()
<= __le__()
>= __ge__()
== __eq__()
63
!= __ne__()
& __and__()
| __or__()
^ __xor__()
<< __lshift__()
>> __rshift__()
~ __invert__()
+= __iadd()
-= __isub__()
*= __imul__()
/= __idiv__()
//= __ifloordiv__()
%= __imod__()
**= __imod__()
&= __iand__()
|= __ior__()
^= __ixor__()
_ __neg__()
64
Abstract class
An abstract class can be considered as a blueprint for other classes. It allows goes
to create a set of methods that must be created within any child classes built from
the abstract class. A class which contains one or more abstract methods is called an
abstract class, an abstract method is a method that has a declaration but does not
have an implementation while we are designing large functional units we use an
abstract class.
By defining an abstract base class, you can define a common application program
interface for a set of subclasses.
Code:
class A(ABC):
@abstract method
def disp(self):
print(‘hi’)
@abstract method
def show(self):
print(‘hello’)
class B(A):
def disp(self):
print(‘in subclass’)
def show(self):
print(‘ in show’)
P=B()
[Link]()
[Link]()
Output:
In subclass
In show
65
Patterns programs in Python
1) Write a python program to print the given pattern.
*****
*****
*****
*****
*****
Code:
for x in range(1,6):
for y in range(1,6):
print(“*”, ends=””)
print()
Code:
for x in range(1,6):
for y in range(1,6):
print(x,ends=””)
print()
66
3) Write a python program to print the given pattern.
12345
12345
12345
12345
12345
Code:
for x in range(1,6):
for y in range(1,6):
print(y, ends=””)
print()
Code:
for x in range(1,6):
for y in range(65,70):
print(chr(y),ends=””)
print()
67
5) Write a python program to print the given pattern.
AAAAA
BBBBB
CCCCC
DDDDD
EEEEE
Code:
for x in range(65,70):
for y in range(1,6);
print(chr(x),ends=””)
print()
Code:
for x in range(5,0,-1):
for y in range(5,0,-1):
Print(x,ends=””)
Print()
68
7) Write a python program to print the given pattern.
EEEEE
DDDD
CCCC
BBBBB
AAAAA
Code:
for x in range(69,64,-1):
for y in range(1,6):
Print(chr(x),ends=””)
Print()
Code:
for x in range(5,0,-1):
for y in range(5,0,-1):
Print(x,ends=””)
Print()
69
70