Professional Documents
Culture Documents
Python Class Notes Merged
Python Class Notes Merged
What is Language?
Types of Languages
1. Machine Language
2. Assembly Language
The problem with low level languages are non portable (hardware
dependent).
All High level languages are english like, easy to understand. High
level languages are portable or hardware independent.
EG: C,C++,Java,Pythonl,C#.net,….
What is translator?
Types of translator
1. Interpreter
2. Compiler
What is translator?
Types of translator
1. Interpreter
2. Compiler
Interpreter
1. Fetch/Reading
2. Syntax Verification
3. Translating
4. Executing
If there is an error in one line rest of the lines are not interpreted and
executed. It terminates the execution of program.
Compiler
Interpreter Compiler
C ➔ Programming Language
C++ ➔ Programming Language
Java ➔ Programming Language
Python ➔ Programming Language
Scripting Language
Q: What is program?
1. Data
2. Instructions
Q: What is programming?
What is python?
PASCAL(Scientific Applications)
R (Statistics)
Python Features
What is library?
Python Versions
Stable Version(LTS)
Un-Stable Version
Python Language
Python implementations
Python Distributions
▪ eGenix PyRun (a portable Python runtime, complete with stdlib, frozen into a single 3.5MB -
13MB executable file)
Python IDE’s
Q: What is IDE?
1. Pydroid 3
2. Sololearn
3. Python for android
4. Qpython
1. Interactive Mode
2. Scripting Mode/Programming Mode
Interactive Mode
In interactive mode your work with python shell. Python shell is a tool
or a program which receive the commands given at prompt and
interpret and give the result.
>>>
>>> help(“os”)
>>>help(“while”)
>>>help(“print”)
>>> print("hello")
hello
Scripting Mode
In scripting mode we write a python program and save with ext .py.
This scripting mode also called programming mode.
print("Hello World")
print("Welcome to python")
print("This is my first program in python")
1. ASCII
2. UNICODE
>>> name="naresh"
>>> name
'naresh'
>>> x=100
>>> x
100
>>> name="नरे श"
>>> name
'नरे श'
>>>
>>> name="నరేశ్"
>>> name
'నరేశ్'
>>>
Tokens
1. Keywords
2. Identifiers
3. Literals/Constants
4. Data types
5. Operators
Keywords
['False', 'None', 'True', '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']
>>> len(keyword.kwlist)
35
Identifiers
Rules
1. Identifier should not be a keyword
Example:
>>> from=100
SyntaxError: invalid syntax
>>> x=100
>>> y=200
>>> base=1.5
>>> break=1
SyntaxError: invalid syntax
2. Identifier should not start with digit.
>>> no1=100
>>> no2=200
>>> 3no=300
SyntaxError: invalid syntax
3. There should not be any space in identifier
>>> account number=101
SyntaxError: invalid syntax
>>> student rollno=1
SyntaxError: invalid syntax
>>> account_number=101
>>> student_rollno=102
4. It allows only one special character _, This _ should be a prefix
or in between or suffix
>>> _no1=100
>>> no1_=200
>>> no_1=300
>>> _no1
100
>>> no1_
200
>>> no_1
300
>>> _=400
>>> _
400
>>> __=500
>>> _no_=600
>>> __
500
>>> _no_
600
5. There is no restriction of length of identifier. Preferred length is 8
or 16.
>>>
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaa=100
>>>
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
bbbbbbbbbbbbbbb=200
>>>
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaa
100
>>>
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
bbbbbbbbbbbbbbb
200
6. Identifier can be in uppercase or lowercase. Python case
sensitive language it finds the difference between uppercase
and lowercase.
>>> A=100
>>> a=200
>>> A
100
>>> a
200
>>> ROLLNO=1
>>> rollno=2
>>> ROLLNO
1
>>> rollno
2
Data types
int
Q: What is variable?
A variable is named memory location.
A variable is identifier which is used to identity value/object.
In python memory is allocated or reserved by creating variables.
In python variables are created by assigning value.
In python memory is reserved by assigning value to variable.
In python variables are reference type, which does not hold value it
hold address.
This variables are dynamic in type.
Ex:
>>> n1=100
>>> n1
100
>>> n2=200
>>> n2
200
>>> type(n1)
<class 'int'>
>>> type(n2)
<class 'int'>
type() function
Id() function
>>> n1=100
>>> n1
100
>>> n2=200
>>> n2
200
>>> type(n1)
<class 'int'>
>>> type(n2)
<class 'int'>
>>> id(n1)
1494265312
>>> id(n2)
1494266912
int is an immutable data type. A data type which does not allows to
modify value after creating object.
An object whose state/value cannot be changed is called
immutable object or class.
>>> num1=999999999999999999999999999999999999999999999999
>>> num1
999999999999999999999999999999999999999999999999
>>>
num2=999999999999999999999999999999999999999999999999999999
999999999999999999999999
>>> num2
999999999999999999999999999999999999999999999999999999999999
999999999999999999
>>>
float
x.py
x=1.5
y=1.5
print(id(x))
print(id(y))
>>> n1=200
>>> n2=200
>>> id(n1)
527528321680
>>> id(n2)
527528321680
>>> n3=257
>>> n4=257
>>> id(n3)
527572892784
>>> id(n4)
527572892720
>>> x=256
>>> y=256
>>> id(x)
730607020432
>>> id(y)
730607020432
>>>
complex
>>> comp1=1+2j
>>> comp2=1+4j
>>> comp1
(1+2j)
>>> comp2
(1+4j)
>>> type(comp1)
<class 'complex'>
>>> type(comp2)
<class 'complex'>
>>> comp1.real (. Is called member access operator)
1.0
>>> comp1.imag
2.0
>>> comp2.real
1.0
>>> comp2.imag
4.0
>>>
>>> c1=1+2j+3k
SyntaxError: invalid syntax
>>> c1=1+2i
SyntaxError: invalid syntax
>>>
>>> comp1.real=2.0
Traceback (most recent call last):
File "<pyshell#42>", line 1, in <module>
comp1.real=2.0
AttributeError: readonly attribute
>>> c1=2j
>>> c1.real
0.0
>>> c1.imag
2.0
>>> c2=1+2j+3j
>>> c2
(1+5j)
>>>
Python Shell
>>> c3=1+2j
>>> c4=1+2j
>>> id(c3)
730654438448
>>> id(c4)
730654438736
>>>
Pogramming Mode/Scripting Mode
c1=1+2j
c2=1+2j
print(id(c1))
print(id(c2))
Output:
4342971440
4342971440
Note: int, float, complex all these data types sizes are unlimited
length.
bool
>>> id(b2)
140714985945224
>>> z=True
>>> id(z)
140714985945192
>>>
str
Name1=”naresh”
Name2=’naresh’
Name3=’’’naresh’’’
Name4=”””naresh”””
>>> name1="naresh"
>>> name2='naresh'
>>> name3='''naresh'''
>>> name4="""naresh"""
>>> type(name1)
<class 'str'>
>>> type(name2)
<class 'str'>
>>> type(name3)
<class 'str'>
>>> type(name4)
<class 'str'>
>>> name1
'naresh'
>>> name2
'naresh'
>>> name3
'naresh'
>>> name4
'naresh'
>>>
1. Within single quotes ‘ ‘
2. Within double quotes “ “
3. Within triple quotes ‘’’ ‘’’ or “”” “””
Within single quotes we can embed double quotes.
With in double quotes we can embed single quotes
Within three single quotes we can embed double quotes
Within three double quotes we can embed single quotes
Three single and double quotes are used to represent multiline string.
>>> s1='pythoon is a
SyntaxError: EOL while scanning string literal
>>> s2="python is a
SyntaxError: EOL while scanning string literal
>>> s3='''python is a
programming langauge'''
>>> s3="""python is a programming
Language"""
>>>
Escape Sequences
\’ Single quotes
\” Double quotes
\\ \ character
\n new line
\t tab space
\v vertical table space
print(10,20,30,40,50) ➔ 10 20 30 40 50\n
print(10) ➔ 10\n
print() ➔ \n
Only for reference or internal logic of print or custom print function
import sys
def display(*value,sep=' ',end='\n',file=sys.stdout,flush=False):
str1=''
if len(value)==0:
file.write(end)
if len(value)==1:
str1=str1+str(value[0])+end
file.write(str1)
if len(value)>1:
value1=[str(v) for v in value]
str1=sep.join(value1)
str1=str1+end
file.write(str1)
display()
display(10)
display(10,20,30,40,50)
display(100,200,300,400,500,600,700,800)
# printing values inside userdefined file
f=open("d:\\output","w")
print("Hello Python",file=f,flush=True)
print("Hello Java")
print("Hello ML",file=f,flush=True)
print("Hello DS")
# Find outputs
print(10,20,30,40,50,sep=',')
print(10,20,30,40,50)
print(10,20,30,40,50,sep='\n')
n1=100
n2=200
n3=300
print(n1,n2,n3,sep='\n')
print(100,200,300,end=",",sep="\n")
print("Hello")
# find outputs
#Find output
print(10,end=',')
print(20,end=',')
print(30)
Find output
print(100,200,300,end=",",sep="\n")
print("Hello")
input()
input(prompt=None, /)
Read a string from standard input(keyboard).
>>> x=input()
100
>>> x
'100'
>>> type(x)
<class 'str'>
>>> x=input("Sohel please enter value")
Sohel please enter value100
>>> x
'100'
>>> x=input("enter x value:")
enter x value:100
>>> user=input("UserName :")
UserName :nit
Output:
Enter n1 value10
Enter n2 value20
10 20
<class 'str'> <class 'str'>
>>> x="10"
>>> y="25"
>>> x+y
'1025'
>>> n1=10
>>> n2=20
>>> n1+n2
30
>>>
>>> a=65
>>> type(a)
<class 'int'>
>>> a
65
>>> b=0o45
>>> type(b)
<class 'int'>
>>> b
37
>>> oct(b)
'0o45'
>>> c=0xa
>>> type(c)
<class 'int'>
>>> c
10
>>> hex(c)
'0xa'
>>> d=0b101
>>> type(d)
<class 'int'>
>>> d
5
>>> bin(d)
'0b101'
>>>
Syntax1:
Int([x])
X is value is not defined, the default value of x is 0
X value can be integer(decimal,octal,hexa,binary), float
Syntax2:
Int(str,base=10)
String required integer value with base of 10. If string not
having integer with base 10, we need to define the base value of
integer represented within string.
Without type we can create integer with integer value.
Eg: n1=65
n2=0o45
n3=0xab
n4=0b1010
With type we can create integer with different types of values.
Eg:
n1=int(1.5) # creating integer with float value
n2=int(“65”) # creating integer with string value contain
integer with base 10
n3=int(“0o45”) # error
n4=int(“0o45”,base=8)
n5=int(“0xab”) # error
n6=int(“0xab”,base=16)
n7=int(“0b101”) # error
n8=int(“0b101”,base=2)
>>> x=int("1.5")
Traceback (most recent call last):
File "<pyshell#15>", line 1, in <module>
x=int("1.5")
ValueError: invalid literal for int() with base 10: '1.5'
>>> y=int(1.5)
>>> y
1
>>>
float() type
Example
f1=float(1.5) # constructing float using float value
f2=float(25) # constructing float using int value
print(f1,f2)
Example
f1=float("1.5") # converting string to float(standard format)
f2=float("1.5e1") # converting string to float(expo format)
print(f1,f2)
# write a program to add two float numbers
n1=float(input("Enter first float number"))
n2=float(input("Enter second float number"))
n3=n1+n2
print(n3)
# write a program to find area of triangle
base=float(input("enter base"))
height=float(input("enter height"))
area=0.5*base*height
print("area is ",area)
complex() type
This type is used to construct complex number. It allows to create
complex number using different types of values.
1. Using real and imag of type float or integer
2. Using string
c1="1"
comp4=complex(c1) # create complex number using real value of
type string
print(comp4)
c2="2j"
comp5=complex(c2) # create complex number using imag value of
type string
print(comp5)
c3="1+3j"
comp6=complex(c3) # create complex number using both real and
imag
print(comp6)
bool() datatype
This data type is used to construct Boolean objects. It allows to
create Boolean object using integers.
>>> b1=bool(1)
>>> b2=bool(0)
>>> b1
True
>>> b2
False
>>> b3=bool(100)
>>> b3
True
>>> b4=bool(45)
>>> b4
True
>>> b5=bool(0)
>>> b5
False
>>> b6=bool(True)
>>> b7=bool(False)
>>> b6
True
>>> b7
False
>>> b8=bool("True")
>>> b8
True
>>> b9=bool("False")
>>> b9
True
>>> b10=bool("a")
>>> b10
True
>>>
str() type
This type is used to construct string object using other types (OR)
converting other types to string.
Example
x=10
y=20
z=x+y
print(x,y,z)
s1=str(x) # converting integer to string
s2=str(y) # converting integer to string
s3=s1+s2
print(s1,s2,s3)
f1=1.5
f2=2.5
f3=f1+f2
print(f1,f2,f3,sep='\n')
s4=str(f1) # converting float to string
s5=str(f2) # converting float to string
s6=s4+s5
print(s4,s5,s6)
c1=1+2j
c2=2+3j
c3=c1+c2
print(c1,c2,c3)
s7=str(c1) # converting complex number to string
s8=str(c2) # converting complex number to string
s9=s7+s8
print(s7,s8,s9)
Operators
10+20=30
1+2+3+4+5
3+3+4+5
6+4+5
10+5 =15
Types of Operators
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Bitwise Operators
6. Identity Operators
7. Membership Operators
8. Conditional Operators
Arithmetic Operators
These operators are used to perform arithmetic operations. These are
binary operators.
Operator Meaning
+ Addition, Concatenation
- Subtraction
* Multiplication, Repeating
sequence number of times
/ Float Division
// Floor division or integer division
% Modular Operator
** Expo
+ operator is used to perform two operations.
1. Adding numbers
2. Concatenating string
If two operands are numbers it performs addition.
If two operands are strings it perform concatenation
Example:
a1=10
a2=20
a3=a1+a2
print(a1,a2,a3)
s1="Python"
s2="Language"
s3=s1+s2
print(s1,s2,s3)
Example
s1="Python"
f1=3.9
s2=s1+f1
print(s1,f1,s2)
Output:
Traceback (most recent call last):
File "C:/Users/admin/Desktop/py11am/py27.py", line 3, in <module>
s2=s1+f1
TypeError: can only concatenate str (not "float") to str
Example
s1="Python"
f1=3.9
s2=s1+str(f1)
print(s1,f1,s2)
Output:
Python 3.9 Python 3.9
Example
res1=100+200
res2=1.5+2.5
res3=1+2j+1+3j
res4="python"+"language"
res5=True+True
res6=False+False
print(res1,res2,res3,res4,res5,res6,sep='\n')
10+2.5 ➔ 12.5
10+20 ➔ 30
1.5+2.5 ➔ 4.0
1+2+3.5+1.2 ➔ 7.7
1+2j+1 ➔ 2+2j
3.0/2.0 ➔ 1.5
3.0//2.0 ➔ 1 ➔ 1.0
res1=3/2
res2=3//2
print(res1,res2,sep='\n')
res3=3.0/2.0
res4=3.0//2.0
print(res3,res4,sep="\n")
res1=10%2
res2=9%2
print(res1)
print(res2)
res1=10**2
res2=1.5**3
print(res1)
print(res2)
Operator precedence
Operator Description
:= Assignment expression
lambda Lambda expression
if – else Conditional expression
Operator Description
or Boolean OR
and Boolean AND
not x Boolean NOT
in, not in, is, is not, <, <=, >, Comparisons, including membership
>=, !=, == tests and identity tests
| Bitwise OR
^ Bitwise XOR
& Bitwise AND
<<, >> Shifts
+, - Addition and subtraction
Multiplication, matrix multiplication,
*, @, /, //, %
division, floor division, remainder
+x, -x, ~x Positive, negative, bitwise NOT
** Exponentiation
await x Await expression
x[index], x[index:index], Subscription, slicing, call, attribute
x(arguments...), x.attribute reference
(expressions...),
Binding or parenthesized expression, list
[expressions...], {key: display, dictionary display, set display
value...}, {expressions...}
Relational Operators
These operators are used to find relation between two
values/objects. Relational operators are used to compare objects.
Operator Meaning
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
== Equality operator
!= Not Equal
All relational operator return Boolean value(True/False).
An expression which is having relational operators is called Boolean
expression.
10+20-5 ➔ Arithmetic Expression
10>20 ➔ Boolean Expression
In python relational operators are used on standard data
type(int,float,complex,bool) and sequence datatypes(list,set,str,..)
Example
b1=100>50
b2=50<100
b3=100>200
b4=100<50
b5=100>=200
b6=100<=200
print(b1,b2,b3,b4,b5,b6)
b7="A">"B" # ==> 65>66
b8="B">"A" # ==> 66>65
b9="A"<"B" # ==> 65<66
print(b7,b8,b9)
b10=1.5<1.7
b11=1.7>1.5
print(b10,b11)
Example
b1=100==100
b2="nit"=="nit"
b3=True==True
b4=True!=True
print(b1,b2,b3,b4)
Logical Operator
Logical operators are used to combine more than one Boolean
expression (OR) these operators are used to combine two conditions
or test.
Logical operators are represented using keywords.
Operator Meaning
and Logical and operator
or Logical or operator
not Logical not operator
Truth table of and operator
Operand1 Operand2 Operand1 and
operand2
True True True
True False False
False True False
False False False
Truth table of or operator
Operand1 Operand2 Operand1 or
Operand2
True True True
True False True
False True True
False False False
Truth table of not operator
Operand1 not operand1
True False
False True
Precedence of Logical Operators least to highest.
or Boolean OR
and Boolean AND
not x Boolean NOT
Example
x=100 and 200
print(x)
y=100 and 200 and 300
print(y)
z=100 and 0 and 300
print(z)
t1=100>50 and 50<100
print(t1)
Output
200
300
0
True
Example
x=True or True
y=True or False
z=False or True
p=False or False
print(x,y,z,p)
a=100 or 200
b=0 or 200
c=200 or 300 or 0
d=0 or 200 or 300
print(a,b,c,d)
e=0 or 0
print(e)
Output:
True True True False
100 200 200 200
0
Example:
a=100 and 200 or 300
b=100 or 200 and 300
c=0 or 200 and 300
print(a,b,c)
p=100>50 or 100>50 and 50<100
print(p)
Output:
200 100 300
True
Example:
x=not True
print(x)
y=not False
print(y)
a=not 100
b=not 0
print(a,b)
Operator Meaning
>> Right shift operator
<< Left shift operator
& Bitwise and operator
| Bitwise or operator
^ Bitwise xor operator
~ Bitwise not operator
>> right shift operator is used to shift number of bits toward right side.
By shift number bits towards right the value get decremented.
Shifting bits towards right side is deleting bits at right side.
Example
n=30
m=n>>2
print(n,m)
Output
30 7
Formula => num//2**bits ➔ 30//2**2 ➔ 30//4 ➔ 7
Output:
30 120
& Bitwise and operator
| Bitwise or operator
^ Bitwise xor operator
~ Bitwise not operator
Logic gates are the basic building blocks of any digital system. It is
an electronic circuit having one or more than one input and only
one output. The relationship between the input and the output is
based on a certain logic. Based on this, logic gates are named as
AND gate, OR gate, NOT gate etc.
Example:
a=10
b=5
a+=b
print(a,b)
Output:
15 5
Identity Operators
Every object in python is having identity. This identity is called
address. Identity operators are used to compare addresses.
1. is
2. is not
These operators return Boolean value(True/False).
If two variables hold address of same object it return True otherwise
return False.
== operator is used to compare the state/values of the object.
Example
>>> f1=1.5
>>> f2=1.5
>>> id(f1)
1012338075920
>>> id(f2)
1012338076944
>>> f1==f2
True
>>> f1 is f2
False
>>>
Example
>>> x=1.5
>>> y=x
>>> id(x)
1012338815120
>>> id(y)
1012338815120
>>> x==y
True
>>> x is y
True
>>>
Membership Operators
1. sequence
2. selection
3. iteration
If..else
This syntax define two block 1. If block 2. Else block
Syntax:
If <condition>/<test>:
Statement-1
Statement-2
else:
statement-3
statement-4
statement-5
if False:
print("Hello")
print("Bye")
Output:
Hello
Bye
Bye
Example
if 100>50:
print("Python")
if 100<50:
print("Python")
output:
Python
Example
if True:
print("Python")
else:
print("Jython")
if False:
print("Python")
else:
print("Jython")
Output:
Python
Jython
Example
# Develop login application
user=input("UserName :")
pwd=input("Password :")
if user=="nit" and pwd=="nit123":
print("welcome to my application")
else:
print("invalid username or password")
# write a program to find input number is even or odd
num=int(input("enter any number"))
if num%2==0:
print(num,"is even")
else:
print(num,"is odd")
# write a program to find input character is vowel or not
ch=input("enter any character")
if ch in "aeiouAEIOU":
print(ch,"is vowel")
else:
print(ch,"is not vowel")
ch=input("enter charCTER")
if(ch=='A' or ch=='E'or ch=='I' or ch=='O' or ch=='U' or ch=='a' or ch=='e' or ch=='i' or
ch=='o'or ch=='u' ):
print("chara is vowel")
else:
print("not vowel")
nested if
if within if or if followed by if is called nested if.
Syntax:
If condition1:
If condition2:
Statement-1
else:
statement-2
else:
statement-3
# login application
accno=int(input("Enter accno"))
bal=float(input("Enter balance"))
ttype=input("Enter transaction type")
tamt=float(input("Enter transaction amount"))
if ttype=='withdraw':
if tamt<bal:
bal=bal-tamt
else:
print("insuff balance")
elif ttype=='deposit':
bal=bal+tamt
else:
print("invalid transaction type")
print("AccountNo ",accno)
print("Balance ",bal)
print("TransactionType ",ttype)
print("TransactionAmt ",tamt)
1. While
2. For
Syntax-1:
while <expression>/<condition>:
statement-1
statement-2
statement-3
while <condition>:
statement-1
statement-2
else:
statement-3
statement-4
statement-5
Syntax1:
range()
Syntax1:range(stop)
Syntax2:range(start,stop,step)
Example:
r1=range(1,21)
print(r1)
for value in r1:
print(value,end=' ')
Example
r=range(1,6,1)
it=iter(r)
value1=next(it)
value2=next(it)
value3=next(it)
value4=next(it)
value5=next(it)
print(value1,value2,value3,value4,value5)
r1=range(1,6,1)
for value in r1:
print(value)
Example
e1=range(1.5,4.5)
for value in e1:
print(value)
The above code display error because range can be used only with
integers.
# write a program to generate even numbers between 1 to n
Example:
n=int(input("enter n value"))
for value in range(2,n+1,2):
print(value)
for value in range(1,n+1,2):
print(value)
Example:
r1=range(10,0,-1)
r2=range(-1,-11,-1)
r3=range(-10,0,1)
for value in r1:
print(value,end=' ')
print()
for value in r2:
print(value,end=' ')
print()
for value in r3:
print(value,end=' ')
print()
1 1 1 1 1 for i in range(1,6):
2 2 2 2 2 for j in range(1,6):
3 3 3 3 3 print(i,end=' ')
4 4 4 4 4 print()
5 5 5 5 5
5 5 5 5 5 for i in range(5,0,-1):
4 4 4 4 4 for j in range(1,6):
3 3 3 3 3 print(i,end=' ')
2 2 2 2 2 print()
1 1 1 1 1
1 for i in range(1,6):
2 2 for j in range(1,i+1):
3 3 3 print(i,end=' ')
4 4 4 4 print()
5 5 5 5 5
5 5 5 5 5 for i in range(5,0,-1):
4 4 4 4 for j in range(1,i+1):
3 3 3 print(i,end=' ')
2 2 print()
1
5 for i in range(5,0,-1): # 5 4 3 2 1
4 4 for j in range(5,i-1,-1):
3 3 3 print(i,end=' ')
2 2 2 2 print()
1 1 1 1 1
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
A
A B
A B C
A B C D
A B C D E
1 for i in range(1,6):
1 2 for j in range(1,6):
1 2 3 if j<=i:
1 2 3 4 print(j,end=' ')
1 2 3 4 5 print()
1 2 3 4 5 for i in range(5,0,-1):
1 2 3 4 for j in range(1,6):
1 2 3 if j<=i:
1 2 print(j,end=' ')
1 print()
A for i in range(65,70):
A B for j in range(65,70):
A B C if j<=i:
A B C D print(chr(j),end=' ')
A B C D E print()
1 2 3 4 5 for i in range(1,6):
2 3 4 5 for j in range(1,6):
3 4 5 if j>=i:
4 5 print(j,end=' ')
5 else:
print(' ',end=' ')
print()
5 for i in range(5,0,-1):
4 5 for j in range(1,6):
3 4 5 if j<=i:
2 3 4 5 print(j,end=' ')
1 2 3 4 5 print()
1 for i in range(1,6):
2 1
3 2 1 for j in range(5,0,-1):
4 3 2 1
5 4 3 2 1 if j<=i:
else:
print(' ',end = ' ')
print()
for i in range(1,10):
if i<=5:
continue
print(i)
for i in range(1,6):
print("inside for block")
else:
print("inside else block")
Note: else block is not executed when loop is terminated with break
for i in range(1,10):
if i>5:
break
print(i)
else:
print("inside else block")
pass
pass is a keyword in python.
pass is a null operation — when it is executed, nothing happens. It is
useful as a placeholder when a statement is required syntactically,
but no code needs to be executed.
Eg:
If True:
print(“Hello”)
Explanation: The above code generate syntax error, because if
required at least one statement. Any block in python required one
statement. If you want write block without performing any operation
then include pass statement.
Eg:
If true:
pass
Explanation: The above code does not generate any error.
while False:
pass
Explanation: The above code does not generate any error
Example
if True:
pass # it is not for terminate, it just perform null operation
print("inside if")
print("Hello")
Strings
Example
# special characters
For loop is used to read the content of iterable, string is also iterable.
For loop each time read one character and perform operation.
Using index we can read only one character from string. With the
slicing we can read more than one character. Slice is reading part of
a sequence.
>>> str1="PYTHON"
>>> str2=str1[0:4:1]
>>> str1
'PYTHON'
>>> str2
'PYTH'
>>> str3=str1[1:5]
>>> str3
'YTHO'
>>> str4=str1[::]
>>> str4
'PYTHON'
>>> str5=str1[:]
>>> str5
'PYTHON'
>>> str6=str1[:3]
>>> str6
'PYT'
>>>
>>> str7=str1[::1]
>>> str8=str1[::-1]
>>> str7
'PYTHON'
>>> str8
'NOHTYP'
Example:
str1="PROGRAMMING"
str2=str1[::]
str3=str1[:]
str4=str1[::1]
str5=str1[::-1]
str6=str1[::2]
str7=str1[::-2]
str8=str1[2:5]
str9=str1[5:2:-1]
str10=str1[-3:-6:-1]
str11=str1[-6:-3:1]
print(str1)
print(str2)
print(str3)
print(str4)
print(str5)
print(str6)
print(str7)
print(str8)
print(str9)
print(str10)
slice() object
slice object is reusable
Syntax-1:slice(stop) ➔ default start 0 and step +1
Syntax-2:slice(start,stop,[step]) ➔ default step is +1
Example
s=slice(4)
str1="PROGRAMMING"
str2="LANGUAGE"
str3=str1[s]
str4=str2[s]
print(str1)
print(str2)
print(str3)
print(str4)
Example
s1=slice(0,5)
str1="PROGRAMMING"
str2="LANGUAGE"
str3=str1[s1]
str4=str1[s1]
s2=slice(-1,-5,-1)
str5=str1[s2]
str6=str2[s2]
print(str1)
print(str2)
print(str3)
print(str4)
print(str5)
print(str6)
String methods
Conversion Methods
• str.capitalize()
o Return a copy of the string with its first character
capitalized and the rest lowercased.
• str.swapcase()
o Return a copy of the string with uppercase characters
converted to lowercase and vice versa. Note that it is not
necessarily true that s.swapcase().swapcase() == s.
• str.title()
o Return a titlecased version of the string where words start
with an uppercase character and the remaining
• str.upper()
o Return a copy of the string with all the cased characters
converted to uppercase.
• str.lower()
o Return a copy of the string with all the cased characters
converted to lowercase
Example
str1="python"
str2=str1.upper()
print(str1,str2)
str3="JAVA"
str4=str3.lower()
print(str3,str4)
str5="datascience"
str6=str5.capitalize()
print(str5,str6)
str7="gudio van rossum"
str8=str7.title()
print(str7,str8)
str9="aBcDeF"
str10=str9.swapcase()
print(str9,str10)
str.isdecimal()
Return True if all characters in the string are decimal characters and
there is at least one character, False otherwise
Example
str1="123"
b1=str1.isdecimal()
print(b1)
str2="0b1010"
b2=str2.isdecimal()
print(b2)
str3="0o45"
b3=str3.isdecimal()
print(b3)
str4="0xab"
b4=str4.isdecimal()
print(b4)
if str1.isdecimal():
n=int(str1)
print(n)
str.isdigit()
Return True if all characters in the string are digits and there is at least
one character, False otherwise
str1="123"
b1=str1.isdigit()
print(b1)
str2="abc"
b3=str2.isdigit()
print(b3)
# write a program to input string and count number of
alphabets,digits and special characters
str1=input("Enter any string")
ac=0
dc=0
sc=0
for ch in str1:
if ch.isalpha():
ac=ac+1
elif ch.isdigit():
dc=dc+1
else:
sc=sc+1
print("Alphabet count ",ac)
print("Digit count ",dc)
print("Special character count",sc)
str.islower()
str.isspace()
str.istitle()
str.isupper()
str1=input("Enter string")
uc=0
lc=0
sc=0
for ch in str1:
if ch.isupper():
uc=uc+1
elif ch.islower():
lc=lc+1
elif ch.isspace():
sc=sc+1
print("uppercase characters ",uc)
print("lowercase characters ",lc)
print("space count ",sc)
Return the lowest index in the string where substring sub is found
within the slice s[start:end]. Optional arguments start and end
are interpreted as in slice notation. Return -1 if sub is not found.
Return True if string starts with the prefix, otherwise return False.
prefix can also be a tuple of prefixes to look for. With optional
start, test string beginning at that position. With optional end,
stop comparing string at that position.
Return True if the string ends with the specified suffix, otherwise
return False. suffix can also be a tuple of suffixes to look for. With
optional start, test beginning at that position. With optional end,
stop comparing at that position.
Example
str1="python is a programming langauge"
i=str1.find("is")
print(i)
i=str1.rfind("is")
print(i)
str2="python is a programming and is a scripting langauge"
i1=str2.find("is")
i2=str2.rfind("is")
print(i1)
print(i2)
Example
str1="python is a programming and is a scripting langauge"
i1=str1.find("a",12)
print(i1)
i2=str1.find("a")
print(i2)
Example
str1="naresh"
b1=str1.startswith("n")
print(b1)
b2=str1.startswith(('a','b','c'))
print(b2)
b3=str1.endswith("h")
print(b3)
b4=str1.endswith(('h','H','a','e'))
print(b4)
Collections or Data Structures
Collection itself is one object which contains more than one object.
Grouping individual objects and representing it is one object.
Every collection follows some set of rules and regulation for
organization of objects/data structures.
As a part of python or python support the following data structures.
1. List ➔ Sequence type
2. Tuple ➔ Sequence type
3. Set ➔ non sequence type
4. Frozenset ➔ non sequence type
5. Dict ➔ non sequence
Sequence types are index based and organize objects in sequential
order.
Non sequence types are non index based organizing objects are not
done using index.
Every collection is called one container.
Containers are used to store and perform aggregate operations or
group operations. These are also used to send data from one place
to another.
Collections are used to store more than one value/object.
List
Lists are mutable sequences, typically used to store collections of
homogeneous items or similar type of items. But it also support to
store heterogeneous items or different types.
After creating list we can modify (add,update or delete) items.
List is a index based collection, where reading and writing is done
using index. Index allows to read and write in sequentially or
randomly.
List allows duplicates.
List is ordered collection, where insertion is preserved (order of
insertion does not changes from one insertion to another).
List is sequence data type or data type.
>>> list1=[]
>>> print(list1)
[]
>>> print(type(list1))
<class 'list'>
>>> list2=[10]
>>> print(list2)
[10]
>>> print(type(list2))
<class 'list'>
>>> list3=[10,20,30,40,50]
>>> print(type(list3))
<class 'list'>
>>> print(list3)
[10, 20, 30, 40, 50]
>>>
>>> print(type(list3))
<class 'list'>
>>> print(list3)
[10, 20, 30, 40, 50]
>>> list4=[10,1.5,"naresh",1+2j]
>>> list4
[10, 1.5, 'naresh', (1+2j)]
>>> print(type(list4))
<class 'list'>
>>>
>>> student_record=[101,'naresh','python',5000.0]
>>> print(student_record)
[101, 'naresh', 'python', 5000.0]
>>> list1=list(range(10,110,10))
>>> print(list1)
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
>>> list2=list("PYTHON")
>>> print(list2)
['P', 'Y', 'T', 'H', 'O', 'N']
>>> list3=list(list1)
>>> print(list3)
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
>>>
List is an iterable, which allows to each time one object. We can
create list using existing iterables or collections using list() type.
print(list1)
print("Even Numbers Count ",ecount)
print("Odd Numbers Count ",ocount)
Example
# list the names whose name ends with h
list1=['naresh','suresh','rajesh','kishore','raman']
for i in range(0,len(list1)): # 0 1 2 3 4
if list1[i].endswith('h'):
print(list1[i])
# list names whose name starts with r
for i in range(0,len(list1)):
if list1[i].startswith('r'):
print(list1[i])
# list names whose name starts with r or s
for i in range(0,len(list1)):
if list1[i].startswith(('r','s')):
print(list1[i])
Reading elements from list using slicing.
Slicing allows to read more than one value. This slicing is done using
two ways.
1. Slice operator
2. Slice object
Example
list1=list(range(10,110,10))
print(list1)
list2=list1[::]
list3=list1[::-1]
list4=list1[2:]
list5=list1[-2::-1]
print(list2,list3,list4,list5,sep="\n")
list6=list1[3:7]
print(list6)
list7=list1[7:3:-1]
list8=list1[-6:-2]
print(list7,list8,sep='\n')
Example
names_list=['naresh','suresh','rajesh','kishore','rakesh','ramesh']
s1=slice(5)
names_list1=names_list[s1]
s2=slice(5,2,-1)
names_list2=names_list[s2]
print(names_list1,names_list2,sep="\n")
iterator
The content list or sequence can be read using iterator. Iterator
allows to read each time one object.
list1=[10,20,30,40,50]
i=iter(list1)
e1=next(i)
e2=next(i)
e3=next(i)
print(list1)
print(e1,e2,e3)
for e in i:
print(e,sep='\n')
enumeration
The content of list or sequence can be read using enumeration, this
return count and element. This is useful to convert list map collection.
list1=[10,20,30,40,50]
e=enumerate(list1)
print(next(e))
print(next(e))
for loop
for loop each time it read one value from list or collection and
execute block of statements.
list1=list(range(10,110,10))
for value in list1:
print(value)
s=0
for value in list1:
s=s+value
print(s)
Example1:
list1=[]
print(list1)
list1.append(10)
list1.append(20)
list1.append(30)
print(list1)
Example2:
# write a program to read the scores n players and display
scores=[]
n=int(input("Enter how many players"))
for i in range(n):
score=int(input("Enter score"))
scores.append(score)
sales=[]
n=int(input("enter how may sales persons"))
for i in range(n):
sale=float(input("enter sale amount"))
sales.append(sale)
print(sales)
min_sale=min(sales)
max_sale=max(sales)
print(min_sale)
print(max_sale)
Example
list1=list(range(10,110,10))
print(list1)
list1[0]=99 # using index we can replace only one value
print(list1)
list1[0:4]=[11,22,33,44] # using slicing we can replace more than one
value
print(list1)
Deleting elements from list
Example
# deleting using index, it allows to delete only one
list1=[10,20,30,40,50]
print(list1)
del list1[0]
print(list1)
Example
list1=list(range(1,50))
print(list1)
del list1[1::2]
print(list1)
Example
list1=list(range(10))
print(list1)
list1.clear()
print(list1)
Example
list1=list(range(1,50))
print(list1)
del list1[:]
print(list1)
Example
list1=list(range(10,110,10))
print(list1)
list1.remove(20)
print(list1)
# example of insert
list1=[10,20,30,40,50]
print(list1)
list1.insert(0,99)
print(list1)
list2=[100,200,300,400,500]
print(list2)
list2[2:2]=[600,700]
print(list2)
In shallows copy if changes done using one list that changes reflect
to another list.
Q:What is deep copy?
Deep copy is object copy, it will not copy addresses but create
copy of object and copy into another sequence/list.
For performing deep copy, python provide copy module. This
module is having a function deepcopy()
In this copy if any changes done in one list, that changes not reflect
another list.
copy.deepcopy(x[, memo])
Return a deep copy of x.
import copy
list1=[10,[20,30]]
list2=copy.deepcopy(list1)
print(list1)
print(list2)
list1[1].append(40)
print(list1)
print(list2)
list2[1].append(100)
print(list2)
print(list1)
# stack operations
stack=[]
while True:
print("****Stack Operations****")
print("1. Push")
print("2. Pop")
print("3. Display")
print("4. Exit")
opt=int(input("enter option"))
if opt==1:
ele=int(input("enter element to push"))
stack.append(ele)
print("element pushed inside stack")
if opt==2:
if len(stack)==0:
print("Stack Empty")
else:
print("Elemeted poped",stack.pop())
if opt==3:
print(stack)
if opt==4:
break
This method sorts the list in place, using only < comparisons between
items. Exceptions are not suppressed - if any comparison operations
fail, the entire sort operation will fail (and the list will likely be left in a
partially modified state.
Example
list1=[10,40,20,50,30]
print(list1)
list1.sort()
print(list1)
list1.sort(reverse=True)
print(list1)
stringlist=['aaa','AAA','bbb','BBB','ccc','CCC']
print(stringlist)
stringlist.sort()
print(stringlist)
stringlist.sort(key=str.upper)
print(stringlist)
stringlist.sort(key=str.lower,reverse=True)
print(stringlist)
len(s) length of s
min(s) smallest item of s
max(s) largest item of s
s.count(x) total number of occurrences of x in s
Example
list1=[10,20,30,40,50]
print(len(list1))
print(max(list1))
print(min(list1))
print(list1.count(10))
Nested List
List within list is called nested list. Nested list can be used as matrix.
Nested list allows organizing data in rows and columns.
List is index based collection where we can read and write using
index.
Example
list1=[[1,2],[3,4],[5,6]]
print(list1[0][0],list1[0][1])
print(list1[1][0],list1[1][1])
print(list1[2][0],list1[2][1])
print(list1[0])
print(list1[1])
print(list1[2])
list2=[10,20,[30,40]]
print(list2[0])
print(list2[1])
print(list2[2])
print(list2[2][0],list2[2][1])
Example
list1=[]
list1.append([])
list1.append([])
print(list1)
list1[0].append(10)
list1[0].append(20)
list1[1].append(30)
list1[1].append(40)
print(list1)
print(list1[0][0])
print(list1[0][1])
print(list1[1][0])
print(list1[1][1])
print(list1[0])
print(list1[1])
Example
# write a program to read 2x2 matrix and display
matrix=[]
for i in range(2): # 0 1
matrix.append([])
for j in range(2):
ele=int(input("enter element"))
matrix[i].append(ele)
print(matrix)
for i in range(2):
for j in range(2):
print(matrix[i][j],end=' ')
print()
# write a program to read MxN matrix and display
m=int(input("enter number of rows"))
n=int(input("enter number of columns"))
matrix=[]
for i in range(m):
matrix.append([])
for j in range(n):
ele=int(input("enter element"))
matrix[i].append(ele)
for i in range(m):
for j in range(n):
print(matrix[i][j],end=' ')
print()
print(matrix)
print(matrix1)
print(matrix2)
print(matrix3)
Comprehension
For constructing a list, a set or a dictionary Python provides special
syntax called “displays”, each of them in two flavors:
Ex:
List1=[10,20,30,40,50]
List2=[1+2,2+2,3+4,5+5]
Example
# create random 10 otp list
import random
otp_list=[str(random.randint(0,9))+str(random.randint(0,9))+str(rando
m.randint(0,9))+str(random.randint(0,9))+str(random.randint(0,9)) for i
in range(10)]
print(otp_list)
Example
# create list with 5 random passwords
import random
password_list=[chr(random.randint(65,91))+
chr(random.randint(97,121))+
chr(random.randint(65,91))+
chr(random.randint(97,121))+
str(random.randint(1,9))
for i in range(5)]
print(password_list)
Example
names_list=['naresh','suresh','ramesh','kishore']
names_list1=[s.upper() for s in names_list]
print(names_list)
print(names_list1)
# without comprehension
names_list2=[]
for name in names_list:
names_list2.append(name.upper())
print(names_list2)
Comprehension with test condition or filter
Example
list1=list(range(1,31))
print(list1)
even_list=[value for value in list1 if value%2==0]
odd_list=[value for value in list1 if value%2!=0]
print(even_list)
print(odd_list)
Example
sales_list=[10000,12000,15000,20000,21000,30000,13000,14000,35000]
sales_list1=[sales for sales in sales_list if sales<15000]
sales_list2=[sales for sales in sales_list if sales>=15000]
print(sales_list)
print(sales_list1)
print(sales_list2)
Example
names_list=['suresh','kishore','naresh','ramesh','rajesh']
names_list1=[name for name in names_list if name.endswith('h')]
names_list2=[name for name in names_list if
name.startswith(('s','k','r'))]
print(names_list)
print(names_list1)
print(names_list2)
List Comprehension using nested for loop
Example
matrix1=[[1,2],[3,4]]
matrix2=[[5,6],[8,9]]
matrix3=[[matrix1[i][j]+matrix2[i][j] for j in range(2)] for i in range(2)]
print(matrix1)
print(matrix2)
print(matrix3)
Example
list1=[[1,2,3],[4,5,6],[7,8,9]]
list2=[col for row in list1 for col in row]
print(list1)
print(list2)
tuple
tuple is immutable collection. After creating tuple we cannot modify
(add,update or delete) items.
Tuple is useful to represent dictionaries.
Tuple is useful to represent function arguments.
Tuple is read only, we can read but cannot modify.
Example
t1=(10,20,30,40,50)
print(t1)
t1[0]=99 # error
print(t1)
Example:
t1=(10,20,30,40,50)
print(t1)
del t1[0] # error
print(t1)
Example
# converting list to tuple and tuple to list
t1=(10,20,30,40,50)
l1=list(t1)
l1.append(60)
t1=tuple(l1)
print(t1)
set
set is non index based collection.
Set is unordered collection, where insertion order is not preserved.
In set data is organized using hashing data structure.
Set does not allow duplicates.
Set is mutable collection, after creating set we can add and remove
items.
Set allows only hashable objects. The object which generate
hashcode is called hashable object. This hashcode is used to
organize objects in hash based data structures. If two objects are
equal then it should generate same hashcode.
Hashcode is an integer value, which is used to organize objects in
hash based data structures.
Example:
>>> hash(10)
10
>>> hash(1.5)
1073741825
>>> hash("java")
471029483
>>> x="java"
>>> y="java"
>>> hash(x)
471029483
>>> hash(y)
471029483
>>> a=100
>>> b=100
>>> a==b
True
>>> hash(a)
100
>>> hash(b)
100
>>> f1=1.5
>>> f2=1.5
>>> f1==f2
True
>>> hash(f1)
1073741825
>>> hash(f2)
1073741825
>>> s1="python"
>>> s2="python"
>>> s1==s2
True
>>> hash(s1)
-1745864186
>>> hash(s2)
-1745864186
>>>
Q: What is hashing data structure?
According to hashing there is a hash table. Each location in
hashtable is identified with key. Each location is called bucket, which
one or more than one object.
Where to add the object is defined by hashing alg.
Example
# creating set using existing iterables
set1=set() # creating empty set
set2=set([10,20,30,40,50])
set3=set({10,20,30,40,50})
set4=set(range(10,60,10))
set5=set((10,20,30,40,50))
set6=set("PYTHON")
print(set1,set2,set3,set4,set5,set6,sep='\n')
How to read elements from set?
We can read elements from set using,
1. For loop
2. Iterator
3. Enumerator
Set does not allow indexing and slicing, because set is not index
based collection.
Example
# reading using for loop
set1={10,20,30,40,50}
for value in set1:
print(value)
# reading using iterator
it=iter(set1)
value1=next(it)
value2=next(it)
value3=next(it)
print(value1,value2,value3)
# reading using enumeration
e=enumerate(set1)
value1=next(e)
value2=next(e)
value3=next(e)
print(value1,value2,value3)
list1=[10,20,10,20,30,40,50,30,40,50]
set1=set(list1)
print(set1)
list2=list(set1)
print(list2)
#output 3-30,3-20,1-30,1-40
set1=set()
print(set1)
set1.add(10)
set1.add(20)
set1.add(30)
set1.add(40)
set1.add(50)
print(set1)
set1={10,20,30,40,50}
print(set1)
set1.remove(10)
print(set1)
set1.remove(10)
discard(elem)
set1={10,20,30,40,50}
print(set1)
set1.discard(100)
Set operations provided by set.
union(*others)
set | other | ...
Return a new set with elements from the set and all others.
intersection(*others)
set & other & ...
Return a new set with elements common to the set and all
others.
difference(*others)
set - other - ...
Return a new set with elements in the set that are not in the
others.
symmetric_difference(other)
set ^ other
Return a new set with elements in either the set or other but not
both.
Example:
A={1,2,3,4,5}
B={1,2,3,6,7}
C=A.union(B)
print(A,B,C,sep='\n')
D=A|B
print(A,B,D,sep='\n')
Example
python_students={'suresh','rajesh','kishore'}
java_students={'ramesh','naresh','kiran'}
python_java_students=python_students.union(java_students)
print(python_students)
print(java_students)
print(python_java_students)
Example
A={1,2,3,4,5}
B={1,2,3,5,6}
C={1,2,7,8,9}
D=A|B|C
print(D)
intersection(*others)
set & other & ...
Return a new set with elements common to the set and all others.
A={10,20,30,40,50}
B={10,20,40,50,60}
C=A.intersection(B)
print(A,B,C,sep='\n')
python_students={'suresh','kishore','rajesh','ramesh'}
java_students={'kishore','naresh','ramesh','kiran'}
both_students=python_students.intersection(java_students)
print(python_students)
print(java_students)
print(both_students)
A={1,2,3,4,5}
B={1,2,3,6,7}
C={6,7,8,9,10}
D=A&B&C
print(A)
print(B)
print(C)
print(D)
difference(*others)
set - other - ...
Return a new set with elements in the set that are not in the others.
A={1,2,3,4,5}
B={1,2,3,6,7}
C=A.difference(B)
print(A,B,C,sep='\n')
python_students={'naresh','suresh','kishore','ramesh'}
java_students={'naresh','kiran','rajesh','karan'}
only_python=python_students.difference(java_students)
only_java=java_students.difference(python_students)
print(python_students)
print(java_students)
print(only_python)
print(only_java)
symmetric_difference(other)
set ^ other
Return a new set with elements in either the set or other but not both.
A={1,2,3,4,5}
B={1,2,3,6,7}
C=A.symmetric_difference(B)
print(A,B,C,sep='\n')
update(*others)
set |= other | ...
Update the set, adding elements from all others.
intersection_update(*others)
set &= other & ...
Update the set, keeping only elements found in it and all
others.
difference_update(*others)
set -= other | ...
Update the set, removing elements found in others.
symmetric_difference_update(other)
set ^= other
Update the set, keeping only elements found in either set, but
not in both.
Example
products_list1={'keyboard','mouse','disk'}
products_list2={'monitor','printer'}
products_list1.update(products_list2)
print(products_list1)
Example
A={1,2,3,4,5}
B={1,2,3,6,7}
A.intersection_update(B)
print(A)
Example
python_students={'naresh','suresh','kishore','kiran'}
java_students={'naresh','kiran','ramesh'}
python_students.difference_update(java_students)
print(python_students)
Example
A={1,2,3,4,5}
B={1,2,3,6,7}
A.symmetric_difference_update(B)
print(A)
isdisjoint(other)
Return True if the set has no elements in common with other. Sets are
disjoint if and only if their intersection is the empty set.
A={1,2,3,4,5}
B={6,7,8,9,10}
res=A.isdisjoint(B)
print(A,B,res,sep='\n')
sales_2019={10000,20000,30000,40000,50000}
sales_2020={10000,30000,60000,70000,90000}
b=sales_2019.isdisjoint(sales_2020)
print(b)
issubset(other)
set <= other
A={1,2,3,4,5}
B={1,2,3,4,5,6,7,8,9,10}
res=A.issubset(B)
print(A,B,res,sep='\n')
issuperset(other)
set >= other
A={1,2,3}
B={1,2}
res=A.issuperset(B)
print(A,B,res,sep='\n')
FrozenSet
Frozenset is immutable collection, after creating frozenset we cannot
modify.
Fronzenset is used to define a set in side set or nested set.
Inorder to define nested set the inner set must be frozenset because
frozenset is hashable.
How to create frozenset?
Frozenset is created using frozenset type or class.
Syntax:
Forzenset() ➔ creating empty frozenset
Forzenset(iterable) ➔ creating frozenset with iterable
>>> set1={{1,2,3}}
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
set1={{1,2,3}}
TypeError: unhashable type: 'set'
Nested sets are not possible directly, in order to create set inside set
we should use frozenset.
>>> f1=frozenset()
>>> f1.add(10)
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
f1.add(10)
AttributeError: 'frozenset' object has no attribute 'add'
>>> s=set()
>>> s.add(10)
>>> s
{10}
>>> s1={frozenset(range(1,6)),frozenset(range(6,11))}
>>> s1
{frozenset({1, 2, 3, 4, 5}), frozenset({6, 7, 8, 9, 10})}
>>> for s in s1:
print(s)
frozenset({1, 2, 3, 4, 5})
frozenset({6, 7, 8, 9, 10})
>>> for s in s1:
for value in s:
print(value)
1
2
3
4
5
6
7
8
9
10
>>>
In order to create dictionary using list, the list should consist of a tuple
which is key and value pair.
zip([1,2,3],[‘one’,’two’,’three’])
[(1,’one’),(2,’two’),(3,’three’)]
Example
courses_dict={'java':2000,'oracle':1000,'python':4000,'c':1000}
print(courses_dict)
fee1=courses_dict['java']
fee2=courses_dict['python']
fee3=courses_dict['c']
print(fee1,fee2,fee3)
# fee4=courses_dict['django'] it raises KeyError
2. Using for loop, for loop each time iterate/read key from
dictionary.
Example
students_dict={1:['naresh','python'],2:['suresh','java'],3:['kishore','cpp']}
print(students_dict)
for rno in students_dict:
print(rno,students_dict[rno])
Example
players_dict={'rahul':40,'hardhik':90}
for name in players_dict:
print(name,players_dict[name])
telephone_dir={'naresh':998877665,'suresh':77788777,'kishore':4556677
8}
print(telephone_dir)
names_view=telephone_dir.keys()
print(names_view)
phone_view=telephone_dir.values()
print(phone_view)
for name in names_view:
print(name)
for no in phone_view:
print(no)
d=telephone_dir.items()
print(d)
for t in d:
print(t)
for name,no in d:
print(name,no)
get(key,default)
dict1={1:'one',2:'two',3:'three'}
value=dict1[1]
print(value)
value=dict1.get(10,0)
print(value)
value=dict1.get(10)
print(value)
updating dictionary
the dictionary value can be updated using key. If the key is exists it
update the value, if key is not exists add new item.
Dict-name[key]=value
Update(iterable)
Example
dict1={1:10,2:20,3:30,4:40}
dict2={1:100,3:300,5:500,6:600}
print(dict1)
dict1.update(dict2)
print(dict1)
In order to update or add more than one item using update
method.
Example
dict1={1:100,2:200,3:300,4:400}
print(dict1)
dict1[1]=10
print(dict1)
Example
dict1={1:10,2:20,3:30,4:40,5:50}
print(dict1)
del dict1[2]
print(dict1)
dict1.clear()
print(dict1)
dict2={1:100,2:200,3:300,4:400}
print(dict2)
i=dict2.popitem()
print(i)
print(dict2)
***Shoping Cart***
1.Adding Porduct
2.Updating Product
3.Deleting Product
4.View Products
5.Exit
Enter your option:
product_dict={}
while True:
print("****Shoping Cart****")
print("1. Add Product")
print("2. Update Product")
print("3. Delete Product")
print("4. View Products")
print("5. Exit")
opt=int(input("Enter your option"))
if opt==1:
pname=input("Enter product name")
qty=int(input("Enter Qty"))
product_dict[pname]=qty
print("Product Added")
elif opt==2:
pname=input("Enter product name")
if pname in product_dict:
qty=int(input("enter qty"))
product_dict[pname]=qty
print("product updated")
else:
print("Product not exists")
elif opt==3:
pname=input("Enter product name to delete")
if pname in product_dict:
del product_dict[pname]
print("product deleted")
else:
print("product not exists")
elif opt==4:
for pname,qty in product_dict.items():
print(pname,qty)
elif opt==5:
break
Dictionary Comprehension
Dictionary comprehension allows to create dictionary using for loop
and test conditions.
Comprehension is elegant way creating dictionary.
Example
sales_dict1={'naresh':10000,'suresh':20000,'kishore':30000,'rajesh':35000
}
print(sales_dict1)
# without comprehension creating dictionary from existing dictionary
sales_dict2={}
for name,sales in sales_dict1.items():
sales_dict2[name]=sales
print(sales_dict2)
# with comprehension
sales_dict3={name:sales for name,sales in sales_dict1.items()}
print(sales_dict3)
Example
sales_dict1={'naresh':10000,'suresh':20000,'kishore':30000,'rajesh':35000
}
print(sales_dict1)
Functions
Python is multi paradigm programming language. It allows writing
programs using different programming methods or approaches.
Python support procedural oriented programming.
In procedural oriented programming instructions are organized by
dividing according their operations into small pieces and these small
pieces are called subroutines or functions.
Q: What is function?
A function is building block of procedural oriented programming.
A function is small program within program.
A function is named block, which consists instructions to perform
operation.
Adv of functions
1. Modularity : dividing programming instructions according to
their operations into small pieces, which are called functions.
2. Readability: Easy to understand
3. Reusability: It allows writing the code once and using number of
times.
4. Efficiency: reusability reduces the size of program, which
increase efficiency.
Example
def fun1():
print("Hello function1")
fun1() # calling the fun1/executing fun1/executable statement
def main():
drawline()
print("PYTHON LANGUAGE")
drawline()
print("PROGRAMMING LANGUAGE")
drawline()
main()
Local variables
Local variables are used within function but cannot used outside the
function.
Example:
def fun1():
x=100 # local variable
def main():
print(x) # cannot access local variable x of fun1 inside main
main()
Example
def add():
n1=100 # local variable
n2=200 # local variable
n3=n1+n2 # local variable
print(n3)
def main():
add()
main()
Global variables
The variables declared outside the function are called global
variables. Global variables can be anywhere within program or
outside the program.
Example:
x=100
y=200
def fun1():
print(x)
print(y)
def fun2():
print(x)
print(y)
def main():
print(x)
print(y)
fun1()
fun2()
main()
Example:
x=10
y=5
def add():
print(x+y)
def sub():
print(x-y)
def multiply():
print(x*y)
def div():
print(x/y)
def main():
add()
sub()
multiply()
div()
main()
Example
x=100
def fun1():
x=200 # creating local variable with name x inside fun1
print(x) # because in python variable is created by assigning value
def fun2():
print(x)
def main():
fun1()
fun2()
main()
How modify or update global variable within function?
global keyword
global variable-name,variable-name
def main():
fun1()
fun2()
main()
base=0 # global variable
height=0 # global variable
def read():
global base,height
base=float(input("Enter base"))
height=float(input("Enter height"))
def find_area():
area=base*height*0.5
print("Area of triangle",area)
def main():
read()
find_area()
main()
def fun2():
print(x)
print(y)
def main():
fun1()
fun2()
main()
def <function-name>(arg1,arg2,arg3,…):
statement-1
statement-2
Example:
def fun1(a,b):
print(a,b)
def main():
fun1(100,200)
fun1(a=100,b=300)
fun1(b=100,a=200)
fun1() # error
main()
return keyword
return <value>/<expression>
Example of function which return value
def add(n1,n2):
n3=n1+n2
return n3 # return value to calling function
def sub(n1,n2):
n3=n1-n2
return n3 # return value to calling function
def multiply(n1,n2):
n3=n1*n2
return n3 # return value to calling function
def div(n1,n2):
n3=n1/n2
return n3 # return value to calling function
def main(): # calling function
res1=add(100,200)
res2=sub(10,5)
res3=multiply(5,2)
res4=div(4,2)
print(res1)
print(res2)
print(res3)
print(res4)
main()
Example
def draw_line(ch,length): # required arguments
for i in range(length):
print(ch,end='')
print()
def main():
draw_line("*",10)
print("Hello")
draw_line("$",5)
print("Python")
draw_line("%",30)
main()
Syntax:
def <function-name>(arg1,arg2=value,arg3=value):
statement-1
statement-2
Example
def fun1(a,b=10):
print(a,b)
def main():
fun1(100,200)
fun1(200)
main()
Function with default arguments
Arguments which are assigned values at the time defining function.
If the values are not given to these arguments, it takes default
values.
Syntax:
def <function-name>(arg1,arg2=value,arg3=value):
statement-1
statement-2
Example
def fun1(a,b=10):
print(a,b)
def main():
fun1(100,200)
fun1(200)
main()
Example
def draw_line(ch='*',length=30):
for i in range(length):
print(ch,end='')
print()
def main():
draw_line()
draw_line('#')
draw_line('$',20)
draw_line(length=10)
main()
Example
def string_conversion(s,case='upper'):
s1=''
for ch in s:
if case=='upper':
if ch>='a' and ch<='z':
s1=s1+chr(ord(ch)-32)
else:
s1=s1+ch
elif case=='lower':
if ch>='A' and ch<='Z':
s1=s1+chr(ord(ch)+32)
else:
s1=s1+ch
return s1
def main():
str1=string_conversion("python")
str2=string_conversion("PYTHON",case='lower')
print(str1)
print(str2)
main()
Example
def sort_data(data,order='ascending'):
if order=='ascending':
for i in range(len(data)):
for j in range(len(data)-1):
if data[j]>data[j+1]:
data[j],data[j+1]=data[j+1],data[j]
elif order=='descending':
for i in range(len(data)):
for j in range(len(data)-1):
if data[j]<data[j+1]:
data[j],data[j+1]=data[j+1],data[j]
def main():
list1=[10,4,1,8,2,9,6]
sort_data(list1)
print(list1)
sort_data(list1,'descending')
print(list1)
main()
def function-name(arg1,arg2=value,*arg3):
statement-1
statement-2
arg1 ➔ is a required argument
arg2 ➔ is default argument
arg3 ➔ variable length argument
Example:
def fun1(*n):
print(n)
print(type(n))
def main():
fun1()
fun1(10)
fun1(10,20)
fun1(10,20,30)
fun1(10,20,30,40)
main()
Example
def maximum(*n):
m=0
for i in range(len(n)):
if m<n[i]:
m=n[i]
return m
def main():
m1=maximum()
print(m1)
m2=maximum(10,20)
print(m2)
m3=maximum(4,1,2)
print(m3)
main()
Example
def add(*value):
s=0
for i in range(len(value)):
s=s+value[i]
return s
def main():
s1=add(10,20)
s2=add(10,20,30)
s3=add(10,20,30,40)
print(s1,s2,s3)
main()
Keyword arguments
Keyword arguments receive values as key, value pair.
Keyword arguments are of type dictionary.
Dictionary consist of key and value.
Keywords argument is prefix with **
Syntax:
def <function-name>(arg1,arg2=value,*arg3,**arg4):
statement-1
statement-2
statement-3
Example
def fun1(**k):
print(k)
print(type(k))
def main():
fun1(a=10,b=20)
fun1(x=100,y=200)
main()
Example
def simple_intrest(**kwargs):
si=kwargs['amt']*kwargs['time']*kwargs['rate']/100
return si
def main():
si1=simple_intrest(amt=5000,time=12,rate=1.5)
print("Simple intrest",si1)
main()
Generators or Generator function
Generator a special function which return generator iterator.
Generators are used to generate range of value. It allows to
develop customized range.
Example
def fun1():
yield 10
yield 20
yield 30
yield 40
yield 50
def main():
n=fun1() # creating generator iterator object
print(next(n))
print(next(n))
print(next(n))
print(next(n))
print(next(n))
print(next(n)) # error
main()
Example
def alpha_generator():
for n in range(65,91):
yield chr(n)
def main():
alpha=alpha_generator() # creating generator iterator
print(next(alpha))
for c in alpha:
print(c,end=' ')
main()
Example
def prime_generator(m,n):
for num in range(m,n+1):
c=0
for i in range(1,num+1):
if num%i==0:
c=c+1
if c==2:
yield num
def main():
prime=prime_generator(5,50)
for value in prime:
print(value)
main()
Example
import random
def otp_generator():
while True:
n1=random.randint(0,9)
n2=random.randint(0,9)
n3=random.randint(0,9)
n4=random.randint(0,9)
n5=random.randint(0,9)
yield str(n1)+str(n2)+str(n3)+str(n4)+str(n5)
def main():
otp=otp_generator()
otp1=next(otp)
otp2=next(otp)
otp3=next(otp)
print(otp1,otp2,otp3)
main()