Pdf24 Merged
Pdf24 Merged
1. Keywords
2. Identifiers
3. Literals
4. Data types
5. Operators
Keywords
Keywords are language related words. The meaning of keyword is
reserved by python translator.
Each keyword is used to perform specific operation.
Soft Keywords
Soft keywords can be used as user defined word or identifiers.
>>> keyword.softkwlist
['_', 'case', 'match', 'type']
Identifiers
Identifier is programmer defined words or user defined words.
Identifier is used to identify programming elements.
1. Variable names
2. Function names
3. Data type names
4. Program name / Module name
5. Package name
>>> a=0123
SyntaxError: leading zeros in decimal integer literals are not
permitted; use an 0o prefix for octal integers
>>> amt1=500
>>> amt1
500
>>> type(amt1)
<class 'int'>
>>> amt2=1_500
>>> amt2
1500
>>> amt3=1_50_000
>>> amt3
150000
>>> a=10_
SyntaxError: invalid decimal literal
>>> b=_10
Traceback (most recent call last):
File "<pyshell#20>", line 1, in <module>
b=_10
NameError: name '_10' is not defined
Octal Integer
An integer value with base 8 is called octal integer.
Octal integer is created using digits range from 0-7.
This integer is prefix with 0o or 0O
Example:
>>> a=0o45
>>> type(a)
<class 'int'>
>>> b=0o89
SyntaxError: invalid digit '8' in octal literal
>>> c=0o278
SyntaxError: invalid digit '8' in octal literal
>>> b=0o35
>>> b
29
>>> c=0o125
>>> c
85
Hexadecimal Integer
An integer value with base 16 is called hexadecimal integer.
This integer is created using 16 digits 0-9,a-f/A-F
This integer is prefix with 0x or 0X.
Larger integer values are represented in hexadecimal format.
>>> n1=0xa
>>> n1
10
>>> n2=0xb
>>> n2
11
>>> n3=0xf
>>> n3
15
>>> n4=0xg
SyntaxError: invalid hexadecimal literal
>>> n5=0xabc
>>> n5
2748
>>> n6=0xff
>>> n6
255
>>> n6=0xbad
>>> n6
2989
Binary Integer
An integer value with base 2 is called binary integer.
Binary integer is created using two digits 0 and 1
Binary integer is prefix with 0b or 0B
>>> n1=0b10
>>> n1
2
>>> n2=0b1010
>>> n2
10
>>> n3=0b1012
SyntaxError: invalid digit '2' in binary literal
Identifiers
Identifier is programmer defined words or user defined words.
Identifier is used to identify programming elements.
1. Variable names
2. Function names
3. Data type names
4. Program name / Module name
5. Package name
>>> a=10
>>> a
10
>>> rollno=1
>>> rollno
1
>>> pass=100
SyntaxError: invalid syntax
>>> break=1
SyntaxError: invalid syntax
>>> class=5
SyntaxError: invalid syntax
>>> Pass=1
>>> Pass
1
>>> A=10
>>> a=20
>>> A
10
>>> a
20
amt$=10
SyntaxError: invalid syntax
$amt=1
SyntaxError: invalid syntax
>>> a*mt=1
SyntaxError: cannot assign to expression here. Maybe you meant '=='
instead of '='?
>>> stud_rollno=1
>>> stud_rollno
1
>>> _=1
>>> _
1
>>> __x__=10
>>> __x__
10
5. Identifier should start with alphabet or _ but should not start with
digit
>>> number1=100
number2=200
>>> number1
100
>>> number2
200
>>> 3number=300
SyntaxError: invalid decimal literal
>>> _number=400
>>> _number
400
>>> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa=10
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
10
>>>
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
bb=100
>>>
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
bb
100
>>> a=10
>>> b=20
>>> a+b
30
Naming Conventions
1. pascal case
2. snake case
3. camelcase
Data types
Scalar data types are used to allocate memory for one value or
single value.
1. int
2. float
3. complex
4. bool
5. NoneType
Collection data types are used to allocate memory for more than
one value. Collection data types are classified into 3 categories
1. Sequences
a. List
b. Tuple
c. Range
d. Str
e. Bytes
f. Bytearray
2. Sets
a. Set
b. Frozenset
3. Mapping
a. Dict
These 14 data types are called python standard data types
Literals
Literals are values which never changed.
Python literals are classified into two categories
1. Numeric
2. Non-Numeric
Numeric : integer, float, complex
Non Numeric: str, None, bool
What is class?
What is object?
Python is pure object oriented programming language. Every data
type in python is a class and data is represented as objects.
What is class?
A class represents data type.
Class is used to allocate memory for data or object.
Class defines structure of object.
Class is a blue print of object
Class defines properties and behavior of object.
Properties defines the values hold by object
Behavior defines the functionality of object
What is object?
An object is instance of a class
Allocating memory for members/properties of the class is process of
creating object.
Object is an implementation of a class.
Python is a dynamically typed programming language, variables are
not bind with specific data type or variables are not declared with
any data type.
int a; a=10
a=10; type(a) 🡪 int
a=1.5; Error a=1.5
type(a) 🡪 float
What is variable?
Variable is an identifier, which is used to identify value/object.
Variable is named memory location.
>>>
x=9999999999999999999999999999999999999999999999999999999999
999999
>>> x
999999999999999999999999999999999999999999999999999999999999
9999
>>> import sys
>>> sys.getsizeof(x)
56
>>> y=100
>>> sys.getsizeof(y)
28
>>> z=8999999999999999999
>>> sys.getsizeof(z)
36
Decimal Integer
An integer value with base 10 is called decimal integer.
This integer is created using all the digits from 0-9.
This integer is not prefix with 0
This integer is prefix with + or –
Default representation of integer values are in decimal format.
>>> a=0123
SyntaxError: leading zeros in decimal integer literals are not
permitted; use an 0o prefix for octal integers
Binary Integer
An integer value with base 2 is called binary integer.
Binary integer is created using two digits 0 and 1
Binary integer is prefix with 0b or 0B
>>> n1=0b10
>>> n1
2
>>> n2=0b1010
>>> n2
10
>>> n3=0b1012
SyntaxError: invalid digit '2' in binary literal
>>> rollno=125
>>> rollno
125
>>> accountNo=123456999
>>> accountNo
123456999
>>> color=0xff0000
>>> color
16711680
>>> color=0xff
>>> color
255
Example:
>>> a=60
>>> a
60
>>> id(a)
140716079894808
>>> b=90
>>> id(b)
140716079895768
>>> a=80
>>> a
80
>>> id(a)
140716079895448
Immutable objects are sharable.
Example:
>>> x=10
>>> y=10
>>> z=10
>>> x
10
>>> y
10
>>> z
10
>>> id(x)
140716079893208
>>> id(y)
140716079893208
>>> id(z)
140716079893208
>>> p=5+5
>>> p
10
>>> id(p)
140716079893208
Example:
>>> a=12
>>> a
12
>>> bin(a)
'0b1100'
>>> hex(a)
'0xc'
>>> oct(a)
'0o14'
>>> b=0xc
>>> b
12
>>> bin(b)
'0b1100'
>>> oct(b)
'0o14'
>>> bin(4000)
'0b111110100000'
c=0o12
>>> c
10
>>> oct(c)
'0o12'
>>> hex(c)
'0xa'
>>> bin(c)
'0b1010'
Example:
>>> a=1.5
>>> a
1.5
>>> type(a)
<class 'float'>
>>> a=1.5
>>> a
1.5
>>> type(a)
<class 'float'>
>>> b=1.123123123123123123123123123123123
>>> b
1.1231231231231231
>>> c=1.123456789123456789123456789
>>> c
1.1234567891234568
>>> f1=12.456
>>> f1
12.456
>>> f2=12456e-3
>>> f2
12.456
>>> f3=1.234e2
>>> f3
123.4
>>> c1=1+2j
>>> c1
(1+2j)
>>> type(c1)
<class 'complex'>
>>> c1.real
1.0
>>> c1.imag
2.0
>>> c2=2j
>>> c2
2j
>>> type(c2)
<class 'complex'>
>>> c2.real
0.0
>>> c2.imag
2.0
>>> c2.real=1.0
Traceback (most recent call last):
File "<pyshell#78>", line 1, in <module>
c2.real=1.0
AttributeError: readonly attribute
Example:
>>> a=True
>>> a
True
>>> type(a)
<class 'bool'>
>>> b=False
>>> b
False
>>> type(b)
<class 'bool'>
>>> c=1
>>> c
1
>>> type(c)
<class 'int'>
>>> d=10>2
>>> d
True
NoneType
NoneType represent None value.
In python None is represented as missing value or no value.
>>> rollno=1
>>> name=None
>>> fee=4000.0
>>> feePaid=True
>>> rollno
1
>>> name
>>> fee
4000.0
>>> feePaid
True
>>> a=None
>>> a
>>> type(a)
<class 'NoneType'>
string
String
Example:
>>> s1='python'
>>> s1
'python'
>>> s2='python 3.12'
s2
>>> 'python 3.12'
>>> s3='45'
>>> n1=45
>>> n1+10
55
>>> s3+10
Traceback (most recent call last):
File "<pyshell#19>", line 1, in <module>
s3+10
TypeError: can only concatenate str (not "int") to str
>>> s4='python is a
SyntaxError: incomplete input
>>> s4='python is "high" programming language'
>>> print(s4)
python is "high" programming language
>>> s5='python is a 'high level' programming language'
SyntaxError: invalid syntax
>>> str1="python"
>>> print(str1)
python
>>> str2="python 3.12"
>>> print(str2)
python 3.12
>>> str3="45"
>>> print(str3)
45
>>> str4="python is high level
SyntaxError: incomplete input
>>> rollno=101
>>> name="nk"
>>> course="FSP"
>>> description=''' Full Stack Python consists of 5 Modules
Module1: Python
Module2: Database
Module3: UI
Module4: Backend
Module5: Tools'''
>>> print(rollno)
101
>>> print(name)
nk
>>> print(course)
FSP
>>> print(description)
Full Stack Python consists of 5 Modules
Module1: Python
Module2: Database
Module3: UI
Module4: Backend
Module5: Tools
>>> str1=""" Python is
... high level, multiparadigm
... programming language"""
>>> print(str1)
Python is
high level, multiparadigm
programming language
Comments in Python
test1.py
# This is my first program in python
Output:
Hello
test2.py
a=''' This is my first python program '''
print("Hello")
print(a)
Output:
Hello
This is my first python program
What is indent?
Space given at the beginning of the statement is called indent.
Indent is used to create block.
print()
print() is a predefined function in python.
print() is a standard output function, this function is used to print data
or information on console/monitor.
Example:
print()
print()
print()
print()
Output:
4 blank lines
Example:
print(10)
print()
print(20)
print()
print(1.5)
print()
print("Hello")
Output:
10
20
1.5
Hello
Example:
print(10,20,30,40,50)
print(1,"nk","python",4000.0)
print(10,20,30,40,50,sep="$")
print(10,20,30,40,50,sep=",")
print(10,20,30,40,50)
print(1,2,3,4,5,sep="nit")
Output:
10 20 30 40 50
1 nk python 4000.0
10$20$30$40$50
10,20,30,40,50
10 20 30 40 50
1nit2nit3nit4nit5
Example:
rollno=101
name="Nk"
course="Python"
fee=5000.0
print("rollno",rollno)
print("name",name)
print("course",course)
print("fee",fee)
Output:
rollno 101
name Nk
course Python
fee 5000.0
Example:
a=10
b=20
c=30
print(a,b,c)
print("a","b","c")
Output:
10 20 30
abc
Example:
print(10,20,30,end=';')
print(40,50,60)
print(70,80)
Output:
10 20 30;40 50 60
70 80
Escape Sequences
Escape sequences are special string
These are called backslash character literals
\n New line
\t Horizontal tab space
\v Vertical tab space
\\ \
\” “
\’ ‘
\b backspace
Example:
print('\\')
print("\"")
print('\'')
print("\n")
print("\t")
Output:
\
"
'
Example:
a=10
b=20
c=30
print(a,b,c,sep="\n")
x=100
y=200
z=300
print(x,y,z,sep="\t")
Output:
10
20
30
100 200 300
Example:
a=10
b=20
print("sum of ",a,b,"is",a+b)
Output:
sum of 10 20 is 30
format string
A string prefix with f or F is called format string.
This string contains replacement fields, which are replaced with
values (OR) format string allows to insert values within string.
Format string is used to format output.
Inside format string replacement fields are represented using curly
braces {}.
Example:
a=10
b=20
print(f'sum of {a} and {b} is {a+b}')
Output:
sum of 10 and 20 is 30
Example:
a=10
print(f'{a:d},{a:o},{a:x},{a:b}')
b=1.5
print(f'{b}')
print(f'{b:f}')
print(f'{b:.2f}')
print(f'{b:.30f}')
c=1.5e-2
print(f'{c:e}')
print(f'{c:.2e}')
Output:
10,12,a,1010
1.5
1.500000
1.50
1.500000000000000000000000000000
1.500000e-02
1.50e-02
format function of string data type
before 3.8 formatting of output is done using format function of string
data type.
Example:
a=10
b=20
print("sum of {} and {} is {}".format(a,b,a+b))
print("{:d},{:o},{:x},{:b}".format(a,a,a,a))
base=1.5
height=2.5
print("Area of triangle with base={} and height={} is
{}".format(base,height,0.5*base*height))
print("Area of triangle with base={:.2f} and height={:.2f} is
{:.2f}".format(base,height,0.5*base*height))
Output:
sum of 10 and 20 is 30
10,12,a,1010
Area of triangle with base=1.5 and height=2.5 is 1.875
Area of triangle with base=1.50 and height=2.50 is 1.88
Input() function
input() is standard input function, this function is used to input/read
data from keyboard.
Input() is function is used to input/read string value.
Input() function allows to input/read one value.
Syntax:
variable=input([prompt])
Example:
a=input("Enter First Value ")
b=input("Enter Second Value ")
c=input("Enter value of c ")
print(a,b,c)
print(type(a),type(b),type(c))
Output:
Enter First Value 100
Enter Second Value 200
Enter value of c 300
100 200 300
<class 'str'> <class 'str'> <class 'str'>
Example:
# Write a program to print sum of integers
# input two integers from keyboard
Output:
Enter First Value 10
Enter Second Value 20
sum of 10 and 20 is 1020
1. Int()
2. Float()
3. Complex()
4. Bool()
5. Str()
int() function
This function is used to create integer object (OR) this function
performs the following conversions.
1. Int to int
2. Float to int
3. String to int
4. Bool to int
Syntax1: int(value)
Syntax2: int(value,base=10)
Output:
Enter First Value 100
Enter Second Value 200
sum of 100 and 200 is 300
Example:
>>> int(10)
10
>>> int(1.5)
1
>>> int(True)
1
>>> int(False)
0
>>> int(1+2j)
Traceback (most recent call last):
File "<pyshell#20>", line 1, in <module>
int(1+2j)
TypeError: int() argument must be a string, a bytes-like object or a
real number, not 'complex'
>>> int("65")
65
>>> int("1.25")
Traceback (most recent call last):
File "<pyshell#22>", line 1, in <module>
int("1.25")
ValueError: invalid literal for int() with base 10: '1.25'
>>> int("a")
Traceback (most recent call last):
File "<pyshell#23>", line 1, in <module>
int("a")
ValueError: invalid literal for int() with base 10: 'a'
>>> int("a",base=16)
10
>>> int("ff",base=16)
255
>>> int("ffff",base=16)
65535
>>> int("1010",base=2)
10
>>> int("1010")
1010
float() function
This function is used to create float object or to perform the following
conversions
1. float to float
2. int to float
3. string to float
4. bool to float
Syntax: float(value)
Example
>>> float(1.5)
1.5
>>> float(1)
1.0
>>> float(True)
1.0
>>> float(False)
0.0
>>> float("1.5")
1.5
>>> float("15e-1")
1.5
>>> float("15")
15.0
>>> float("abc")
Traceback (most recent call last):
File "<pyshell#38>", line 1, in <module>
float("abc")
ValueError: could not convert string to float: 'abc'
Example:
# Write a program to swap/interchange two float values input from
stdin
Output:
Enter value of a 1.5
Enter value of b 2.5
before swaping a=1.5 and b=2.5
after swaping a=2.5 and b=1.5
after swaping a=1.5 and b=2.5
after swaping a=2.5 and b=1.5
complex()
This function is used to create complex number (OR) perform the
following conversions
1. complex to complex
2. int to complex
3. float to complex
4. string to complex
5. bool to complex
complex()
This function is used to create complex number (OR) perform the
following conversions
1. complex to complex
2. int to complex
3. float to complex
4. string to complex
5. bool to complex
Example:
>>> comp1=complex(1+2j)
>>> print(comp1)
(1+2j)
>>> print(type(comp1))
<class 'complex'>
>>> comp2=complex("1+2j")
>>> print(comp2)
(1+2j)
>>> print(type(comp2))
<class 'complex'>
>>> comp3=complex("2j")
print(comp3)
2j
>>> print(type(comp3))
<class 'complex'>
>>> comp4=complex("4")
>>> print(comp4)
(4+0j)
>>> comp5=complex(1)
>>> print(comp5)
(1+0j)
>>> comp6=complex(2j)
>>> print(comp6)
2j
>>> print(comp6.real,comp6.imag)
0.0 2.0
>>> comp7=complex(True)
>>> print(comp7,type(comp7))
(1+0j) <class 'complex'>
>>> comp8=complex(False)
>>> print(comp8,type(comp8))
0j <class 'complex'>
>>> print(comp8.real,comp8.imag)
0.0 0.0
Example:
# Write a program for adding two complex numbers
Output:
input complex number1 1+2j
input complex number2 1+3j
sum of (1+2j) and (1+3j) is (2+5j)
bool() function
This function returns Boolean value (OR) this function performs the
following conversions.
1. Bool to bool
2. Int to bool
3. Float to bool
4. Complex to bool
5. String to bool
Example:
>>> b1=bool(True)
>>> print(b1)
True
>>> b2=bool(False)
>>> print(b2)
False
>>> b3=bool(0)
print(b3)
>>> False
>>> b4=bool(1)
>>> print(b4)
True
>>> b5=bool(100)
>>> print(b5)
True
>>> b6=bool(-5)
>>> print(b6)
True
>>> b7=bool(0.0)
>>> print(b7)
False
>>> b8=bool(0.5)
>>> print(b8)
True
>>> b9=bool(0+0j)
>>> print(b9)
False
>>> b10=bool(1+0j)
>>> print(b10)
True
>>> b11=bool("A")
>>> print(b11)
True
>>> b12=bool("NARESH")
>>> print(b12)
True
>>> b13=bool("False")
>>> print(b13)
True
>>> b14=bool("True")
>>> print(b14)
True
ord(),char()
Example:
>>> ord('A')
65
>>> ord('B')
66
>>> ord('C')
67
>>> ord('Z')
90
>>> ord('a')
97
>>> ord('b')
98
>>> ord('c')
99
>>> ord('z')
122
>>> chr(65)
'A'
>>> chr(66)
'B'
>>> chr(90)
'Z'
>>> chr(97)
'a'
>>> chr(98)
'b'
>>> chr(122)
'z'
Example:
# Write a program to convert given character from uppercase to
lowercase
char='B'
print(char)
value=ord(char) # 66
value=value+32
char1=chr(value)
print(char1)
value=ord(char1)
value=value-32
char2=chr(value)
print(char2)
Output:
B
b
B
B
str() function
This function returns string object (OR) this function is used to convert
other types into string type.
Syntax: str(value)
>>> s1=str()
print(s1)
>>> s2=str(25)
>>> print(s2)
25
>>> s3=str(1.5)
>>> print(s3)
1.5
>>> s2+s3
'251.5'
>>> print(type(s2),type(s3))
<class 'str'> <class 'str'>
>>> s4=str(1+2j)
>>> print(s4)
(1+2j)
>>> print(type(s4))
<class 'str'>
>>> s5=str(True)
>>> print(s5)
True
>>> s6=str(False)
>>> print(s6)
False
>>> print(type(s5),type(s6))
<class 'str'> <class 'str'>
Operators
What is operator?
Operator is a special symbol, which is used to perform operations.
Based on the numbers of operand used to perform operation, the
operators are classified into 3 categories
1. Unary Operator
2. Binary Operator
3. Ternary Operator
Types of operators
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Membership Operator
6. Identity Operator
7. Conditional Operator
8. Bitwise Operators
9. Walrus Operator (Python 3.8)
Arithmetic Operators
Operator Description
+ Adding or Concatenation
- Subtraction
* Multiplication or Repeat
/ Float Division
// Floor Division
% Modulo
** Exponent or Power
Example:
>>> a=10
>>> b=20
>>> c=a+b
>>> print(a,b,c)
10 20 30
>>> x=1.5
>>> y=1.2
>>> z=x+y
>>> print(x,y,z)
1.5 1.2 2.7
>>> b1=True
>>> b2=False
>>> b3=b1+b2
>>> print(b1,b2,b3)
True False 1
>>> b4=True+15
>>> print(b4)
16
>>> c1=1+2j
>>> c2=1+1j
>>> c3=c1+c2
>>> print(c1,c2,c3)
(1+2j) (1+1j) (2+3j)
>>> s1="Python"
>>> s2="3.12"
>>> s3=s1+s2
>>> print(s1,s2,s3)
Python 3.12 Python3.12
>>> s4="10"
>>> s5="15"
>>> s6=s4+s5
>>> print(s4,s5,s6)
10 15 1015
>>> s7="python"
>>> s8=3.12
>>> print(s7+s8)
Traceback (most recent call last):
File "<pyshell#108>", line 1, in <module>
print(s7+s8)
TypeError: can only concatenate str (not "float") to str
eval() function
it is a predefined function of python. This function evaluate string
representation of expression and return value.
eval(expression)
>>> a=eval("1.5")
>>> print(a,type(a))
1.5 <class 'float'>
>>> b=eval("25")
>>> print(b,type(b))
25 <class 'int'>
>>> c=eval("1+2j")
>>> print(c,type(c))
(1+2j) <class 'complex'>
>>> d=eval("10+20+30")
>>> print(d)
60
Example:
# write a program to add two numbers
Output
Enter first number 10
Enter second number 20
sum of 10 and 20 is 30
>>> a=10
>>> b=1.5
>>> c=a-b
>>> print(a,b,c)
10 1.5 8.5
>>> c1=1+2j
>>> c2=1j
>>> c3=c1-c2
>>> print(c1,c2,c3)
(1+2j) 1j (1+1j)
>>> c3=c1-2
>>> print(c3)
(-1+2j)
complex()
This function is used to create complex number (OR) perform the
following conversions
1. complex to complex
2. int to complex
3. float to complex
4. string to complex
5. bool to complex
Example:
>>> comp1=complex(1+2j)
>>> print(comp1)
(1+2j)
>>> print(type(comp1))
<class 'complex'>
>>> comp2=complex("1+2j")
>>> print(comp2)
(1+2j)
>>> print(type(comp2))
<class 'complex'>
>>> comp3=complex("2j")
print(comp3)
2j
>>> print(type(comp3))
<class 'complex'>
>>> comp4=complex("4")
>>> print(comp4)
(4+0j)
>>> comp5=complex(1)
>>> print(comp5)
(1+0j)
>>> comp6=complex(2j)
>>> print(comp6)
2j
>>> print(comp6.real,comp6.imag)
0.0 2.0
>>> comp7=complex(True)
>>> print(comp7,type(comp7))
(1+0j) <class 'complex'>
>>> comp8=complex(False)
>>> print(comp8,type(comp8))
0j <class 'complex'>
>>> print(comp8.real,comp8.imag)
0.0 0.0
Example:
# Write a program for adding two complex numbers
Output:
input complex number1 1+2j
input complex number2 1+3j
sum of (1+2j) and (1+3j) is (2+5j)
bool() function
This function returns Boolean value (OR) this function performs the
following conversions.
1. Bool to bool
2. Int to bool
3. Float to bool
4. Complex to bool
5. String to bool
Example:
>>> b1=bool(True)
>>> print(b1)
True
>>> b2=bool(False)
>>> print(b2)
False
>>> b3=bool(0)
print(b3)
>>> False
>>> b4=bool(1)
>>> print(b4)
True
>>> b5=bool(100)
>>> print(b5)
True
>>> b6=bool(-5)
>>> print(b6)
True
>>> b7=bool(0.0)
>>> print(b7)
False
>>> b8=bool(0.5)
>>> print(b8)
True
>>> b9=bool(0+0j)
>>> print(b9)
False
>>> b10=bool(1+0j)
>>> print(b10)
True
>>> b11=bool("A")
>>> print(b11)
True
>>> b12=bool("NK")
>>> print(b12)
True
>>> b13=bool("False")
>>> print(b13)
True
>>> b14=bool("True")
>>> print(b14)
True
ord(),char()
Example:
>>> ord('A')
65
>>> ord('B')
66
>>> ord('C')
67
>>> ord('Z')
90
>>> ord('a')
97
>>> ord('b')
98
>>> ord('c')
99
>>> ord('z')
122
>>> chr(65)
'A'
>>> chr(66)
'B'
>>> chr(90)
'Z'
>>> chr(97)
'a'
>>> chr(98)
'b'
>>> chr(122)
'z'
Example:
# Write a program to convert given character from uppercase to
lowercase
char='B'
print(char)
value=ord(char) # 66
value=value+32
char1=chr(value)
print(char1)
value=ord(char1)
value=value-32
char2=chr(value)
print(char2)
Output:
B
b
B
B
str() function
This function returns string object (OR) this function is used to convert
other types into string type.
Syntax: str(value)
>>> s1=str()
print(s1)
>>> s2=str(25)
>>> print(s2)
25
>>> s3=str(1.5)
>>> print(s3)
1.5
>>> s2+s3
'251.5'
>>> print(type(s2),type(s3))
<class 'str'> <class 'str'>
>>> s4=str(1+2j)
>>> print(s4)
(1+2j)
>>> print(type(s4))
<class 'str'>
>>> s5=str(True)
>>> print(s5)
True
>>> s6=str(False)
>>> print(s6)
False
>>> print(type(s5),type(s6))
<class 'str'> <class 'str'>
Operators
What is operator?
Operator is a special symbol, which is used to perform operations.
Based on the numbers of operand used to perform operation, the
operators are classified into 3 categories
1. Unary Operator
2. Binary Operator
3. Ternary Operator
Types of operators
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Membership Operator
6. Identity Operator
7. Conditional Operator
8. Bitwise Operators
9. Walrus Operator (Python 3.8)
Arithmetic Operators
Operator Description
+ Adding or Concatenation
- Subtraction
* Multiplication or Repeat
/ Float Division
// Floor Division
% Modulo
** Exponent or Power
Example:
>>> a=10
>>> b=20
>>> c=a+b
>>> print(a,b,c)
10 20 30
>>> x=1.5
>>> y=1.2
>>> z=x+y
>>> print(x,y,z)
1.5 1.2 2.7
>>> b1=True
>>> b2=False
>>> b3=b1+b2
>>> print(b1,b2,b3)
True False 1
>>> b4=True+15
>>> print(b4)
16
>>> c1=1+2j
>>> c2=1+1j
>>> c3=c1+c2
>>> print(c1,c2,c3)
(1+2j) (1+1j) (2+3j)
>>> s1="Python"
>>> s2="3.12"
>>> s3=s1+s2
>>> print(s1,s2,s3)
Python 3.12 Python3.12
>>> s4="10"
>>> s5="15"
>>> s6=s4+s5
>>> print(s4,s5,s6)
10 15 1015
>>> s7="python"
>>> s8=3.12
>>> print(s7+s8)
Traceback (most recent call last):
File "<pyshell#108>", line 1, in <module>
print(s7+s8)
TypeError: can only concatenate str (not "float") to str
eval() function
it is a predefined function of python. This function evaluate string
representation of expression and return value.
eval(expression)
>>> a=eval("1.5")
>>> print(a,type(a))
1.5 <class 'float'>
>>> b=eval("25")
>>> print(b,type(b))
25 <class 'int'>
>>> c=eval("1+2j")
>>> print(c,type(c))
(1+2j) <class 'complex'>
>>> d=eval("10+20+30")
>>> print(d)
60
Example:
# write a program to add two numbers
Output
Enter first number 10
Enter second number 20
sum of 10 and 20 is 30
>>> a=10
>>> b=1.5
>>> c=a-b
>>> print(a,b,c)
10 1.5 8.5
>>> c1=1+2j
>>> c2=1j
>>> c3=c1-c2
>>> print(c1,c2,c3)
(1+2j) 1j (1+1j)
>>> c3=c1-2
>>> print(c3)
(-1+2j)
“*” This operator is used to perform two operations
1. Multiplication
2. Repeating Sequence number of times
Example:
>>> n1=5
>>> n2=2
>>> n3=n1*n2
>>> print(n1,n2,n3)
5 2 10
>>> f1=1.5
>>> f2=2.5
>>> f3=f1*f2
>>> print(f1,f2,f3)
1.5 2.5 3.75
>>> r1=5*1.5
>>> print(r1)
7.5
>>> r2=5*True
>>> print(r2)
5
Example:
>>> list1=[0]
>>> list1=list1*10
>>> print(list1)
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
>>> s1="abc"
>>> s2=5*s1
>>> print(s2)
abcabcabcabcabc
>>> print("-"*30)
------------------------------
>>> print(30*"*")
******************************
>>> list2=[5]*20
>>> print(list2)
[5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5]
Example:
# Write a program to find area of rectangle
# area=l*b
Output:
Enter value of l1.2
Enter value of b1.5
area of rectangle with l=1.20 and b=1.50 is 1.80
This operator divide two numbers and return value as float type.
Example:
q1=5/2
print(q1)
2.5
>>> q2=4/2
>>> print(q2)
2.0
>>> q3=4/2.0
>>> print(q3)
2.0
>>> q4=4/0
Traceback (most recent call last):
File "<pyshell#28>", line 1, in <module>
q4=4/0
ZeroDivisionError: division by zero
>>> q5=0/5
>>> print(q5)
0.0
Example:
# Write a program to find simple interest
# si=ptr/100
p=float(input("Amount "))
t=int(input("Time "))
r=float(input("Rate "))
si=p*t*r/100
print(f'''Amount {p}
Time {t}
Rate {r}
Simple Interest {si:.2f}''')
Output:
Amount 5000
Time 12
Rate 1.5
Amount 5000.0
Time 12
Rate 1.5
Simple Interest 900.00
Example:
# Write a program to input rollno,name 3 subject marks
# calculate total and avg marks
rollno=int(input("Rollno "))
name=input("Name ")
sub1=int(input("Subject1 Marks "))
sub2=int(input("Subject2 Marks "))
sub3=int(input("Subject3 Marks "))
total=sub1+sub2+sub3
avg=total/3
print(f'''
Rollno {rollno}\tName {name}
Subject1 {sub1}\tSubject2 {sub2}\tSubject3 {sub3}
Total {total}\tAvg {avg:.2f}''')
Output:
Rollno 1
Name nk
Subject1 Marks 50
Subject2 Marks 70
Subject3 Marks 90
Rollno 1 Name nk
Subject1 50 Subject270 Subject390
Total 210 Avg 70.00
https://www.hackerrank.com/challenges/python-arithmetic-
operators/problem?isFullScreen=true
a=int(input())
b=int(input())
print(a+b)
print(a-b)
print(a*b)
>>> r1=5//2
>>> print(r1)
2
>>> r2=5/2
>>> print(r2)
2.5
>>> r3=5//2.0
>>> print(r3)
2.0
>>> r4=5/2.0
>>> print(r4)
2.5
Example:
# Write a program to delete last digit of number
num=456
print(num)
num=num//10
print(num)
Output:
456
45
% modulo operator
This operator divides two numbers and return remainder
>>> rem1=5%3
>>> print(rem1)
2
>>> rem2=4%2
>>> print(rem2)
0
Example:
# Write a program to read last digit of number
num=456
lastdigit=num%10
print(num)
print(lastdigit)
Output:
456
6
>>> res1=5**2
>>> print(res1)
25
>>> res2=5**0
>>> print(res2)
1
>>> res3=10**-1
>>> print(res3)
0.1
Precedence of operators
Operator Description
(expressions...), Binding or parenthesized expression,
[expressions...], {key: value... list display, dictionary display, set
}, {expressions...} display
x[index], x[index:index], x(ar Subscription, slicing, call, attribute
guments...), x.attribute reference
await x Await expression
** Exponentiation 5
+x, -x, ~x Positive, negative, bitwise NOT
Multiplication, matrix multiplication,
*, @, /, //, %
division, floor division, remainder
Operator Description
+, - Addition and subtraction
<<, >> Shifts
& Bitwise AND
^ Bitwise XOR
| Bitwise OR
in, not in, is, is not, <, <=, >, > Comparisons, including membership
=, !=, == tests and identity tests
not x Boolean NOT
and Boolean AND
or Boolean OR
if – else Conditional expression
lambda Lambda expression
:= Assignment expression
Relational Operators
Relational operators are used for comparing values. An expression
created using relational operators is called Boolean expression.
Boolean expression always returns Boolean value (True/False)
Operators Description
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
== Equal
!= Not equal
Example:
>>> 10>5
True
>>> 20>30
False
>>> 20<30
True
>>>10<5
False
>>>10>=10
True
>>>10>=5
True
>>>10<=10
True
>>> 5<=10
True
>>> 20<=10
False
>>> 10==10
True
>>> 10==20
False
>>> 10!=10
False
>>> 10!=20
True
>>> "A">"B"
False
>>> "B">"A"
True
>>> "a">"A"
True
>>> a=5
>>> 1<=a<=10
True
>>> a=20
>>> 1<=a<=10
False
>>> 5>=1<=10
True
Conditional Operator
Conditional operator is a ternary operator, this operator required 3
operands. Condition operator is used for creating conditional
expression. Conditional operators allow evaluating expression based
on condition/test.
Syntax:
<variable-name>=opr1 if opr2 else opr3
Example:
# Write a program to find a person is elg to vote or not
Output:
Enter Name suresh
Enter Age 30
suresh is elg to vote
Example:
# Write a program to find input number is even or odd
Output:
Enter any number 4
4 is even
Example:
# Write a program to find max of two numbers
Output:
Enter First Number 10
Enter Second Number 5
10 is max
Logical Operators
Logical operators are used to combine two or more conditions or
boolean expressions. In python logical operators are represented
using 3 keywords.
and operator
truth table of and operator
Opr1 Opr2 Opr1 and Opr2
True False False
False True False
False False False
True True True
Example:
>>> True and True
True
>>> True and False
False
>>> False and True
False
>>> False and False
False
>>> 10>5 and 10>20
False
>>> 10>20 and 10>5
False
Example:
# Write a program to read name and 2 subject marks
# calculate total,avg and result
Output:
Enter Name nk
Enter Subject1 Marks 70
Enter Subject2 Marks 80
Name nk
Subject1 70
Subject2 80
Total 150
Avg 75.00
Result pass
Example:
>>> 100 and 200
200
>>> 0 and 100
0
>>>100 and 200 and 300
300
>>>100 and 0 and 300
0
>>> "java" and "python"
'python'
>>> "A" and "B"
'B'
>>> bool(100)
True
>>> bool(0)
False
Example:
# Login Application
Output:
UserName :nk
Password :nit123
invalid username or password
UserName :nit
Password :nk
invalid username or password
>>>
UserName :nit
Password :nit123
Welcome
or operator
truth table
Opr1 Opr2 Opr1 or Opr2
True True True
True False True
False True True
False False False
True or False
True
>>> False or True
True
>>> False or False
False
>>> 100 or 200
100
>>> 100 or 200 or 300
100
Example:
>>> 100 or 200
100
>>> 100 or 200 or 300
100
>>> 100 or 200 and 300
100
>>> 200 and 300 or 100
300
>>> 0 and 100 or 200
200
t.me/fspy5
Using multiple conditional operator
Multiple conditional operators are used to check more than one
condition.
Example:
# Write a program to find input character is vowel or not
Output:
Enter Single Character i
Vowel
Example:
# Write a program to find input number is +ve,-ve or zero
Output:
Enter any number 5
+ve
Example:
# Write a program to find input character is alphabet,digit or special
character
Output:
Enter any character a
alphabet
not operator
not is a unary operator, this operator required 1 operand
truth table of not operator
Opr1 Not Opr1
True False
False True
Example:
>>> not True
False
>>> not False
True
>>> not 100
False
>>> not 0
True
Membership operator
Membership operator is binary operator
This operator required two operands
Membership operator is represented using “in” keyword
1. In
2. Not in
Example
>>> "a" in "java"
True
>>> "python" in "best programming language to learn is python"
True
>>> 10 in [10,20,30,40]
True
>>> 100 in [10,20,30,40]
False
>>> "[email protected]" in ["[email protected]","[email protected]"]
False
>>> 10 not in [10,20,30,40,50]
False
>>> 100 not in [10,20,30,40,50]
True
Example:
# Write a program to find input character is vowel
Output
Enter any character a
vowel
Identity Operator
Identity operator is a binary operator
Identity operator is represented using “is” keyword.
Identity operator is used to compare references or identity of object.
1. is
2. is not
is operator returns True, if two variables pointing to same object
inside memory, else return False
is not operator return True, if two variables are not pointing to same
object inside memory else return False
>>> a=10
>>> b=10
>>> a==b
True
>>> id(a)
140715736550104
>>> id(b)
140715736550104
>>> a is b
True
>>> list1=[10,20,30]
>>> list2=[10,20,30]
>>> list1==list2
True
>>> list1 is list2
False
>>> list3=list1
>>> list1 is list3
True
>>> a=(b=1+5)*(c=5-2)
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of
'='?
>>> a=(b:=1+5)*(c:=5-2)
>>> print(a)
18
>>> print(b)
6
>>> print(c)
3
>>> x:=10
SyntaxError: invalid syntax
>>> x=10
>>> x
10
Bitwise Operators
Bitwise operators are used to perform operation on binary data.
1. Shift operators
a. Left shift operator
b. Right shift operator
2. Bitwise & (and) operator
3. Bitwise | (or) operator
4. Bitwise ^ (XOR) operator
5. Bitwise ~ (NOT) operator
Shift Operators
Shift operators are used to shift or move bits towards left side or right
side.
These operators are used to increment or decrement value by
adding bits or removing bits.
Applications
Memory Management
Encryption and Decryption
>> right shift operator is used to shift number of bits towards right side.
The shifted bits are deleted.
Syntax: value>>n
>>> a=12
>>> b=a>>2
>>> print(a,b)
12 3
>>> print(bin(a),bin(b))
0b1100 0b11
>>> x=25
>>> y=x>>3
>>> print(bin(x),bin(y))
0b11001 0b11
>>> print(x,y)
25 3
>>> b=a>>5
>>> a=20
>>> b=a>>2
>>> print(a)
20
>>> print(b)
5
Left shift operator is used to shift number of bits towards left side. By
shifting number of bits toward left side the value get incremented.
Syntax: value<<n
Formula: value*2 pow n
>>> a=10
>>> print(bin(a))
0b1010
>>> b=a<<1
>>> print(bin(b))
0b10100
>>> print(b)
20
Logical Gates
A logic gate is a device that acts as a building block for
digital circuits. They perform basic logical functions that are
fundamental to digital circuits. Most electronic devices we use today
will have some form of logic gates in them. For example, logic gates
can be used in technologies such as smartphones, tablets or within
memory devices.
.
Bitwise & (and) operator
This operator is used to apply and gate
Truth table of bitwise & (and) operator
Note: bitwise operators are applied only one integer data types.
Example:
>>> a=5
>>> b=4
>>> c=a&b
>>> print(a,b,c)
544
>>> print(bin(a),bin(b),bin(c))
0b101 0b100 0b100
>>> x=0b1010
>>> y=0b1110
>>> z=x&y
>>> print(bin(x),bin(y),bin(z))
0b1010 0b1110 0b1010
>>> print(x,y,z)
10 14 10
>>> x=0b101
>>> y=0b110
>>> z=x|y
>>> print(bin(x),bin(y),bin(z))
0b101 0b110 0b111
>>> a=12
>>> b=20
>>> c=a|b
>>> print(bin(a),bin(b),bin(c))
0b1100 0b10100 0b11100
>>> print(a,b,c)
12 20 28
>>> a and b
20
>>> a=0b101
>>> b=0b100
>>> c=a^b
>>> print(bin(a),bin(b),bin(c))
0b101 0b100 0b1
Bitwise not (~) operator
Bitwise not operator is unary operator, this operator required 1
operand.
Formula –(value+1)
Truth table
Opr1 ~Opr1
1 0
0 1
>>> a=5
>>> b=~a
>>> print(a)
5
>>> print(b)
-6
>>> print(bin(a),bin(b))
0b101 -0b110
>>> a=5
>>> a=a+2
>>> print(a)
7
>>> a+=2
>>> print(a)
9
>>> b=10
>>> b-=1
>>> print(b)
9
>>> c=16
>>> c/=4
>>> print(c)
4.0
>>> a=12
>>> a>>=2
>>> print(a)
3
Command line arguments
The values send to python program from command prompt or
command line is called command line arguments.
The values send from command prompt are stored in one variable
called argv. It is a predefined variable/object exists in sys module.
How to execute program with command line arguments in IDLE?
Control Statements
If statement
if is keyword which represent conditional statement.
Types of if syntax
1. simple if
2. if..else
3. if..elif..else (if..else ladder)
4. nested if
simple if
Syntax:
If <condition>:
Statement-1
Statement-2
Statement-3
Example:
if 10>5:
print("Python")
print("Hello")
if 5>10:
print("Java")
print("Bye")
if 2>10:
print(".Net")
print("Good")
Output:
Python
Hello
Bye
Example:
if 10>5:
pass
print("a")
print("b")
Output:
a
b
pass keyword
The pass statement is used as a placeholder for future code. When
the pass statement is executed, nothing happens, but you avoid
getting an error when empty code is not allowed. Empty code is not
allowed in loops, function definitions, class definitions, or in if
statements.
Example:
if 10>5:
pass
print("Hello")
Output:
Hello
If..else
Syntax:
If <condition>:
Statement-1
Statement-2
else:
Statement-3
Statement-4
Statement-5
Example:
# Write a program to verify input number divisible with 7 or not
Output:
Enter any number 14
14 is divisible with 7
Example:
Output:
Enter any Number 20
Hello
Enter any Number 22
Bye
Home Work
If condition1:
Statement-1
elif condition2:
Statement-2
elif condition3:
Statement-3
…
else:
Statement-n
Output:
Enter any character a
alphabet
https://www.hackerrank.com/challenges/py-if-else/problem?
isFullScreen=true
n=int(input())
if n%2!=0:
print("Weird")
elif n>=2 and n<=5:
print("Not Weird")
elif n>=6 and n<=20:
print("Weird")
elif n>20:
print("Not Weird")
units=int(input("Enter units"))
if units<=100:
amt=0
elif units>100 and units<=200:
amt=(units-100)*5
else:
amt=0+500+(units-200)*10
print(f'Amount {amt}')
p=int(input("Enter Percentage"))
if p>90:
print("A")
elif p>80 and p<=90:
print("B")
elif p>=60 and p<=80:
print("C")
else:
print("D")
cost=int(input("Enter Bike Price :"))
if cost>100000:
tax=cost*15/100
elif cost>50000 and cost<=100000:
tax=cost*10/100
else:
tax=cost*5/100
print(f'Salary {salary}')
print(f'Bonus {bonus}')
Output:
Enter Salary 50000
Enter Service 12
Salary 50000
Bonus 5000.0
Example:
# Write a program to convert input alphabet into uppercase to
lower case,
# lowercase to uppercase
Output:
Enter any character $
input character must be alphabet
Nested if
If condition1:
If condition2:
Statement-1
else:
Statement-2
elif condition3:
if condition4:
Statement-3
Else:
Statement-4
else:
Statement-5
Example:
# Login Application
user=input("UserName ")
if user=="nit":
pwd=input("Password ")
if pwd=="nit123":
print("Welcome")
else:
print("invalid password")
else:
print("invalid username")
Output:
UserName abc
invalid username
UserName nit
Password nit123
Welcome
Example:
# Write program to login with OTP
import random
user=input("UserName ")
otp=random.randint(1000,9999)
print(f'{user} please Login with OTP {otp}')
otp1=int(input("OTP :"))
if otp1==otp:
print(f'{user} welcome')
else:
print("invalid OTP")
Output:
UserName nk
nk please Login with OTP 2602
OTP :2602
nk welcome
UserName suresh
suresh please Login with OTP 9425
OTP :9424
invalid OTP
match statement
match statement
match is selection statement.
match statement execute block of statements based selection of
value.
match is softkeyword in python.
match statement is introduced in python 3.10 version
Syntax:
match(expression/value):
case <pattern>:
statement-1
case <pattern>:
statement-2
case <pattern>:
statement-3
case _:
statement-x
PVM read value and compare with all the cases, if equals to any
case, PVM execute that block and terminates.
If value is not equal to any case, PVM executes default case which is
defined _
Example:
Example:
print("****Menu****")
print("1.Area of Circle")
print("2.Area of Triangle")
print("3.Area of Rectangle")
print("4.Exit")
opt=int(input("Enter Your Option [1-4] "))
match(opt):
case 1:
r=float(input("Enter R Value "))
area=3.147*r*r
print(f'Area of Circle is {area:.2f}')
case 2:
base=float(input("Enter Base Value "))
height=float(input("Enter Height Value "))
area=0.5*base*height
print(f'Area of Triangle {area:.2f}')
case 3:
l=float(input("Enter L Value "))
b=float(input("Enter B Value "))
area=l*b
print(f'Area of Rectangle {area:.2f}')
case 4:
print("Thank You...")
case _:
print("Invalid Option Try again...")
Output:
****Menu****
1.Area of Circle
2.Area of Triangle
3.Area of Rectangle
4.Exit
Enter Your Option [1-4] 2
Enter Base Value 1.2
Enter Height Value 1.5
Area of Triangle 0.90
****Menu****
1.Area of Circle
2.Area of Triangle
3.Area of Rectangle
4.Exit
Enter Your Option [1-4] 1
Enter R Value 1.5
Area of Circle is 7.08
Example:
# Write a program to find input character is vowel or not
Output:
Enter any character e
vowel
while loop
while <condition>:
statement-1
statement-2
i=1
s=0
while i<=5:
value=int(input("Enter Value "))
s=s+value
i=i+1
print(f'Sum is {s}')
Output:
Enter Value 10
Enter Value 40
Enter Value 20
Enter Value 40
Enter Value 50
Sum is 160
Example:
i=0
while i<=5:
print("Hello")
i=i+1
j=1
while j<=5:
print("Bye")
j=j+2
k=1
while k>=5:
print("java")
k=k+1
p=5
while p>=1:
print("Python")
p=p-1
Output:
Hello
Hello
Hello
Hello
Hello
Hello
Bye
Bye
Bye
Python
Python
Python
Python
Python
Full Stack Python (Part-26)
Example:
# Write a program to find length of number or count digits of input
number
Output:
Enter any number 0
Count of digits 1
while num>0:
r=num%10
s=s+r
num=num//10
Output:
Enter any number 123
Sum of digits 6
# Write a program to count how many even and odd digits exists
within input number
while num>0:
r=num%10
if r%2==0:
ecount=ecount+1
else:
ocount=ocount+1
num=num//10
Output:
Enter any number 4893
Even count digits 2
Odd count digits 2
if s==num1:
print(f'{num1} armstrong')
else:
print(f'{num1} is not armstrong')
Output
Enter any number 153
153 armstrong
s=0
i=1
while i<num:
r=num%i
if r==0:
s=s+i
i=i+1
if s==num:
print(f'{num} is perfect number ')
else:
print(f'{num} is not perfect number')
Output:
enter any number 6
6 is perfect number
while num>0:
r=num%10
rev=(rev*10)+r
num=num//10
print(num1)
print(rev)
if rev==num1:
print(f'{num1} is palindrome')
else:
print(f'{num1} is not palindrome')
Output:
Enter any number 123
123
321
123 is not palindrome
HOME WORK
123
489
for loop
Syntax:
for variable-name in iterable:
statement-1
statement-2
for loop each time read one value from iterable and assign to a
variable; After assigning to variable, it execute block of statements.
Statement-1, statement-2 is executed until read all the values from
iterable.
Example:
str1="java"
for ch in str1:
print(ch)
Output:
j
a
v
a
Example:
# Write a program to find length of string
Output:
Enter any string python
Length of string 6
ac=0
dc=0
sc=0
for ch in str1:
if ch>='a' and ch<='z' or ch>='A' and ch<='Z':
ac=ac+1
elif ch>='0' and ch<='9':
dc=dc+1
else:
sc=sc+1
Output:
Enter any string ab12$%c@34A
Alphabet Count 4
Digit Count 4
Special Character Count 3
range data type
range is an immutable sequence data type.
This data type is used to generate sequence of integer values.
Example:
r1=range(10) # creating range object start=0,stop=10,step=1 0 1 2 3
456789
for a in r1:
print(a,end=' ')
print("\n-----------------------")
for b in range(5): # start=0,stop=5,step=1 --> 0 1 2 3 4
print(b,end=' ')
print("\n-------------------------")
for c in range(-5): # start=0,stop=-5,step=1
print(c,end=' ')
Output:
0123456789
-----------------------
01234
-------------------------
Syntax2: range(start,stop,[step])
This syntax is used to generate sequence of integers in increment or
decrement order.
If step value is not given it default to +1
Example:
for a in range(1,11): # start=1,stop=11,step=1 --> 1 2 3 4 5 6 7 8 9 10
print(a,end=' ')
print()
for b in range(1,11,2): # start=1,stop=11,step=2 --> 1 3 5 7 9
print(b,end=' ')
print()
for c in range(2,20,2): # start=2,stop=20,step=2 --> 2 4 6 8 10 12 14 16
18
print(c,end=' ')
print()
for d in range(10,0,-1): # start=10,stop=0,step=-1 --> 10 9 8 7 6 5 4 3 2 1
print(d,end=' ')
print()
for e in range(-1,-11,-1): # start=-1,stop=-11,step=-1
print(e,end=' ')
print()
for f in range(-10,0,1): # start=-10,stop=0,step=1
print(f,end=' ')
print()
for g in range(-5,6): # start=-5,stop=6,step=1
print(g,end=' ')
print()
for h in range(5,-6,-1): # start=5,stop=-6,step=-1
print(h,end=' ')
print()
Output:
1 2 3 4 5 6 7 8 9 10
13579
2 4 6 8 10 12 14 16 18
10 9 8 7 6 5 4 3 2 1
-1 -2 -3 -4 -5 -6 -7 -8 -9 -10
-10 -9 -8 -7 -6 -5 -4 -3 -2 -1
-5 -4 -3 -2 -1 0 1 2 3 4 5
5 4 3 2 1 0 -1 -2 -3 -4 -5
Example:
# Write a program to generate math table of input number
#5
# 5x1=5
# 5x2=10
# ...
# 5x10=50
for i in range(1,11): # 1 2 3 4 5 6 7 8 9 10
p=num*i
print(f'{num}x{i}={p}')
Output:
Enter any number 7
7x1=7
7x2=14
7x3=21
7x4=28
7x5=35
7x6=42
7x7=49
7x8=56
7x9=63
7x10=70
Nested Looping Statements
1. Nested for
2. Nested while
Syntax:
Example:
# Write a program to generate tables from 1 to 5
Output:
1x1=1
1x2=2
1x3=3
1x4=4
1x5=5
1x6=6
1x7=7
1x8=8
1x9=9
1x10=10
2x1=2
2x2=4
2x3=6
2x4=8
2x5=10
2x6=12
2x7=14
2x8=16
2x9=18
2x10=20
3x1=3
3x2=6
3x3=9
3x4=12
3x5=15
3x6=18
3x7=21
3x8=24
3x9=27
3x10=30
4x1=4
4x2=8
4x3=12
4x4=16
4x5=20
4x6=24
4x7=28
4x8=32
4x9=36
4x10=40
5x1=5
5x2=10
5x3=15
5x4=20
5x5=25
5x6=30
5x7=35
5x8=40
5x9=45
5x10=50
Example:
# write a program to generate factorials of all numbers from 1-5
# 1 --> 1
# 2 --> 2
# 3 --> 6
# 4 --> 24
# 5 --> 120
Output:
Factorial of 1-->1
Factorial of 2-->2
Factorial of 3-->6
Factorial of 4-->24
Factorial of 5-->120
Example:
# write a program to print prime numbers from 2 to 20
Output:
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
Example:
for j in range(1,6):
for i in range(1,6):
print(1,end=' ')
print()
for j in range(1,6):
for i in range(1,6): # 1 2 3 4 5
print(i,end=' ')
print()
Output:
11111
11111
11111
11111
11111
12345
12345
12345
12345
12345
Example:
# Write a program to generate the following series
# 1 4 9 16 25 36 ... n**2
Output:
enter value of n5
1-->1
2-->4
3-->9
4-->16
5-->25
Example:
# write a program to generate even numbers between m,n
Output:
enter value of m5
enter value of n20
6
8
10
12
14
16
18
20
Example:
# Write a program to genreate ascii table for uppercase letter
# A --> 65
# B ---> 66
# C ---> 67
# Z --> 90
Output:
A-->65
B-->66
C-->67
D-->68
E-->69
F-->70
G-->71
Example:
# Write a program to find input number is prime or not
if c==2:
print(f'{num} is prime')
else:
print(f'{num} is not prime')
Output:
Enter any number 4
4 is not prime
Output:
20
18
16
14
12
10
8
6
4
2
s=0
for i in range(10):
num=int(input("Enter any number "))
s=s+num
avg=s/10
print(f'Avg is {avg:.2f}')
Output:
Enter any number 10
Enter any number 20
Enter any number 30
Enter any number 40
Enter any number 50
Enter any number 60
Enter any number 70
Enter any number 80
Enter any number 90
Enter any number 100
Avg is 55.00
Example:
# Accept 10 numbers from user and find maximum and minimum
value
max_value=0
min_value=0
for i in range(10):
num=int(input("Enter any number "))
if i==0:
max_value=num
min_value=num
else:
if num>max_value:
max_value=num
elif num<min_value:
min_value=num
Output:
Enter any number 1
Enter any number 7
Enter any number 3
Enter any number 9
Enter any number 2
Enter any number 5
Enter any number 4
Enter any number 77
Enter any number 1
Enter any number 0
Minimum Value 0
Maximum Value 77
even_sum=0
odd_sum=0
for num in range(12,38):
if num%2==0:
even_sum+=num
else:
odd_sum+=num
Output:
Output:
121
143
165
187
209
231
253
275
297
319
341
363
385
407
429
451
473
495
Example:
spaces=4
for r in range(1,6):
for s in range(spaces):
print(" ",end='')
for c in range(1,r+1):
print("* ",end='')
print()
spaces=spaces-1
spaces=0
for r in range(5,0,-1):
for s in range(spaces):
print(" ",end='')
for c in range(1,r+1):
print("* ",end='')
print()
spaces=spaces+1
Output:
Nested while loop
While loop inside while loop is called nested while loop.
Syntax:
while <condition>: 🡪 Outer looping statement
statement-1
statement-2
while <condition>: 🡪 Inner looping statement
statement-3
statement-4
Example:
# using while loop generate numbers from 1 to 10
num=1
while num<=10:
print(num,end=' ')
num=num+1
Output:
1 2 3 4 5 6 7 8 9 10
Example:
# Write a program to generate the following output
#1 2 3 4 5 6 7 8 9 10
#2 4 6 8 10 12 14 16 18 20
# 3 6 9 12 15 18 21 24 27 30
#....
# 10 20 30 40 50 60 70 80 90 100
n=1
while n<=10: # Outer loop
i=1
while i<=10: # inner loop
print(n*i,end=' ')
i=i+1
print()
n=n+1
Output:
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100
Example:
a=int(input("enter starting value "))
b=int(input("enter ending value "))
while a<=b:
i=1
s=0
while i<a:
if a%i==0:
s=s+i
i=i+1
if s==a:
print(a)
a=a+1
Output:
enter starting value 6
enter ending value 500
6
28
496
break
break is branching statement or passes control statement.
break is a keyword.
break statement is used inside looping statements (while, for).
This statement is used to terminate execution of while or for
unconditionally or in between.
Example:
for num in range(1,11):
print("Hello")
break
num=1
while num<=10:
print("Bye")
num=num+1
break
Output:
Hello
Bye
Example:
# write a program to find input number is prime or not
if c==2:
print(f'{num} is prime')
else:
print(f'{num} is not prime')
Output:
Enter any number 6
Hello
Hello
Hello
6 is not prime
Example of Login app
while True:
user=input("UserName :")
pwd=input("Password :")
if user=="nit" and pwd=="nit123":
print("Welcome")
break
else:
print("invalid username or password pls try again...")
Output:
UserName :nit
Password :abc
invalid username or password pls try again...
UserName :abc
Password :nit123
invalid username or password pls try again...
UserName :nit
Password :nit123
Welcome
Example:
# Write a program to generate first 10 prime numbers
num=2
prime_count=0
while True:
c=0
for i in range(1,num+1):
if num%i==0:
c=c+1
if c>2:
break
if c==2:
print(num)
prime_count=prime_count+1
if prime_count==10:
break
num=num+1
Output:
2
3
5
7
11
13
17
19
23
29
continue
Output:
1
3
5
7
9
Full Stack Python (Part-33)
Example:
n=1
while n<=5:
print(n)
n=n+1
else:
print("inside else block")
n=1
while n<=5:
print(n)
break
else:
print("Inside else block")
Output:
1
2
3
4
5
inside else block
1
Example:
for num in range(1,6): # 1 2 3 4 5
print(num)
else:
print("inside else block")
Output:
1
2
3
4
5
inside else block
1
Sequences
Sequences are ordered collections, where objects are organized in
sequential order (OR) insertion order is preserved.
Properties of sequences
1. Index based
2. Allows duplicates
3. Slicing
4. Homogenous or Heterogeneous
Example:
>>> 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(list3)
[10, 20, 30, 40, 50]
>>> print(type(list3))
<class 'list'>
>>> sales=[10000,20000,30000,40000,50000]
>>> stud=[1,"Nk","python",6000.0]
>>> print(sales)
[10000, 20000, 30000, 40000, 50000]
>>> print(stud)
[1, 'Nk', 'python', 6000.0]
Example:
>>> list4=list()
>>> print(list4)
[]
>>> print(type(list4))
<class 'list'>
>>> list5=list(range(1,6))
>>> print(list5)
[1, 2, 3, 4, 5]
>>> list6=list(range(10,110,10))
>>> print(list6)
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
>>> list7=list("PYTHON")
>>> print(list7)
['P', 'Y', 'T', 'H', 'O', 'N']
>>> list8=list("NIT")
>>> print(list8)
['N', 'I', 'T']
>>> list9=list([10,20,30])
>>> list10=list(list9)
>>> print(list9)
[10, 20, 30]
>>> print(list10)
[10, 20, 30]
index
What is index?
Index is an integer value.
Each element/item in list/sequence identified with index.
Index is element position OR each location in list/sequence is
identified with integer value called index.
Index is used to read elements from sequence in sequentially or
randomly.
Index values are two types
1. +ve Index
2. –ve index
+ve index start at 0, which is used to read items left to right (forward
direction)
-ve index start at -1, which is used to read items in right to left
(backward direction)
Syntax: list-name[index]
Example
>>> L=[10,20,30,40,50]
>>> print(L)
[10, 20, 30, 40, 50]
>>> L[0]
10
>>> L[-1]
50
>>> L[2]
30
>>> L[-2]
40
>>> L[5]
Traceback (most recent call last):
File "<pyshell#39>", line 1, in <module>
L[5]
IndexError: list index out of range
>>> L[-5]
10
Full Stack Python (Part-34)
Example:
>>> list1=[10,20,30,40,50]
>>> print(list1)
[10, 20, 30, 40, 50]
>>> print(len(list1))
5
Example:
Displaying +ve and –ve values from list
list1=[1,2,-4,5,-6,6,7,8,9,-10,-12,11,-14,-13]
print(list1)
a=len(list1)
print("Reading -Ve Values from List")
for i in range(a): # start=0,stop=10,step=1 0 1 2 3 4 5 6 7 8 9
if list1[i]<0:
print(list1[i],end=' ')
print()
print("Reading +Ve values from List")
for i in range(a):
if list1[i]>=0:
print(list1[i],end=' ')
Output:
[1, 2, -4, 5, -6, 6, 7, 8, 9, -10, -12, 11, -14, -13]
Reading -Ve Values from List
-4 -6 -10 -12 -14 -13
Reading +Ve values from List
1 2 5 6 7 8 9 11
Example:
# Count of even and odd number of list
list1=[4,8,9,1,2,3,4,12,15,17,19,24,35,76,77,45,54,34,21]
print(list1)
a=len(list1)
ecount,ocount=0,0
for i in range(a): # start=0,stop=15,step=1 0 1 2 3 4 5 6 7 8 9 ... 14
if list1[i]%2==0:
ecount+=1
else:
ocount+=1
Output:
[4, 8, 9, 1, 2, 3, 4, 12, 15, 17, 19, 24, 35, 76, 77, 45, 54, 34, 21]
Even number count 9
Odd number count 10
Example:
list1=[1,2,-4,5,-6,6,7,8,9,-10,-12,11,-14,-13]
a=len(list1)
for i in range(-1,-(a+1),-1): # start=-1,stop=-15,step=-1 -1 -2 -3 -4 -5 ... -
14
print(list1[i],end=' ')
print()
for i in range(a): # start=0,stop=14,step=1
print(list1[i],end='')
Output:
-13 -14 11 -12 -10 9 8 7 6 -6 5 -4 2 1
12-45-66789-10-1211-14-13
Example:
# Write a program to add all the values of list
list1=list(range(10,110,10))
print(list1)
a=len(list1)
total=0
for i in range(a):# start=0,stop=10,step=1 0123456789
total=total+list1[i]
print(f'Total is {total}')
print(f'Avg is {total/a}')
Output:
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
Total is 550
Avg is 55.0
Example:
# Python program to find smallest number in a list
scores=[50,30,20,10,50,60]
a=len(scores)
print(scores)
print(f'Minimum Score {min_score}')
Sort
sort(*, key=None, reverse=False)
This method sorts the list in place. It is a mutable method of list.
Reverse argument:
Default value of reverse is False, which mean it sort in
ascending order
If reserve value is given True, it sort elements in descending
order
Key is a function which is applied to each element.
Example:
>>> list1=[4,5,1,8,3,9,2,7,11,66,12,15,10]
>>> print(list1)
[4, 5, 1, 8, 3, 9, 2, 7, 11, 66, 12, 15, 10]
>>> list1.sort()
>>> print(list1)
[1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 15, 66]
>>> list1.sort(reverse=True)
>>> print(list1)
[66, 15, 12, 11, 10, 9, 8, 7, 5, 4, 3, 2, 1]
>>> list1=["d","a","B","c","A","D","C","b"]
>>> print(list1)
['d', 'a', 'B', 'c', 'A', 'D', 'C', 'b']
>>> list1.sort()
>>> print(list1)
['A', 'B', 'C', 'D', 'a', 'b', 'c', 'd']
>>> list1.sort(key=str.upper)
>>> print(list1)
['A', 'a', 'B', 'b', 'C', 'c', 'D', 'd']
>>> list1.sort(key=str.upper,reverse=True)
>>> print(list1)
['D', 'd', 'C', 'c', 'B', 'b', 'A', 'a']
count(value)
This method return count of given value inside iterable.
>>> list1=[1,2,3,4,1,2,3,1,2,3,5,6,7]
>>> list1.count(1)
3
>>> list1.count(5)
1
>>> list1.count(3)
3
Example:
# finding second maximum
list1=[4,8,1,9,1,2,3,4,12,15,17,19,24,35,76,77,45,54,34,21,77]
print(list1)
list1.sort()
print(list1)
fmax=list1[-1]
k=list1.count(fmax)
smax=list1[-(k+1)]
print(fmax)
print(smax)
fmin=list1[0]
k=list1.count(fmin)
smin=list1[k]
print(fmin)
print(smin)
Output:
[4, 8, 1, 9, 1, 2, 3, 4, 12, 15, 17, 19, 24, 35, 76, 77, 45, 54, 34, 21, 77]
[1, 1, 2, 3, 4, 4, 8, 9, 12, 15, 17, 19, 21, 24, 34, 35, 45, 54, 76, 77, 77]
77
76
1
2
Slicing
“Slicing” means getting a subset of elements from an
iterable/sequence based on their indices.
Slicing allows reading more than one value from sequences.
Slice operator
Syntax: sequence-name[start:stop:step]
Example:
>>> list1=[10,20,30,40,50]
>>> print(list1)
[10, 20, 30, 40, 50]
>>> list2=list1[::]
>>> print(list2)
[10, 20, 30, 40, 50]
>>> list3=list1[:]
>>> print(list3)
[10, 20, 30, 40, 50]
Syntax2: sequence-name[::step]
In this syntax start and stop values are generated based on step
value.
If step=+ve, start=0,stop=len(sequence)
If step=-ve, start=-1,stop=-(len(sequence)+1)
Example:
>>> list1=list(range(10,110,10))
print(list1)
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
>>> list2=list1[::1]
>>> print(list2)
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
>>> list3=list1[::2]
>>> print(list3)
[10, 30, 50, 70, 90]
>>> list4=list1[::-1]
>>> print(list4)
[100, 90, 80, 70, 60, 50, 40, 30, 20, 10]
>>> list5=list1[::-2]
>>> print(list5)
[100, 80, 60, 40, 20]
>>> list1=list(range(10,110,10))
>>> print(list1)
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
>>> list2=list1[5:]
>>> print(list2)
[60, 70, 80, 90, 100]
>>> list3=list1[-5:]
>>> print(list3)
[60, 70, 80, 90, 100]
Syntax4: sequence-name[:stop:] or sequence-name[:stop]
This syntax read values from left to right
Default start=0,step=1
>>> list1=list(range(10,110,10))
>>> print(list1)
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
>>> list2=list1[:5:]
>>> print(list2)
[10, 20, 30, 40, 50]
>>> list3=list1[:-5:]
>>> print(list3)
[10, 20, 30, 40, 50]
>>> list4=list1[:-3:]
>>> print(list4)
[10, 20, 30, 40, 50, 60, 70]
>>> list5=list1[:-8:]
>>> print(list5)
[10, 20]
Syntax5: sequence-name[start:stop:]
This syntax read values from left to right
Defaults step is +1
>>> list1=list(range(10,110,10))
>>> print(list1)
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
>>> list2=list1[0:5]
>>> print(list2)
[10, 20, 30, 40, 50]
>>> list3=list1[-5:-3]
>>> print(list3)
[60, 70]
>>> list4=list1[-3:-6]
>>> print(list4)
[]
>>> list5=list1[3:-3]
>>> print(list5)
[40, 50, 60, 70]
Syntax-6: sequence-name[start:stop:step]
>>> list1=list(range(10,110,10))
>>> print(list1)
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
>>> list2=list1[2:8:2]
>>> print(list2)
[30, 50, 70]
>>> list3=list1[-2:-8:-2]
>>> print(list3)
[90, 70, 50]
Syntax:
for variable in iterable:
statement-1
statement2
Example:
>>> list1=[10,20,30,40,50]
>>> for a in list1:
print(a)
10
20
30
40
50
>>> for i in range(len(list1)):
... print(list1[i])
10
20
30
40
50
Full Stack Python (Part-36)
# Find Median
list1=[1,2,3,4,5]
a=len(list1)
if a%2!=0:
mid=len(list1)//2
print(f"Median {list1[mid]}")
else:
mid=len(list1)//2
print(f"Median {(list1[mid]+list1[mid-1])/2}")
# Find Output
list1=[10,20,30,40,50]
for x in list1[::-1]: # [50,40,30,20,10]
print(x,end=' ')
print()
# Find Output
list1=[10,20,30,40,50,60,70,80,90,100]
for x in list1[-5:]: # [60,70,80,90,100]
print(x,end=' ')
print()
for x in list1[:-5]: # [10,20,30,40,50]
print(x,end=' ')
print()
for x in list1[3:-3]: # [40,50,60,70]
print(x,end=' ')
print()
for x in list1[0]: # Error 10
print(x,end=' ')
Output:
Sum of [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] is 550
Maximum value of [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] is 100
Median 3
Length of [1, 2, 3, 4, 5, 6, 7, 8] is 8
50 40 30 20 10
60 70 80 90 100
10 20 30 40 50
40 50 60 70
Traceback (most recent call last):
File "E:/student drive/FSP7PM/test120.py", line 53, in <module>
for x in list1[0]: # Error 10
TypeError: 'int' object is not iterable
Iterator object
iter(iterable) this function receives iterable object and return iterator
object. This iterator object is used to read values from iterables.
__next__() this method read and return next value from iterable.
Example:
names_list=["naresh","ramesh","suresh","kishore"]
a=iter(names_list)
n1=a.__next__()
print(n1)
for n in a:
print(n,end=' ')
Output:
naresh
ramesh suresh kishore
Example:
>>> list1=[10,20,30,40,50]
>>> a=iter(list1)
>>> print(list1)
[10, 20, 30, 40, 50]
>>> list2=list(a)
>>> print(list2)
[10, 20, 30, 40, 50]
>>> list3=list(range(10,110,10))
>>> print(list3)
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
>>> list4=list("abc")
>>> print(list4)
['a', 'b', 'c']
enumerate object
enumerate(iterable,start=0), this function returns enumerate object.
Enumerate is also iterator object, which iterate value and count.
Example:
sales=[10000,20000,30000,40000,5000]
e=enumerate(sales,1999)
for x in e:
print(x)
names_list=["naresh","suresh","ramesh"]
a=enumerate(names_list,1)
for stud in a:
print(stud)
Output:
(1999, 10000)
(2000, 20000)
(2001, 30000)
(2002, 40000)
(2003, 5000)
(1, 'naresh')
(2, 'suresh')
(3, 'ramesh')
1. append(element/value)
This method add element/value at the end of list
Syntax: list-name.append(value)
Example:
>>> list1=[]
>>> print(list1)
[]
>>> list1.append(10)
>>> list1.append(20)
>>> list1.append(30)
>>> print(list1)
[10, 20, 30]
>>> list1.append(40)
>>> print(list1)
[10, 20, 30, 40]
Example:
# Write a program to append 5 values in list
print(list1)
Output:
Input integer value 10
Input integer value 20
Input integer value 30
Input integer value 40
Input integer value 50
[10, 20, 30, 40, 50]
Example:
# Write a program read scores of n players and display
scores=[]
for i in range(n):
s=int(input("Enter Score "))
scores.append(s)
print(f'Scores {scores}')
print(f'Maximum Score {max(scores)}')
print(f'Minimum Score {min(scores)}')
print(f'Total Score {sum(scores)}')
Output:
How many players?4
Enter Score 10
Enter Score 50
Enter Score 20
Enter Score 40
Scores [10, 50, 20, 40]
Maximum Score 50
Minimum Score 10
Total Score 120
Example:
# Write a program to filter data
num_list=[2,8,1,2,9,5,11,15,17,18,21,89,34,56,87,23,32,37,87,56,45,34,23,
12]
even_list=[]
odd_list=[]
Output:
Number List [2, 8, 1, 2, 9, 5, 11, 15, 17, 18, 21, 89, 34, 56, 87, 23, 32, 37,
87, 56, 45, 34, 23, 12]
Even numbers List [2, 8, 2, 18, 34, 56, 32, 56, 34, 12]
Odd numbers List [1, 9, 5, 11, 15, 17, 21, 89, 87, 23, 37, 87, 45, 23]
Example:
>>> list1=[]
>>> list1.append(10,20)
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
list1.append(10,20)
TypeError: list.append() takes exactly one argument (2 given)
Syntax: list-name[len(list):]=iterable
Example:
>>> list1=[10,20,30]
>>> print(list1)
[10, 20, 30]
>> list1[3:]=40,50
>>> print(list1)
[10, 20, 30, 40, 50]
>>> list1[5:]=100,200,300
>>> print(list1)
[10, 20, 30, 40, 50, 100, 200, 300]
>>> list1[len(list1):]="NIT"
>>> print(list1)
[10, 20, 30, 40, 50, 100, 200, 300, 'N', 'I', 'T']
>>> list1[len(list1):]=[1,2,3,4,5]
>>> print(list1)
[10, 20, 30, 40, 50, 100, 200, 300, 'N', 'I', 'T', 1, 2, 3, 4, 5]
>>> list1[len(list1):]=range(-1,-6,-1)
>>> print(list1)
[10, 20, 30, 40, 50, 100, 200, 300, 'N', 'I', 'T', 1, 2, 3, 4, 5, -1, -2, -3, -4, -5]
Syntax1: list-name[index]=value
Syntax2: list-name[startindex:stopindex:step]=iterable
Example:
>>> list1=[10,20,30,40,50]
>>> print(list1)
[10, 20, 30, 40, 50]
>>> list1[0]=99
print(list1)
>>> [99, 20, 30, 40, 50]
>>> list1[-1]=88
>>> print(list1)
[99, 20, 30, 40, 88]
>>> list1[2]=44
>>> print(list1)
[99, 20, 44, 40, 88]
>>> list1[5]=66
Traceback (most recent call last):
File "<pyshell#30>", line 1, in <module>
list1[5]=66
IndexError: list assignment index out of range
>>> list1[-5]=10
>>> print(list1)
[10, 20, 44, 40, 88]
>>> list1[-6]=100
Traceback (most recent call last):
File "<pyshell#33>", line 1, in <module>
list1[-6]=100
IndexError: list assignment index out of range
Example:
# Python program to interchange first and last elements in a list
# Input : [12, 35, 9, 56, 24]
# Output : [24, 35, 9, 56, 12]
# 1st approch
x=list1[0]
list1[0]=list1[-1]
list1[-1]=x
# 2nd approch
list1[0],list1[-1]=list1[-1],list1[0]
print(f'After Swaping {list1}')
Output:
After Swaping [24, 35, 9, 56, 12]
After Swaping [12, 35, 9, 56, 24]
Replacing more than one value
Example:
>>> list1=[10,20,30,40,50]
>>> print(list1)
[10, 20, 30, 40, 50]
>>> list1[:2]=99,88
>>> print(list1)
[99, 88, 30, 40, 50]
>>> list1[2:]=1,2
>>> print(list1)
[99, 88, 1, 2]
>>> list1[2:]=1,2,3
>>> print(list1)
[99, 88, 1, 2, 3]
>>> list1[2:]=10,20,30,40,50,60,70,80,90,100
>>> print(list1)
[99, 88, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
>>> list1[3:6]=11,22,33
>>> print(list1)
[99, 88, 10, 11, 22, 33, 50, 60, 70, 80, 90, 100]
>>> list1[-10::-1]=[1,2,3,4,5]
Traceback (most recent call last):
File "<pyshell#46>", line 1, in <module>
list1[-10::-1]=[1,2,3,4,5]
ValueError: attempt to assign sequence of size 5 to extended slice of
size 3
>>> list1[-1:-4:-1]=1,2,3
>>> print(list1)
[99, 88, 10, 11, 22, 33, 50, 60, 70, 3, 2, 1]
Example:
# Given a list in Python and provided the positions of the elements,
write a program to swap the two elements in the list.
# Examples:
# Input : List = [23, 65, 19, 90], pos1 = 1, pos2 = 3
# Output : [19, 65, 23, 90]
# Input : List = [1, 2, 3, 4, 5], pos1 = 2, pos2 = 5
# Output : [1, 5, 3, 4, 2]
list1=[]
n=int(input("How many values ?"))
for i in range(n):
value=int(input("Enter any value "))
list1.append(value)
Output:
How many values ?5
Enter any value 10
Enter any value 20
Enter any value 30
Enter any value 40
Enter any value 50
Before Swaping [10, 20, 30, 40, 50]
Enter Pos1 1
Enter Pos2 2
After Swaping [20, 10, 30, 40, 50]
Example:
# Reverse list in place
list1=[10,20,30,40,50]
print(list1)
list1[::]=list1[::-1] # [50,40,30,20,10]
print(list1)
list1=[10,20,30,40,50]
print(list1)
list1[:3]=list1[:-4:-1] # [50,40,30]
print(list1)
Output:
[10, 20, 30, 40, 50]
[50, 40, 30, 20, 10]
[10, 20, 30, 40, 50]
[50, 40, 30, 40, 50]
Example:
list1=[10,20,30,40,50]
i=0
for list1[i] in list1[::-1]:
i=i+1
print(list1)
list1=[10,20,30,40,50]
list2=[60,70,80,90,100]
list1[:3]=list2[:3]
print(list1)
Output
[50, 40, 30, 20, 10]
[60, 70, 80, 40, 50]
Example:
# Sorting list values using Bubble Sort
for i in range(n):
for j in range(0,n-1): # 0 1 2 3
if list1[j]>list1[j+1]:
temp=list1[j]
list1[j]=list1[j+1]
list1[j+1]=temp
Output:
Enter how many values ?5
Enter value 5
Enter value 1
Enter value 3
Enter value 2
Enter value 4
before sorting values [5, 1, 3, 2, 4]
After sorting [1, 2, 3, 4, 5]
How to delete or remove values/elements from list?
For deleting elements or values from list, python provides the
following approaches.
del keyword
“del” keyword is used to delete one or more than one value from list.
Del keyword required,
1. Index for deleting one value/element
2. Slicing for deleting more than one value/element
Syntax1: list-name[index]
Syntax2: list-name[start-index:stop-index:step]
Example:
>>> list1=[10,20,30,40,50]
>>> print(list1)
[10, 20, 30, 40, 50]
>>> del list1[0]
>>> print(list1)
[20, 30, 40, 50]
>>> del list1[-2]
>>> print(list1)
[20, 30, 50]
>>> del list1[3]
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
del list1[3]
IndexError: list assignment index out of range
index (ele,start,stop)
This return index of given element/value.
By defining start and stop value, it will search in slice notation.
>>> list1=[10,20,30,40,50,60,70]
>>> a=list1.index(40)
>>> print(a)
3
>>> a=list1.index(100)
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
a=list1.index(100)
ValueError: 100 is not in list
>>> list2=[10,20,30,40,50,10,20,30,40,50,10,20,30,40,50]
>>> a=list2.index(10,-10)
>>> print(a)
5
Example:
# Write a program to read n values into list
# remove given value from list
list1=[]
n=int(input("Enter how many values?"))
for i in range(n):
value=int(input("Enter value"))
list1.append(value)
Example:
# Write a program to read n values into list
# remove given value from list
list1=[]
n=int(input("Enter how many values?"))
for i in range(n):
value=int(input("Enter value"))
list1.append(value)
if found==True:
print(f'After deleting values {list1}')
else:
print(f'{value} not exists in list')
Output:
Enter how many values?5
Enter value10
Enter value10
Enter value20
Enter value30
Enter value20
Before deleting values [10, 10, 20, 30, 20]
Enter value to delete 10
After deleting values [20, 30, 20]
>>> list1=list(range(10,110,10))
>>> print(list1)
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
>>> del list1[0:3]
>>> print(list1)
[40, 50, 60, 70, 80, 90, 100]
>>> del list1[-3:]
>>> print(list1)
[40, 50, 60, 70]
>>> del list1[1:-1]
>>> print(list1)
[40, 70]
>>> list2=list(range(10,110,10))
>>> print(list2)
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
>>> del list2[::2]
>>> print(list2)
[20, 40, 60, 80, 100]
>>> list3=list(range(10,110,10))
>>> print(list3)
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
>>> del list3[::-2]
>>> print(list3)
[10, 30, 50, 70, 90]
Example:
>>> list1=[10,20,30,40,50,60,70,80,90,100]
>>> print(list1)
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
>>> list1.remove(10)
>>> print(list1)
[20, 30, 40, 50, 60, 70, 80, 90, 100]
>>> list1.remove(90)
>>> print(list1)
[20, 30, 40, 50, 60, 70, 80, 100]
>>> list1.remove(10)
Traceback (most recent call last):
File "<pyshell#47>", line 1, in <module>
list1.remove(10)
ValueError: list.remove(x): x not in list
>>> list1=[10,10,10,20,20]
>>> list1.remove(10)
>>> print(list1)
[10, 10, 20, 20]
list1=[4,9,2,3,5,1,11,13,17,23,8,12,16,18,20,22]
Output:
Before Deleting values [4, 9, 2, 3, 5, 1, 11, 13, 17, 23, 8, 12, 16, 18, 20,
22]
After Deleting values [9, 3, 5, 1, 11, 13, 17, 23]
clear()
Empty the list or remove all the values or elements from list
Example:
>>> list1=list(range(10,110,10))
>>> print(list1)
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
>>> list1.clear()
>>> print(list1)
[]
>>> list1=list(range(10,110,10))
>>> print(list1)
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
>>> del list1[:]
>>> print(list1)
[]
pop()
pop()
list can be used as a data structure called stack.
Stack is data structure which follows LIFO (Last In First Out). The
element/value added last is removed first.
Stack allows two operations
1. Push
2. Pop
Push is operation of adding/appending element
Pop is operation of removing and returning element
Example:
>>> list1=[]
>>> list1.append(10)
>>> list1.append(20)
>>> list1.append(30)
>>> print(list1)
[10, 20, 30]
>>> list1.pop()
30
>>> print(list1)
[10, 20]
>>> list1.pop()
20
>>> print(list1)
[10]
>>> list1.pop()
10
>>> print(list1)
[]
list1.pop()
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
list1.pop()
IndexError: pop from empty list
>>> undo=[]
>>> undo.append("format")
>>> undo.append("inserting image")
>>> undo.append("inserting table")
>>> print(undo)
['format', 'inserting image', 'inserting table']
>>> undo.pop()
'inserting table'
>>> print(undo)
['format', 'inserting image']
>>> undo.pop()
'inserting image'
>>> print(undo)
['format']
>>> undo.pop()
'format'
>>> print(undo)
[]
>>> list1=[10,20,30,40,50]
>>> print(list1)
[10, 20, 30, 40, 50]
>>> list1.pop(2)
30
>>> print(list1)
[10, 20, 40, 50]
Output:
1. Adding
2. Removing
3. Display
4. Exit
Enter your option 1
Enter any value10
10 added inside Q
Example:
>>> list1=[]
>>> list1.append(10)
>>> print(list1)
[10]
>>> list1.append(20,30)
Traceback (most recent call last):
File "<pyshell#30>", line 1, in <module>
>>> list1.append(20,30)
TypeError: list.append() takes exactly one argument (2 given)
>>> list1.extend((20,30))
>>> print(list1)
[10, 20, 30]
>>> list1.extend([40,50,60])
>>> print(list1)
[10, 20, 30, 40, 50, 60]
>>> list1.extend("NIT")
>>> print(list1)
[10, 20, 30, 40, 50, 60, 'N', 'I', 'T']
Example:
>>> list1=[10,20,30]
>>> print(list1)
[10, 20, 30]
>>> list1.insert(1,99)
>>> print(list1)
[10, 99, 20, 30]
>>> list1.insert(0,88)
>>> print(list1)
[88, 10, 99, 20, 30]
>>> list1.insert(-1,77)
>>> print(list1)
[88, 10, 99, 20, 77, 30]
>>> list1.insert(9,44)
>>> print(list1)
[88, 10, 99, 20, 77, 30, 44]
>>> list1.insert(-9,33)
>>> print(list1)
[33, 88, 10, 99, 20, 77, 30, 44]
>>> list1.insert(0,100,200)
Traceback (most recent call last):
File "<pyshell#49>", line 1, in <module>
list1.insert(0,100,200)
TypeError: insert expected 2 arguments, got 3
>>> list2=[10,20,30]
>>> print(list2)
[10, 20, 30]
>>> list2[2:2]=[40,50,60]
>>> print(list2)
[10, 20, 40, 50, 60, 30]
>>> list2[1:1]=[11,22,33,44,55]
>>> print(list2)
[10, 11, 22, 33, 44, 55, 20, 40, 50, 60, 30]
>>> list1=[10,20,30,40,50]
>>> print(list1)
[10, 20, 30, 40, 50]
>>> list1.reverse()
>>> print(list1)
[50, 40, 30, 20, 10]
>>> list2=[10,20,30,40,50]
>>> list3=list2[::-1]
>>> print(list2)
[10, 20, 30, 40, 50]
>>> print(list3)
[50, 40, 30, 20, 10]
copy module
copy.deepcopy(iterable)
Nested List
Defining list as element inside list is called nested list (OR) defining list
inside list is called nested list.
Using nested list data can be organized in rows and columns (OR)
nested list can be used to represent matrix.
Syntax:
<list-name>=[[v1,v2,v3],[v1,v2],[v1,v2,v3,v4]]
Example:
list1=[[10,20,30],[40,50,60],[70,80,90]]
print(list1[0])
print(list1[1])
print(list1[2])
print(list1[0][0],list1[0][1],list1[0][2])
print(list1[1][0],list1[1][1],list1[1][2])
print(list1[2][0],list1[2][1],list1[2][2])
print(list1[-1])
print(list1[-1][-1],list1[-1][-2],list1[-1][-3])
print(list1[-1][0],list1[-1][1],list1[-1][2])
Output:
[10, 20, 30]
[40, 50, 60]
[70, 80, 90]
10 20 30
40 50 60
70 80 90
[70, 80, 90]
90 80 70
70 80 90
Example:
# Reading elements from nested list using index
list1=[[10,20,30],[40,50,60],[70,80,90]]
for i in range(3): # start=0,stop=3,step=1 --> 0 1 2
print(list1[i])
Output:
[10, 20, 30]
[40, 50, 60]
[70, 80, 90]
10 20 30
40 50 60
70 80 90
Example:
# Reading elements from nested list without using index
list1=[[1,2,3],[4,5,6],[7,8,9]]
for x in list1:
print(x)
for x in list1:
for y in x:
print(y,end=' ')
print()
Output:
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
123
456
789
Example:
# Creating nested list by input values at runtime (OR) create 2x2
matrix
matrix=[]
matrix.append(row)
print(matrix)
Output:
Enter elements of matrix
Enter value 1
Enter value 2
Enter value 3
Enter value 4
[[1, 2], [3, 4]]
Example:
# write a program to read marks for 3 students and 3 subjects (3x3)
stud=[]
print("enter marks of students")
for i in range(3):
marks=[]
for j in range(3):
m=int(input("Enter Marks "))
marks.append(m)
stud.append(marks)
print(stud)
Output:
enter marks of students
Enter Marks 50
Enter Marks 60
Enter Marks 70
Enter Marks 80
Enter Marks 90
Enter Marks 60
Enter Marks 40
Enter Marks 50
Enter Marks 60
[[50, 60, 70], [80, 90, 60], [40, 50, 60]]
Example:
# Write a program to add two matrices
matrix1=[]
matrix2=[]
matrix3=[]
for i in range(2):
row=[]
for j in range(2):
row.append(matrix1[i][j]+matrix2[i][j])
matrix3.append(row)
print(matrix1)
print(matrix2)
print(matrix3)
Output:
Enter Elements of matrix1
Enter Value 1
Enter Value 2
Enter Value 3
Enter Value 4
Enter Elements of matrix2
Enter Value 5
Enter Value 6
Enter Value 7
Enter Value 8
[[1, 2], [3, 4]]
[[5, 6], [7, 8]]
[[6, 8], [10, 12]]
Comprehension
● List Comprehensions
● Dictionary Comprehensions
● Set Comprehensions
● Generator Comprehensions
Comprehensions are a powerful and concise way to create and
manipulate lists , sets , and dictionaries .
List Comprehension
Creating list using comprehension
Example:
# Create List with 0 filled 100 values
namesList=["nk","ramesh","suresh","kishore"]
# Create copy of list by converting all the names in upper case
namesList1=[ name.upper() for name in namesList]
print(namesList)
print(namesList1)
Output:
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
'V', 'W', 'X', 'Y', 'Z']
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z']
['nk', 'ramesh', 'suresh', 'kishore']
['NK', 'RAMESH', 'SURESH', 'KISHORE']
Example:
# Create a list with n values
#without comprehension
list1=[]
for i in range(n):
value=int(input("enter value"))
list1.append(value)
print(list1)
# with comprehension
list2=[int(input("enter value")) for i in range(n)]
print(list2)
Output:
Enter the value of n5
enter value10
enter value20
enter value30
enter value40
enter value50
[10, 20, 30, 40, 50]
enter value10
enter value20
enter value30
enter value40
enter value50
[10, 20, 30, 40, 50]
Example:
# Write a program to read 2x2 matrix
# without comprehension
matrix=[]
for i in range(2):
row=[]
for j in range(2):
value=int(input("enter value "))
row.append(value)
matrix.append(row)
print(matrix)
# with comprehension
matrix=[[int(input("enter value"))for j in range(2)] for i in range(2)]
print(matrix)
Output:
enter value 1
enter value 2
enter value 3
enter value 4
[[1, 2], [3, 4]]
enter value1
enter value2
enter value3
enter value4
[[1, 2], [3, 4]]
Example:
list1=[1,2,3,4,5,-1,-2,-3,-4,-5,10,20,-30,40,-20,-5,-7,60,30]
#without comprehension
list2=[]
list3=[]
for value in list1:
if value>=0:
list2.append(value)
else:
list3.append(value)
print(list1)
print(list2)
print(list3)
# with comprehension
list2=[value for value in list1 if value>=0]
list3=[value for value in list1 if value<0]
print(list2)
print(list3)
Output:
[1, 2, 3, 4, 5, -1, -2, -3, -4, -5, 10, 20, -30, 40, -20, -5, -7, 60, 30]
[1, 2, 3, 4, 5, 10, 20, 40, 60, 30]
[-1, -2, -3, -4, -5, -30, -20, -5, -7]
[1, 2, 3, 4, 5, 10, 20, 40, 60, 30]
[-1, -2, -3, -4, -5, -30, -20, -5, -7]
Example:
gradeList=[['nk','A'],
['suresh','A'],
['ramesh','B'],['kiran','C'],['raman','A'],['rajesh','B']]
print(gradeList)
Output:
[['nk', 'A'], ['suresh', 'A'], ['ramesh', 'B'], ['kiran', 'C'], ['raman', 'A'],
['rajesh', 'B']]
[['nk', 'A'], ['suresh', 'A'], ['raman', 'A']]
[['ramesh', 'B'], ['rajesh', 'B']]
[['kiran', 'C']]
Example:
numbers_list=[3,8,1,3,9,7,8,5,6,11,13,15,16,12,32,45,76,89,67,45]
even_list=[value for value in numbers_list if value%2==0]
odd_list=[value for value in numbers_list if value%2!=0]
print(numbers_list)
print(even_list)
print(odd_list)
Output:
[3, 8, 1, 3, 9, 7, 8, 5, 6, 11, 13, 15, 16, 12, 32, 45, 76, 89, 67, 45]
[8, 8, 6, 16, 12, 32, 76]
[3, 1, 3, 9, 7, 5, 11, 13, 15, 45, 89, 67, 45]
>>> list1=[1,2,3,4,5]
>>> list2=[6,7,8,9,10]
>>> list3=list1+list2
>>> print(list1)
[1, 2, 3, 4, 5]
>>> print(list2)
[6, 7, 8, 9, 10]
>>> print(list3)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> list2=[1,2]
>>> list3=list2*5
>>> print(list2)
[1, 2]
>>> print(list3)
[1, 2, 1, 2, 1, 2, 1, 2, 1, 2]
>>> list4=5*list2
>>> print(list4)
[1, 2, 1, 2, 1, 2, 1, 2, 1, 2]
>>> list1=[10,20,30]
>>> list2=[10,20,30]
>>> list1==list2
True
>>> list3=[30,10,20]
>>> list1==list3
False
>>> list1=[10,20,30]
>>> list2=[1,2,3]
>>> list1>list2
True
>>> list3=[1,30,3]
>>> list1>list2
True
>>> list1>list3
True
>>> list4=[30,1,2]
>>> list1>list4
False
any(iterable)¶
Return True if any element of the iterable is true. If the iterable is
empty, return False.
Example:
>>> list1=[]
>>> any(list1)
False
>>> list2=[10,20,30,40,40]
>>> any(list2)
True
>>> list3=[0,0,0]
>>> any(list3)
False
>>> list4=["java","python"]
>>> any(list4)
True
all(iterable)
Return True if all elements of the iterable are true (or if the iterable is
empty)
>>> list1=[1,2,3,4,5]
>>> all(list1)
True
>>> list2=[1,2,3,0,5]
>>> all(list2)
False
>>> list3=['*','+','/']
>>> all(list3)
True
tuple
tuple is an immutable sequence. After creating tuple changes
cannot be done. Tuple does not provides the following methods
1. Append()
2. Insert()
3. Remove()
4. Sort()
5. Update()
6. Del
7. …
Example:
>>> t1=()
>>> print(type(t1))
<class 'tuple'>
>>> print(t1)
()
>>> t1.append(10)
Traceback (most recent call last):
File "<pyshell#42>", line 1, in <module>
t1.append(10)
AttributeError: 'tuple' object has no attribute 'append'
>>> list1=[]
>>> list1.append(10)
>>> print(list1)
[10]
>>> t2=10,
>>> print(t2)
(10,)
>>> print(type(t2))
<class 'tuple'>
>>> t3=(30)
>>> print(type(t3))
<class 'int'>
>>> t4=(30,)
>>> print(type(t4))
<class 'tuple'>
>>> print(t4)
(30,)
>>> t5=10,20,30
>>> print(type(t5))
<class 'tuple'>
>>> print(t5)
(10, 20, 30)
>>> t6=(10,20,30,40,50)
>>> print(type(t6))
<class 'tuple'>
>>> print(t6)
(10, 20, 30, 40, 50)
>>> t7=(1,"nk","python",5000.0)
>>> t7[-1]=6000.0
Traceback (most recent call last):
File "<pyshell#61>", line 1, in <module>
t7[-1]=6000.0
TypeError: 'tuple' object does not support item assignment
>>> del t7[2]
Traceback (most recent call last):
File "<pyshell#62>", line 1, in <module>
del t7[2]
TypeError: 'tuple' object doesn't support item deletion
Using the tuple() built-in: tuple() or tuple(iterable)
>>> t1=tuple()
>>> print(t1)
()
>>> print(type(t1))
<class 'tuple'>
>>> t2=tuple(range(1,6))
>>> print(t2)
(1, 2, 3, 4, 5)
>>> t3=tuple(range(5,0,-1))
>>> print(t3)
(5, 4, 3, 2, 1)
>>> t4=tuple("PYTHON")
>>> print(t4)
('P', 'Y', 'T', 'H', 'O', 'N')
>>> list1=[10,20,30,40,50]
>>> t5=tuple(list1)
>>> print(t5)
(10, 20, 30, 40, 50)
>>> t6=tuple((10,20,30,40,50))
>>> print(t6)
(10, 20, 30, 40, 50)
>>> print(type(t6))
<class 'tuple'>
Example:
>>> t1=10,20,30
>>> print(t1)
(10, 20, 30)
>>> print(type(t1))
<class 'tuple'>
>>> a,b,c=10,20,30
>>> print(a,b,c)
10 20 30
>>> x,y,z=(10,20,30)
>>> print(x,y,z)
10 20 30
>>> a,b,c=(10,20,30,40,50)
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
a,b,c=(10,20,30,40,50)
ValueError: too many values to unpack (expected 3)
>>> a,b,c,*d=(10,20,30,40,50,60,70)
>>> print(a,b,c,d)
10 20 30 [40, 50, 60, 70]
>>> list1=[10,20,30]
>>> a,b,c=list1
>>> print(a,b,c)
10 20 30
>>> x=list1 # assigning list1 address to x variable (OR) x is alias
>>> print(x)
[10, 20, 30]
>>> print(list1)
[10, 20, 30]
>>> x,y,*z=list1
>>> print(x,y,z)
input() function read one value of type string. This input string is split
into number of values using split() method.
Example:
>>> s1="10 20 30 40 50"
>>> list1=s1.split()
>>> print(list1)
['10', '20', '30', '40', '50']
>>> s2="10,20,30,40,50"
>>> list2=s2.split(",")
>>> print(s2)
10,20,30,40,50
>>> print(list2)
['10', '20', '30', '40', '50']
>>> s3="1;2;3;4;5"
>>> list3=s3.split(";")
>>> print(s3)
1;2;3;4;5
>>> print(list3)
['1', '2', '3', '4', '5']
>>> s4=input()
10 20 30 40 50
>>> print(s4)
10 20 30 40 50
>>> list4=s4.split()
>>> print(list4)
Example:
s1="10 20"
list1=s1.split() # ['10','20']
a,b=list1 # unpacking
print(a,b)
s2=input()
list2=s2.split()
x,y=list2
print(x,y)
Output
10 20
100 200
100 200
Example:
# Write a program to add two numbers
# input format
#10 20
# output
# 30
s=input()
list1=s.split()
n1,n2=list1
n3=int(n1)+int(n2)
print(f'sum of {n1} and {n2} is {n3}')
Output:
10 20
sum of 10 and 20 is 30
Example:
list1=['10','20','30']
a,b,c=list1
print(a,b,c,type(a),type(b),type(c))
x,y,z=map(int,list1)
print(x,y,z,type(x),type(y),type(z))
p,q,r=map(float,list1)
print(p,q,r,type(p),type(q),type(r))
list2=["java","python","oracle"]
a,b,c=map(str.upper,list2)
print(a,b,c)
Output:
10 20 30 <class 'str'> <class 'str'> <class 'str'>
10 20 30 <class 'int'> <class 'int'> <class 'int'>
10.0 20.0 30.0 <class 'float'> <class 'float'> <class 'float'>
JAVA PYTHON ORACLE
Example:
# Write a program to add two numbers
# input format
#10 20
# output
# 30
n1,n2=map(int,input().split())
n3=n1+n2
print(f'sum of {n1} and {n2} is {n3}')
Output:
10 20
sum of 10 and 20 is 30
Example:
list1=['10','20','30']
list2=list(map(int,list1))
print(list1)
print(list2)
Output:
['10', '20', '30']
[10, 20, 30]
https://www.hackerrank.com/challenges/find-second-maximum-
number-in-a-list/problem?isFullScreen=true
n=int(input())
s=list(map(int,input().split()))
s.sort()
fmax=max(s)
c=s.count(fmax)
print(s[-(c+1)])
https://www.hackerrank.com/challenges/python-lists/problem?
isFullScreen=false
list1=[]
n=int(input())
for i in range(n):
cmd=input().split()
if cmd[0]=='insert':
list1.insert(int(cmd[1]),int(cmd[2]))
elif cmd[0]=="print":
print(list1)
elif cmd[0]=="append":
list1.append(int(cmd[1]))
elif cmd[0]=="remove":
list1.remove(int(cmd[1]))
elif cmd[0]=="sort":
list1.sort()
elif cmd[0]=="reverse":
list1.reverse()
elif cmd[0]=="pop":
list1.pop()
Python – Maximum and Minimum K elements in Tuple
Sometimes, while dealing with tuples, we can have problem in which
we need to extract only extreme K elements, i.e maximum and
minimum K elements in Tuple. This problem can have applications
across domains such as web development and Data Science
test_tup=(3, 7, 1, 18, 9)
k=2
test_tup=sorted(test_tup)
out_tup=tuple(test_tup[:k])+tuple(test_tup[-k:])
print(out_tup)
list1=[9, 5, 6]
list2=[(num,num**3) for num in list1] # list comprehension
print(list1)
print(list2)
What is difference between list and tuple?
List Tuple
List is a mutable sequence Tuple is a immutable sequence
After creating list changes can After creating tuple changes
be done cannot be done
list cannot be used as containers Tuple can be used as containers
for other collections like set and for other collections like set and
dictionary dictionary
List occupy more space Tuple occupy less space
List is created using [] Tuple is created using ()
“list” class or data type represents “tuple” class or data type
list object represents tuple object
In application development list is In application development
used to represent mutable tuple is used to represent
collection immutable collection
String
String is an immutable sequence data type.
String is a collection of characters. These characters can be
alphabets, digits or special characters.
The string which contains alphabets is called alphabetic string
This string which contains alphabets or digits is called alphanumeric
string. String is non numeric data type.
Example: name,course,grade,result,ifsccode,…
Name=”naresh”
Course=”python”
Grade=”A”
Result=”Pass”
Ifsccode=”HDFC000001234”
Example:
>>> str1="naresh"
>>> print(str1)
naresh
>>> str1='naresh'
>>> print(str1)
naresh
>>> str2='python language'
>>> print(str2)
python language
>>> str3='python 3.12'
>>> print(str3)
python 3.12
>>> str4='python "easy" language'
>>> print(str4)
python "easy" language
>>> str5='python 'easy' language'
SyntaxError: invalid syntax
>>> str6='python \'easy\' language'
>>> print(str6)
python 'easy' language
>>> s1="python"
>>> s2="python language"
>>> s3="python 3.12"
>>> print(s1,s2,s3,sep="\n")
python
python language
python 3.12
>>> s4="45"
>>> s5="65"
>>> s6=s4*s5
Traceback (most recent call last):
File "<pyshell#19>", line 1, in <module>
s6=s4*s5
TypeError: can't multiply sequence by non-int of type 'str'
>>> s6=s4+s5
>>> print(s6)
4565
>>> s7="python 'easy' language"
>>> print(s7)
python 'easy' language
>>> s8="python "easy" language"
SyntaxError: invalid syntax
>>> s9="python \"easy\" langauge"
>>> print(s9)
python "easy" langauge
>>> cmd="insert into emp values(101,'naresh',5000)"
>>> print(cmd)
insert into emp values(101,'naresh',5000)
>>> str1='''Python
... is a programming
... language'''
>>> print(str1)
Python
is a programming
language
>>> str2='python
SyntaxError: incomplete input
>>> str3="""python
... is a scripting
... language"""
>>> print(str3)
python
is a scripting
language
>>> n1=65
>>> s2=str(n1)
>>> print(n1,s2)
65 65
>>> print(type(n1),type(s2))
<class 'int'> <class 'str'>
>>> n2=1.5
>>> s3=str(n2)
>>> print(n2,s3)
1.5 1.5
>>> print(type(n2),type(s3))
<class 'float'> <class 'str'>
>>> s4=str()
>>> print(s4)
>>> s5=str("python")
>>> print(s5)
python
>>> s6=str([10,20,30,40,50])
>>> print(s6)
[10, 20, 30, 40, 50]
>>> print(type(s6))
<class 'str'>
>>> list1=[10,20,30,40,50]
>>> s7=str(list1)
>>> print(list1,s7)
[10, 20, 30, 40, 50] [10, 20, 30, 40, 50]
>>> print(type(list1),type(s7))
<class 'list'> <class 'str'>
>>> list1.append(60)
Output:
R
PROGR
AMMING
GNIMMARGORP
GRAMM
PORMIG
GIMROP
Example:
>>> str1="PYTHON"
>>> str1[0]="J"
Traceback (most recent call last):
File "<pyshell#61>", line 1, in <module>
str1[0]="J"
TypeError: 'str' object does not support item assignment
>>> del str1[0]
Traceback (most recent call last):
File "<pyshell#62>", line 1, in <module>
del str1[0]
TypeError: 'str' object doesn't support item deletion
>>> list1=[10,20,30,40]
>>> print(list1)
[10, 20, 30, 40]
>>> list1[0]=99
>>> print(list1)
[99, 20, 30, 40]
>>> del list1[0]
>>> print(list1)
[20, 30, 40]
Example:
# Write a program to find length of string (count of characters)
Example:
# Write a program to count alphabets,digits and special characters
exists within string
Output:
Enter any string 1ab$c3
Alphabet count 3
Digit count 2
Special Character count 1
Example:
str1="PROGRAMMING"
for ch in str1[::-1]:
print(ch,end=' ')
print()
for ch in str1[::2]:
print(ch,end=' ')
Output:
GNIMMARGORP
PORMIG
Example:
# Python program to check if a string is palindrome or not
# madam --> madam
# aba --> aba
Output:
Enter any string ama
ama is pal
Input:amaama
Output:
The entered string is symmetrical
The entered string is palindrome
if str1==str1[::-1]:
print("The entered string is palindrome")
else:
print("The entered string is not palindrome")
str.capitalize()
Return a copy of the string with its first character capitalized and the
rest lowercased.
Example:
>>> str1="python"
>>> str2=str1.capitalize()
>>> print(str1)
python
>>> print(str2)
Python
>>> str3="PYTHON"
>>> str4=str3.capitalize()
>>> print(str3)
PYTHON
>>> print(str4)
Python
Example:
# Write a program to capitalize string
print(str1)
print(str2)
Output:
Enter any string python
python
Python
str.lower()
Return a copy of the string with all the cased characters converted
to lowercase.
Example:
>>> str1="PYTHON"
>>> str2=str1.lower()
>>> print(str1)
PYTHON
>>> print(str2)
python
Example:
# Write a program to convert to strint into lowercase
for ch in str1:
if ch>='A' and ch<='Z':
str2=str2+chr(ord(ch)+32)
else:
str2=str2+ch
print(str1)
print(str2)
Output:
Enter any string ABC
ABC
abc
str.swapcase()
Return a copy of the string with uppercase characters converted to
lowercase and vice versa.
Example:
str1="aBcdEfG"
str2=str1.swapcase()
print(str1)
aBcdEfG
>>> print(str2)
AbCDeFg
>>> s1="nk"
>>> s2=s1.swapcase()
>>> print(s1)
nk
>>> print(s2)
Nk
Example:
# Write a program for swapcase
print(str1)
print(str2)
Output:
Enter any String abCDef
abCDef
ABcdEF
str.title()
Return a titlecased version of the string where words start with an
uppercase character and the remaining characters are lowercase.
Example:
Example:
# write a program for title case
str.upper()
Return a copy of the string with all the cased characters converted
to uppercase.
>>> str1="python"
>>> str2=str1.upper()
>>> print(str1)
python
>>> print(str2)
PYTHON
str.isalpha()
Return True if all characters in the string are alphabetic and there is
at least one character, False otherwise.
Example:
>>> str1="java"
>>> str1.isalpha()
True
>>> str2="java 17"
>>> str2.isalpha()
False
>>> str3="123"
>>> str3.isalpha()
False
Example:
# Write a program to verify string contains only alphabets
print(ans)
Output:
Enter any string python
True
str.isalnum()
Return True if all characters in the string are alphanumeric and there
is at least one character, False otherwise.
Example:
>>> str1="abc"
>>> str1.isalnum()
True
>>> str2="123"
>>> str2.isalnum()
True
>>> str3="abc123"
>>> str3.isalnum()
True
>>> str4="abc123$"
>>> str4.isalnum()
False
Example:
# Write a program to find input string is alphanumeric or not
print(ans)
Output:
Enter any string 123
True
str.isdigit()
Return True if all characters in the string are digits and there is at least
one character, False otherwise.
Example
>>> str1="abc"
>>> a=int(str1)
Traceback (most recent call last):
File "<pyshell#44>", line 1, in <module>
a=int(str1)
ValueError: invalid literal for int() with base 10: 'abc'
>>> str2="123"
>>> a=int(str2)
>>> print(a)
123
>>> str1.isdigit()
False
>>> str2.isdigit()
True
>>> str3="a123"
>>> str3.isdigit()
False
str.islower()
Return True if all cased characters in the string are lowercase and
there is at least one cased character, False otherwise.
>>> str1="python"
>>> str1.islower()
True
>>> str2="PYTHON"
>>> str2.islower()
False
>>> str3="a123"
>>> str3.islower()
True
>>> str4="abc123"
>>> str4.islower()
True
>>> str5="abc123$"
>>> str5.islower()
True
>>> str6="abC"
>>> str6.islower()
False
str.isspace()
Return True if there are only whitespace characters in the string and
there is at least one character, False otherwise.
str.istitle()
Return True if the string is a titlecased string and there is at least one
character return False.
str.isupper()
Return True if all cased characters in the string are uppercase and
there is at least one cased character, False otherwise.
>>> "NK".isupper()
True
>>> "nk".isupper()
False
>>> "N123".isupper()
True
str.center(width[, fillchar])
Return centered in a string of length width. Padding is done using the
specified fillchar
>>> s1="nit"
s2=s1.center(17)
>>> print(s1)
nit
>>> print(s2)
nit
>>> s3=s1.center(17,'*')
>>> print(s3)
*******nit*******
>>> s4=s1.center(30,"$")
>>> print(s4)
$$$$$$$$$$$$$nit$$$$$$$$$$$$$$
Full Stack Python (Part-45)
str.center(width[, fillchar])
Return centered in a string of length width. Padding is done using the
specified fillchar
>>> s1="nit"
s2=s1.center(17)
>>> print(s1)
nit
>>> print(s2)
nit
>>> s3=s1.center(17,'*')
>>> print(s3)
*******nit*******
>>> s4=s1.center(30,"$")
>>> print(s4)
$$$$$$$$$$$$$nit$$$$$$$$$$$$$$
str.ljust(width[, fillchar])
Return the string left justified in a string of length width. Padding is
done using the specified fillchar (default is an ASCII space). The
original string is returned if width is less than or equal to len(s).
Example:
>>> s1="nit"
>>> print(s1)
nit
>>> s1.ljust(30)
'nit '
>>> s1.ljust(30,"*")
'nit***************************'
Example:
names_list=["naresh","ramesh","kishore","kiran","rama","rajesh"]
for name in names_list:
print(name.ljust(20))
Output:
naresh
ramesh
kishore
kiran
rama
rajesh
naresh************** naresh**************
ramesh************** ramesh**************
kishore************* kishore*************
kiran*************** kiran***************
rama**************** rama****************
rajesh************** rajesh**************
str.rjust(width[, fillchar])
Return the string right justified in a string of length width. Padding is
done using the specified fillchar (default is an ASCII space). The
original string is returned if width is less than or equal to len(s).
Example:
names_list=["naresh","ramesh","kishore","kiran","rama","rajesh"]
for name in names_list:
print(name.rjust(20))
Output:
naresh
ramesh
kishore
kiran
rama
rajesh
**************naresh
**************ramesh
*************kishore
***************kiran
****************rama
**************rajesh
Split method
str.split(sep=None, maxsplit=- 1)
Return a list of the words in the string, using sep as the delimiter string.
If maxsplit is given, at most maxsplit splits are done (thus, the list will
have at most maxsplit+1 elements). If maxsplit is not specified or -1,
then there is no limit on the number of splits (all possible splits are
made).
Example:
>>> student="101,naresh,python,4000"
>>> list1=student.split(",")
>>> print(list1)
['101', 'naresh', 'python', '4000']
>>> str1="a b c d e f"
>>> list2=str1.split(" ")
>>> print(list2)
['a', 'b', 'c', 'd', 'e', 'f']
>>> list3=str1.split(" ",2)
>>> print(list3)
['a', 'b', 'c d e f']
>>> str3="10,20,30,40,50"
>>> list4=str3.split(",")
>>> print(list4)
str.rsplit(sep=None, maxsplit=- 1)
Return a list of the words in the string, using sep as the delimiter string.
If maxsplit is given, at most maxsplit splits are done,
the rightmost ones. If sep is not specified or None, any
whitespace string is a separator.
>>> s1="a,b,c,d,e"
>>> list1=s1.split(",")
>>> print(list1)
['a', 'b', 'c', 'd', 'e']
>>> list2=s1.rsplit(",")
>>> print(list2)
['a', 'b', 'c', 'd', 'e']
>>> list3=s1.split(",",2)
>>> print(list3)
['a', 'b', 'c,d,e']
>>> list4=s1.rsplit(",",2)
>>> print(list4)
['a,b,c', 'd', 'e']
str.join(iterable)
Return a string which is the concatenation of the strings in iterable.
>>> list1=["10","20","30","40","50"]
>>> s1=",".join(list1)
>>> print(list1)
['10', '20', '30', '40', '50']
>>> print(s1)
10,20,30,40,50
>>> s2=" ".join(list1)
print(s2)
10 20 30 40 50
>>> s3="*".join(list1)
>>> print(s3)
10*20*30*40*50
>>> list2=["a","b","c","d","e"]
>>> s4="".join(list2)
>>> print(list2)
['a', 'b', 'c', 'd', 'e']
>>> print(s4)
abcde
>>> list3=["james","gosling"]
>>> name=" ".join(list3)
>>> print(list3)
['james', 'gosling']
>>> print(name)
james gosling
https://www.hackerrank.com/challenges/swap-case/problem?
isFullScreen=true
def swap_case(s):
s1=""
for ch in s:
if ch>='A' and ch<='Z':
s1=s1+chr(ord(ch)+32)
elif ch>='a' and ch<='z':
s1=s1+chr(ord(ch)-32)
else:
s1=s1+ch
return s1
if __name__ == '__main__':
s = input()
result = swap_case(s)
print(result)
https://www.hackerrank.com/challenges/python-string-split-and-
join/problem?isFullScreen=true
def split_and_join(line):
# write your code here
list1=line.split()
s="-".join(list1)
return s
if __name__ == '__main__':
line = input()
result = split_and_join(line)
print(result)
https://www.hackerrank.com/challenges/python-mutations/
problem?isFullScreen=false
if __name__ == '__main__':
s = input()
i, c = input().split()
s_new = mutate_string(s, int(i), c)
Searching methods
Example:
names_list=["naresh","suresh","ramesh","kishore","rajesh"]
for name in names_list:
a=name.startswith('r')
if a:
print(name)
Output:
ramesh
rajesh
Example:
>>> s1="python"
>>> s1.startswith("p")
True
>>> s1.startswith("j")
False
>>> s2="python language"
>>> s2.startswith("l",7)
True
Example:
names_list=["naresh","suresh","ramesh","kishore","rajesh","kiran"]
for name in names_list:
a=name.startswith(('r','k'))
if a:
print(name)
Output:
ramesh
kishore
rajesh
kiran
Example:
names_list=["naresh","suresh","ramesh","kishore","rajesh","kiran","raman"
]
for name in names_list:
a=name.endswith("h")
if a:
print(name)
print("=========================================")
for name in names_list:
a=name.endswith(("h","n"))
if a:
print(name)
Output:
naresh
suresh
ramesh
rajesh
=========================================
naresh
suresh
ramesh
rajesh
kiran
raman
Example:
>>> s1="java"
>>> s1.endswith("a")
True
>>> s1.endswith("n")
False
>>> s2="python language"
>>> s2.endswith("e")
True
>>> s2.endswith("n",0,6)
True
Strip methods
str.lstrip([chars])
Return a copy of the string with leading characters removed.
The chars argument is a string specifying the set of characters to be
removed. If omitted or None, the chars argument defaults to
removing whitespace. The chars argument is not a prefix; rather, all
combinations of its values are stripped:
>>> a="xyz"
>>> b=" xyz"
>>> a==b
False
>>> a==b.lstrip()
True
>>> c=b.lstrip()
>>> print(a)
xyz
>>> print(b)
xyz
>>> print(c)
xyz
>>> s1="****xyz"
>>> s1=="xyz"
False
>>> s2=s1.lstrip("*")
>>> print(s2)
Xyz
>>> s2=="xyz"
True
>>> s3="**$$**##$$xyz"
>>> s4=s3.lstrip("*#$")
>>> print(s3)
**$$**##$$xyz
p
>>> print(s4)
Xyz
>>> 'Arthur: three!'.lstrip('Arthur: ')
'ee!'
str.removeprefix(prefix, /)
If the string starts with the prefix string, return string[len(prefix):].
Otherwise, return a copy of the original string:
>>>
>>> 'TestHook'.removeprefix('Test')
'Hook'
>>> 'BaseTestCase'.removeprefix('Test')
'BaseTestCase'
str.rstrip([chars])
Return a copy of the string with trailing characters removed.
The chars argument is a string specifying the set of characters to be
removed. If omitted or None, the chars argument defaults to
removing whitespace. The chars argument is not a suffix; rather, all
combinations of its values are stripped:
str.removesuffix(suffix, /)
If the string ends with the suffix string and that suffix is not empty,
return string[:-len(suffix)]. Otherwise, return a copy of the original
string:
>>>
>>> 'MiscTests'.removesuffix('Tests')
'Misc'
>>> 'TmpDirMixin'.removesuffix('Tests')
'TmpDirMixin'
str.strip([chars])
Return a copy of the string with the leading and trailing characters
removed. The chars argument is a string specifying the set of
characters to be removed. If omitted or None, the chars argument
defaults to removing whitespace. The chars argument is not a prefix
or suffix; rather, all combinations of its values are stripped:
Partition methods
str.partition(sep)
Split the string at the first occurrence of sep, and return a 3-tuple
containing the part before the separator, the separator itself, and
the part after the separator. If the separator is not found, return a 3-
tuple containing the string itself, followed by two empty strings.
>>> str1="a,b,c,d,e"
>>> t1=str1.partition(",")
>>> print(str1)
a,b,c,d,e
>>> print(t1)
('a', ',', 'b,c,d,e')
>>> str2="xyz"
>>> t2=str2.partition("y")
>>> print(str2)
xyz
>>> print(t2)
('x', 'y', 'z')
>>> str3="xyz:abc:pqr"
>>> t3=str3.partition(":")
>>> print(t3)
('xyz', ':', 'abc:pqr')
>>> name="rama rao"
>>> t=name.partition(" ")
>>> print(t)
('rama', ' ', 'rao')
>>> fname=t[0]
>>> lname=t[-1]
>>> print(fname,lname)
rama rao
>>> str1=t[1].join((fname,lname))
>>> print(str1)
rama rao
str.rpartition(sep)
Split the string at the last occurrence of sep, and return a 3-tuple
containing the part before the separator, the separator itself, and
the part after the separator. If the separator is not found, return a 3-
tuple containing two empty strings, followed by the string itself.
>>> str1="a,b,c,d"
>>> t=str1.rpartition(",")
>>> print(str1)
a,b,c,d
>>> print(t)
('a,b,c', ',', 'd')
>>> str1="a,b,c,d"
>>> t=str1.rpartition(",")
>>> print(str1)
a,b,c,d
>>> print(t)
('a,b,c', ',', 'd')
>>> t=str1.rpartition(" ")
>>> print(t)
('', '', 'a,b,c,d')
>>> t=str1.partition(" ")
>>> print(t)
('a,b,c,d', '', '')
Translation method
str.translate(table)
Return a copy of the string in which each character has been
mapped through the given translation table.
Example:
>>> table1=str.maketrans("aeiou","!@#$%")
>>> str1="programming"
>>> str2=str1.translate(table1)
>>> print(str1)
programming
>>> print(str2)
pr$gr!mm#ng
>>> table2=str.maketrans("!@#$%","aeiou")
>>> str3=str2.translate(table2)
>>> print(str3)
programming
>>> table3=str.maketrans("abcdefghijklmnopqrstuvwxyz","123456789!
@#$%^&*(){}:><?/")
>>> table4=str.maketrans("123456789!@#$%^&*()
{}:><?/","abcdefghijklmnopqrstuvwxyz")
>>> uname="naresh"
>>> uname1=uname.translate(table3)
>>> print(name)
rama rao
>>> print(uname)
naresh
>>> print(uname1)
%1(5)8
>>> uname2=uname1.translate(table4)
>>> print(uname2)
naresh
>>> table5=str.maketrans("aeiou","!@#$%","1234567890")
>>> str1="python312"
>>> str2=str1.translate(table5)
>>> print(str1)
python312
>>> print(str2)
pyth$n
>>> b1=b'python'
>>> print(type(b1))
<class 'bytes'>
>>> s1='python'
>>> print(type(s1))
<class 'str'>
>>> b2=b"python"
>>> print(b2)
b'python'
>>> print(type(b2))
<class 'bytes'>
>>> b3=b'python is "easy" language'
>>> print(b3)
b'python is "easy" language'
>>> b4=b"python is 'easy' language"
>>> print(b4)
b"python is 'easy' language"
>>> b5=b'''python is
... programming
... language'''
>>> print(b5)
b'python is\nprogramming\nlanguage'
>>> b6=b"""python is
... programming
... language"""
>>> print(b6)
b'python is\nprogramming\nlanguage'
Example:
>>> b1=bytes(10)
>>> print(b1)
b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
>>> b2=bytes(range(65,91))
>>> print(b2)
b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> list1=[65,66,67,68]
>>> b3=bytes(list1)
>>> print(b3)
b'ABCD'
>>> b4=bytes(b3)
>>> print(b4)
b'ABCD'
>>> print(b2[0])
65
>>> for value in b2:
... print(value,end=' ')
...
...
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
89 90
>>> for value in b1:
... print(value,end=' ')
...
...
0000000000
>>> b1=b'ABC'
>>> print(b1)
b'ABC'
>>> b1.append(65)
Traceback (most recent call last):
File "<pyshell#41>", line 1, in <module>
b1.append(65)
AttributeError: 'bytes' object has no attribute 'append'
>>> b1[0]=66
Traceback (most recent call last):
File "<pyshell#42>", line 1, in <module>
b1[0]=66
TypeError: 'bytes' object does not support item assignment
bytearray
Example:
>>> ba1=bytearray()
>>> print(ba1)
bytearray(b'')
>>> ba1.append(65)
>>> print(ba1)
bytearray(b'A')
>>> ba1.append(66)
>>> print(ba1)
bytearray(b'AB')
>>> ba1.extend([67,68,69,70])
>>> print(ba1)
bytearray(b'ABCDEF')
>>> ba1[0]=71
>>> print(ba1)
bytearray(b'GBCDEF')
>>> del ba1[0]
>>> print(ba1)
bytearray(b'BCDEF')
>>> ba2=bytearray(10)
>>> print(ba2)
bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
>>> ba2[0]=65
>>> print(ba2)
bytearray(b'A\x00\x00\x00\x00\x00\x00\x00\x00\x00')
>>> ba2[-1]=90
>>> print(ba2)
bytearray(b'A\x00\x00\x00\x00\x00\x00\x00\x00Z')
>>> ba3=bytearray(range(97,123))
>>> print(ba3)
bytearray(b'abcdefghijklmnopqrstuvwxyz')
>>> ba4=bytearray(ba3)
>>> print(ba4)
bytearray(b'abcdefghijklmnopqrstuvwxyz')
1. set (mutable)
2. frozenset (immutable)
Application of sets
1. To remove duplicates from sequences
2. To perform mathematical set operations
a. Union
b. Intersection
c. Difference
…
3. To represent unique data
Empty set cannot create using empty {}, this represents dictionary.
Example:
>>> s1={}
>>> type(s1)
<class 'dict'>
>>> s2=set()
>>> print(s2)
set()
>>> s3={10}
>>> type(s3)
<class 'set'>
>>> s4={10,20,30,40,50}
>>> type(s4)
<class 'set'>
>>> print(s4)
{50, 20, 40, 10, 30}
>>> s5={10,10,10,10,10,10}
>>> print(s5)
{10}
>>> s6={10,20,10,20,10,20,30}
>>> print(s6)
{10, 20, 30}
Creating set using set function
set() function is used to create empty set and to convert other
iterables into set type.
Example:
>>> s1=set()
>>> print(s1)
>>> set()
>>> type(s1)
<class 'set'>
>>> s1=set()
>>> print(s1)
set()
>>> type(s1)
<class 'set'>
>>> s2=set([10,20,30,40,50])
>>> print(s2)
{40, 10, 50, 20, 30}
>>> s3=set([10,10,20,20,30,40,50])
>>> print(s3)
{40, 10, 50, 20, 30}
>>> s3=set(range(10,60,10))
>>> print(s3)
{40, 10, 50, 20, 30}
>>> s4=set("NIT")
>>> print(s4)
{'I', 'N', 'T'}
>>> s5=set("JAVA")
>>> print(s5)
{'J', 'V', 'A'}
>>> s6=set({10,20,30})
>>> print(s6)
{10, 20, 30}
>>> print(type(s6))
<class 'set'>
>>> s7=set((10,10,10,10,10))
>>> print(s7)
{10}
Hashing
Object Law
If two objects are equal according == operator, it should generate
same hash value.
Example:
>>> a=10
>>> hash(a)
10
>>> b=10
>>> hash(b)
10
>>> a==b
True
>>> f1=1.5
>>> f2=1.5
>>> f1==f2
True
>>> hash(f1)
1152921504606846977
>>> hash(f2)
1152921504606846977
>>> f3=1.7
>>> f1==f3
False
>>> hash(f3)
1614090106449585665
>>> s1="abc"
>>> s2="abc"
>>> s1==s2
True
>>> hash(s1)
4812977690135374638
>>> hash(s2)
4812977690135374638
>>> l1=[10,20,30]
>>> hash(l1)
Traceback (most recent call last):
File "<pyshell#37>", line 1, in <module>
hash(l1)
TypeError: unhashable type: 'list'
Example:
>>> set1={10,20,30,40,50}
>>> print(set1)
{50, 20, 40, 10, 30}
>>> set1[0]
Traceback (most recent call last):
File "<pyshell#40>", line 1, in <module>
set1[0]
TypeError: 'set' object is not subscriptable
Example:
A={10,20,30,40,50}
print("****************************")
e=enumerate(A)
t1=next(e)
t2=next(e)
print(t1)
print(t2)
Membership testing
Example:
# Count of each value in list
# Input:
# list1=[10,20,30,10,10,10,20,30,30,50]
# Output:
# 10 --> 4
# 20 --> 2
# 30 --> 3
# 50 --> 1
list1=[10,20,30,10,10,10,20,30,30,50]
set1=set(list1) # {10,20,30,50}
for value in set1:
c=list1.count(value)
print(f'{value}--->{c}')
Output:
10--->4
20--->2
50--->1
30--->3
Example:
# Count of each character exist within string
# input:
# abcaaabbca
# Output
# 5a3b2c
str1="abcaaabbca"
s1=set(str1) # {"a","b","c"}
str2=""
for ch in s1:
c=str1.count(ch)
str2=str2+str(c)+ch
print(str1)
print(str2)
Output:
abcaaabbca
5a3b2c
https://www.hackerrank.com/challenges/py-introduction-to-sets/
problem?isFullScreen=false
def average(array):
# your code goes here
s=set(array)
a=sum(s)/len(s)
return round(a,3)
if __name__ == '__main__':
n = int(input())
arr = list(map(int, input().split()))
result = average(arr)
print(result)
Set Operations
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.
Full Stack Python (Part-49)
Set Operations
union(*others)
set | other | ...
Return a new set with elements from the set and all others.
Example:
>>> A={10,20,30}
>>> B={40,50,60}
>>> C=A.union(B)
>>> print(A,B,C,sep="\n")
{10, 20, 30}
{40, 50, 60}
{50, 20, 40, 10, 60, 30}
>>> X={1,2,3}
>>> Y={1,2,3,4}
>>> Z={1,2,3,5,6,7}
>>> P=X|Y|Z
>>> print(X,Y,Z,P)
{1, 2, 3} {1, 2, 3, 4} {1, 2, 3, 5, 6, 7} {1, 2, 3, 4, 5, 6, 7}
>>> S1=set("ABC")
>>> S2=set("ABCD")
>>> S3=S1.union(S2)
>>> print(S1,S2,S3)
{'C', 'A', 'B'} {'C', 'A', 'B', 'D'} {'A', 'D', 'C', 'B'}
https://www.hackerrank.com/challenges/py-set-union/problem?
isFullScreen=false
n=int(input())
eng=set(map(int,input().split()))
b=int(input())
fre=set(map(int,input().split()))
c=len(eng.union(fre))
print(c)
intersection(*others)
set & other & ...
Return a new set with elements common to the set and all others.
Example:
>>> A={10,20,30,40,50}
>>> B={10,20,60,70,80}
>>> C=A.intersection(B)
>>> print(A,B,C,sep='\n')
{50, 20, 40, 10, 30}
{80, 20, 70, 10, 60}
{10, 20}
>>> S1={1,2,3,4,5}
>>> S2={3,4,5,6,7}
>>> S3={5,6,7,8,9}
>>> S4=S1&S2&S3
>>> print(S1,S2,S3,S4,sep="\n")
{1, 2, 3, 4, 5}
{3, 4, 5, 6, 7}
{5, 6, 7, 8, 9}
{5}
https://www.hackerrank.com/challenges/py-set-intersection-
operation/problem?isFullScreen=false
n=int(input())
eng=set(map(int,input().split()))
b=int(input())
fre=set(map(int,input().split()))
c=len(eng.intersection(fre))
print(c)
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={3,4,5,6,7}
>>> C=A.difference(B)
>>> print(A)
{1, 2, 3, 4, 5}
>>> print(B)
{3, 4, 5, 6, 7}
>>> print(C)
{1, 2}
>>> python_students={"nk","suresh","kishore","rajesh"}
>>> java_students={"ramesh","raman","kishore","suresh"}
>>> only_python=python_students.difference(java_students)
>>> print(python_students,java_students,only_python,sep="\n")
{'suresh', 'nk', 'kishore', 'rajesh'}
{'kishore', 'suresh', 'raman', 'ramesh'}
{'nk', 'rajesh'}
>>> only_java=java_students-python_students
>>> print(only_java)
{'raman', 'ramesh'}
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={3,4,5,6,7}
>>> C=A.symmetric_difference(B)
>>> print(A)
{1, 2, 3, 4, 5}
>>> print(B)
{3, 4, 5, 6, 7}
>>> print(C)
{1, 2, 6, 7}
https://www.hackerrank.com/challenges/symmetric-difference/
problem?isFullScreen=false
m=int(input())
a=set(map(int,input().split()))
n=int(input())
b=set(map(int,input().split()))
c=a.symmetric_difference(b)
d=list(c)
d.sort()
for value in d:
print(value)
Mutable Operations of Set
add(elem)
Add element elem to the set.
>>> A=set()
>>> print(A)
set()
>>> A.add(10)
>>> A.add(20)
>>> A.add(30)
>>> A.add(40)
>>> A.add(50)
>>> print(A)
{40, 10, 50, 20, 30}
https://www.hackerrank.com/challenges/py-set-add/problem?
isFullScreen=false
N=int(input())
country=set()
for i in range(N):
country_stamp=input()
country.add(country_stamp)
print(len(country))
Example:
>>> A={10,20,30,40,50,60,70,80,90,100}
>>> print(A)
{100, 70, 40, 10, 80, 50, 20, 90, 60, 30}
>>> A.remove(10)
>>> print(A)
{100, 70, 40, 80, 50, 20, 90, 60, 30}
>>> A.remove(60)
>>> print(A)
{100, 70, 40, 80, 50, 20, 90, 30}
>>> A.remove(10)
Traceback (most recent call last):
File "<pyshell#54>", line 1, in <module>
A.remove(10)
KeyError: 10
discard(elem)
Remove element elem from the set if it is present.
>>>
email_set={"[email protected]","[email protected]","[email protected]"}
>>> print(email_set)
{'[email protected]', '[email protected]', '[email protected]'}
>>> email_set.discard("[email protected]")
>>> print(email_set)
{'[email protected]', '[email protected]'}
>>> email_set.discard("[email protected]")
pop()
Remove and return an arbitrary element from the set.
Raises KeyError if the set is empty.
>>> A=set(range(10,60,10))
>>> print(A)
{40, 10, 50, 20, 30}
>>> value1=A.pop()
>>> print(value1)
40
>>> print(A)
{10, 50, 20, 30}
clear()
Remove all elements from the set.
>>> S1={10,20,30,40,50}
>>> S1.clear()
>>> print(S1)
set()
update(*others)
set |= other | ...
Update the set, adding elements from all others
Example:
>>> A={10,20,30}
>>> print(A)
{10, 20, 30}
>>> A.update({40,50})
>>> print(A)
{50, 20, 40, 10, 30}
>>> S1={1,2,3,4,5}
>>> S2={3,4,5,6,7,8,9}
>>> S1.update(S2)
>>> print(S1)
{1, 2, 3, 4, 5, 6, 7, 8, 9}
>>> A.add(80)
>>> A.add(100,200,300)
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
A.add(100,200,300)
TypeError: set.add() takes exactly one argument (3 given)
intersection_update(*others)
set &= other & ...
Update the set, keeping only elements found in it and all others.
>>> A={1,2,3,4,5,6}
>>> B={1,2,3,7,8,9}
>>> print(A)
{1, 2, 3, 4, 5, 6}
>>> print(B)
{1, 2, 3, 7, 8, 9}
>>> A.intersection_update(B)
>>> print(A)
{1, 2, 3}
difference_update(*others)
set -= other | ...
Update the set, removing elements found in others.
>>> A={1,2,3,4,5}
>>> B={1,2,3,6,7}
>>> print(A)
{1, 2, 3, 4, 5}
>>> print(B)
{1, 2, 3, 6, 7}
>>> A.difference_update(B)
>>> print(A)
{4, 5}
symmetric_difference_update(other)
set ^= other
Update the set, keeping only elements found in either set, but not in
both.
>>> A={1,2,4,5}
>>> B={1,2,6,7}
>>> print(A)
{1, 2, 4, 5}
>>> print(B)
{1, 2, 6, 7}
>>> A.symmetric_difference_update(B)
>>> print(A)
{4, 5, 6, 7}
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}
>>> B={4,5,6}
>>> print(A)
{1, 2, 3}
>>> print(B)
{4, 5, 6}
>>> A.isdisjoint(B)
True
>>> java_students={"ramesh","rajesh","kiran"}
>>> python_students={"nk","kishore","raman"}
>>> b=java_students.isdisjoint(python_students)
>>> print(b)
True
>>> if b==True:
... print("no student of java is doing python")
... else:
... print("some students of java are doing python")
...
...
no student of java is doing python
issubset(other)
set <= other
Test whether every element in the set is in other.
>>> A={1,2,3}
>>> B={1,2,3,4,5}
>>> A.issubset(B)
True
issuperset(other)
set >= other
Test whether every element in other is in the set.
>>> A={1,2,3,4,5}
>>> B={1,2,3}
>>> A.issuperset(B)
True
https://www.hackerrank.com/challenges/py-the-captains-room/
problem?isFullScreen=false
k=int(input())
rooms=list(map(int,input().split()))
s=set(rooms)
for rno in s:
c=rooms.count(rno)
if c==1:
print(rno)
or
k = int(input())
rooms = list(map(int, input().split()))
room_count = {}
T=int(input())
for i in range(T):
m=int(input())
A=set(map(int,input().split()[:m]))
n=int(input())
B=set(map(int,input().split()[:n]))
print(A.issubset(B))
frozenset is a set.
Frozenset represents immutable set. After creating frozenset the
following operations cannot be done,
1. add()
2. eemove()
3. discard()
4. clear()
5. pop()
6. update()
7. difference_update()
8. ….
>>> f1=frozenset()
>>> print(f1)
frozenset()
>>> f1.add(10)
Traceback (most recent call last):
File "<pyshell#55>", line 1, in <module>
f1.add(10)
AttributeError: 'frozenset' object has no attribute 'add'
>>> f2=frozenset({10,20,30,40,50})
>>> print(f2)
frozenset({50, 20, 40, 10, 30})
>>> print(type(f2))
<class 'frozenset'>
>>> f2.remove(10)
Traceback (most recent call last):
File "<pyshell#59>", line 1, in <module>
f2.remove(10)
AttributeError: 'frozenset' object has no attribute 'remove'
>>> f3=frozenset(range(10,110,10))
>>> print(f3)
frozenset({100, 70, 40, 10, 80, 50, 20, 90, 60, 30})
>>> f4=frozenset("JAVA")
>>> print(f4)
frozenset({'V', 'J', 'A'})
>>> f5=frozenset([10,20,30,40,50])
>>> print(f5)
frozenset({40, 10, 50, 20, 30})
Example:
>>> A={{1,2},{3,4},{5,6}}
Traceback (most recent call last):
File "<pyshell#66>", line 1, in <module>
A={{1,2},{3,4},{5,6}}
TypeError: unhashable type: 'set'
>>> A={[10,20],[30,40]}
Traceback (most recent call last):
File "<pyshell#67>", line 1, in <module>
A={[10,20],[30,40]}
TypeError: unhashable type: 'list'
>>> A={(10,20),(30,40)}
print(A)
{(30, 40), (10, 20)}
>>> A={frozenset({1,2}),frozenset({3,4}),frozenset({5,6})}
>>> print(A)
{frozenset({3, 4}), frozenset({5, 6}), frozenset({1, 2})}
for s in A:
print(s)
...
frozenset({3, 4})
frozenset({5, 6})
frozenset({1, 2})
>>> for s in A:
... for v in s:
... print(v,end=' ')
... print()
...
...
34
56
12
Example:
>>> d1={}
>>> print(d1)
{}
>>> print(type(d1))
<class 'dict'>
>>> d1={}
>>> print(d1)
{}
>>> print(type(d1))
<class 'dict'>
>>> persons={'nk':50,'suresh':40,'kishore':60,'ramesh':30}
>>> contacts={'nk':995566778,'suresh':8866755667}
>>> print(persons)
{'nk': 50, 'suresh': 40, 'kishore': 60, 'ramesh': 30}
>>> print(contacts)
{'nk': 995566778, 'suresh': 8866755667}
>>> dict1={1:10,2:20,3:30}
>>> print(dict1)
{1: 10, 2: 20, 3: 30}
>>> emp_dict={'empno':[1,2,3],'ename':['nk','ramesh','suresh']}
>>> print(emp_dict)
{'empno': [1, 2, 3], 'ename': ['nk', 'ramesh', 'suresh']}
>>> dict2={1:10,2:20,3:30,3:40,3:50,1:90}
>>> print(dict2)
{1: 90, 2: 20, 3: 50}
>>> dict3={1:10,2:10,3:10,4:10}
>>> print(dict3)
{1: 10, 2: 10, 3: 10, 4: 10}
>>> d1=dict()
>>> print(d1)
{}
>>> print(type(d1))
<class 'dict'>
>>> d1=dict()
>>> print(d1)
{}
>>> print(type(d1))
<class 'dict'>
>>> list1=[10,20,30,40,50]
>>> dict1=dict(list1)
Traceback (most recent call last):
File "<pyshell#19>", line 1, in <module>
dict1=dict(list1)
TypeError: cannot convert dictionary update sequence element #0
to a sequence
>>> e=enumerate(list1)
>>> dict1=dict(e)
>>> print(dict1)
{0: 10, 1: 20, 2: 30, 3: 40, 4: 50}
>>> sales_list=[5000,6000,7000,8000,9000]
>>> e=enumerate(sales_list,2000)
>>> sales_dict=dict(e)
>>> print(sales_dict)
{2000: 5000, 2001: 6000, 2002: 7000, 2003: 8000, 2004: 9000}
>>> list2=[(1,10),(2,20),(3,30),(4,40),(5,50)]
>>> dict2=dict(list2)
>>> print(dict2)
{1: 10, 2: 20, 3: 30, 4: 40, 5: 50}
>>> list1=[1,2,3,4,5]
>>> list2=[10,20,30,40,50]
>>> list3=[(list1[i],list2[i]) for i in range(5)]
>>> print(list3)
[(1, 10), (2, 20), (3, 30), (4, 40), (5, 50)]
>>> dict3=dict(list3)
>>> print(dict3)
{1: 10, 2: 20, 3: 30, 4: 40, 5: 50}
zip()
Iterate over several iterables in parallel, producing tuples with an
item from each one.
More formally: zip() returns an iterator of tuples, where the i-th tuple
contains the i-th element from each of the argument iterables.
zip(*iterables, strict=False)
Example:
>>> list1=[1,2,3]
>>> list2=[10,20]
>>> z1=zip(list1,list2)
>>> dict1=dict(z1)
>>> print(dict1)
{1: 10, 2: 20}
>>> list3=[1,2,3,4]
>>> list4=[10,20,30,40,50,60]
>>> z2=zip(list3,list4)
>>> dict2=dict(z2)
>>> print(dict2)
{1: 10, 2: 20, 3: 30, 4: 40}
>>> z3=zip(list3,list4,strict=True)
>>> print(z3)
<zip object at 0x0000026A6DD03300>
dict3=dict(z3)
Traceback (most recent call last):
File "<pyshell#49>", line 1, in <module>
dict3=dict(z3)
ValueError: zip() argument 2 is longer than argument 1
>>> str1="abcde"
>>> str2="xyz"
>>> z4=zip(str1,str2)
>>> dict4=dict(z4)
>>> print(dict4)
{'a': 'x', 'b': 'y', 'c': 'z'}
>>> dict5=dict(zip(range(1,6),range(10,60,10)))
>>> print(dict5)
{1: 10, 2: 20, 3: 30, 4: 40, 5: 50}
>>> dict6=dict(zip(range(1,6),"ABCDEF"))
>>> print(dict6)
{1: 'A', 2: 'B', 3: 'C', 4: 'D', 5: 'E'}
>>> dict7=dict(zip(range(1,6),
["nk","suresh","ramesh","kishore","rajesh"]))
>>> print(dict7)
{1: 'nk', 2: 'suresh', 3: 'ramesh', 4: 'kishore', 5: 'rajesh'}
>>>
Using key
Dictionary is key based collection, to read value from dictionary we
can use key.
Syntax: dictionary-name[key]
Example:
users_dict={'nk':'nit123','suresh':'s123','kishore':'t543'}
uname=input("UserName ")
pwd=input("Password ")
if uname in users_dict:
p=users_dict[uname]
if p==pwd:
print(f'{uname} welcome')
else:
print("invalid password")
else:
print("Invalid username")
Output:
UserName suresh
Password s123
suresh welcome
UserName ramesh
Password r123
Invalid username
UserName nk
Password n321
invalid password
Example:
>>> d1={1:10,2:20,3:30}
>>> d1[2]
20
>>> d1[3]
30
>>> d1[1]
10
>>> d1[10]
Traceback (most recent call last):
File "<pyshell#65>", line 1, in <module>
d1[10]
KeyError: 10
Example:
>>> prod_dict={'keyboard':1000,'mouse':300,'monitor':7000}
>>> for pname in prod_dict:
print(pname)
keyboard
mouse
monitor
>>> for pname in prod_dict:
print(pname,prod_dict[pname])
keyboard 1000
mouse 300
monitor 7000
>>> d1=[1:10,2:20,3:30]
SyntaxError: invalid syntax
>>> d1={1:10,2:20,3:30}
for k in d1:
... print(k)
...
...
1
2
3
>>> for k in d1:
... print(k,d1[k])
...
...
1 10
2 20
3 30
Using iterator
Syntax: iter(iterable)
Example
dict1={1:10,2:20,3:30,4:40,5:50}
a=iter(dict1)
k1=next(a)
print(k1)
k2=next(a)
print(k2)
v1=dict1[k1]
v2=dict1[k2]
print(v1,v2)
for k in a:
print(k,dict1[k])
Output:
1
2
10 20
3 30
4 40
5 50
Example:
sales={2010:45000,
2011:56000,
2012:65000,
2013:67000,
2014:75000}
print(sales)
years=sales.keys()
for year in years:
print(year)
sales_amt=sales.values()
for s in sales_amt:
print(s)
s=sales.items()
for t in s:
print(t)
Output
{2010: 45000, 2011: 56000, 2012: 65000, 2013: 67000, 2014: 75000}
2010
2011
2012
2013
2014
45000
56000
65000
67000
75000
(2010, 45000)
(2011, 56000)
(2012, 65000)
(2013, 67000)
(2014, 75000)
get(key[, default])
Return the value for key if key is in the dictionary, else default.
If default is not given, it defaults to None, so that this method never
raises a KeyError.
Example:
>>> d1={1:10,2:20,3:30,4:40,5:50}
>>> d1[1]
10
>>> d1[4]
40
>>> d1[6]
Traceback (most recent call last):
File "<pyshell#18>", line 1, in <module>
d1[6]
KeyError: 6
>>> v1=d1.get(1)
>>> print(v1)
10
>>> v2=d1.get(4)
>>> print(v2)
40
>>> v3=d1.get(6)
>>> print(v3)
None
>>> v4=d1.get(6,60)
>>> print(v4)
60
setdefault(key[, default])
If key is in the dictionary, return its value. If not, insert key with a value
of default and return default. default defaults to None.
Full Stack Python (Part-53)
setdefault(key[, default])
If key is in the dictionary, return its value. If not, insert key with a value
of default and return default. default defaults to None.
Example:
>>> d1={1:10,2:20,3:30}
>>> print(d1)
{1: 10, 2: 20, 3: 30}
>>> print(d1[1])
10
>>> print(d1.get(2))
20
>>> print(d1.get(4))
None
>>> print(d1)
{1: 10, 2: 20, 3: 30}
>>> print(d1.setdefault(4))
None
>>> print(d1)
{1: 10, 2: 20, 3: 30, 4: None}
>>> print(d1.setdefault(3))
30
>>> print(d1.setdefault(5,50))
50
>>> print(d1)
{1: 10, 2: 20, 3: 30, 4: None, 5: 50}
Syntax: dictionary-name[key]=value
dict1={1:25,2:21,3:23}
a=list(dict1.values())
a.sort()
print(a)
dict1={}
n=int(input("enter number of terms?"))
for i in range(1,n+1): # 1 2 3 4
dict1[i]=i*5
print(dict1)
d1={1:2,2:90,3:50}
a=d1.values()
tot=sum(a)
print(tot)
d1={1:2,2:90,3:50}
a=d1.keys()
tot=sum(a)
print(tot)
d1={1:2,2:90,3:50}
a=d1.values()
print(f'Minimum value is {min(a)}')
print(f'Maximum value is {max(a)}')
d1={1:"Aman",2:"Suman",3:"Aman"}
d2={}
for k,v in d1.items():
if v not in d2.values():
d2[k]=v
print(d1)
print(d2)
email_dict={'naresh':'[email protected]',
'suresh':'[email protected]',
'kishore':'[email protected]',
'ramesh':'[email protected]'}
print(prod)
emp_dict={1:('naresh',5000),2:('suresh',6000),3:('ramesh',7000)}
print(emp_dict)
empno=int(input("Enter employee number to update "))
if empno in emp_dict:
d=list(emp_dict[empno])
if d[1]<25000:
d[1]=d[1]+1000
emp_dict[empno]=tuple(d)
print(emp_dict)
emp={1:("Amit",25000),2:("Suman",30000),3:("Ravi",36000)}
for key,value in emp.items():
if value[1]>25000:
print(key,value)
print(d1)
stud={}
for i in range(5):
rollno=int(input("Enter rollno "))
name=input("Enter Name ")
sub1=int(input("Enter Subject1 Marks "))
sub2=int(input("Enter Subject2 Marks "))
sub3=int(input("Enter Subject3 Marks "))
stud[rollno]=[name,sub1,sub2,sub3]
for rollno,list1 in stud.items():
print(rollno,list1,sum(list1[1:]))
>>> dict1={1:10,2:20,3:30,4:40,5:50}
>>> print(dict1)
{1: 10, 2: 20, 3: 30, 4: 40, 5: 50}
>>> v1=dict1.pop(1)
>>> print(dict1)
{2: 20, 3: 30, 4: 40, 5: 50}
>>> print(v1)
10
>>> v2=dict1.pop(4)
>>> print(v2)
40
>>> print(dict1)
{2: 20, 3: 30, 5: 50}
>>> v3=dict1.pop(1)
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
v3=dict1.pop(1)
KeyError: 1
>>> v3=dict1.pop(1,None)
>>> print(v3)
None
popitem()
Remove and return a (key, value) pair from the dictionary. Pairs are
returned in LIFO order.
popitem() is useful to destructively iterate over a dictionary, as often
used in set algorithms. If the dictionary is empty,
calling popitem() raises a KeyError.
Example:
stack={101:'nk',
102:'suresh',
103:'ramesh',
104:'kishore'}
print(stack)
item1=stack.popitem()
print(stack)
print(item1)
item2=stack.popitem()
print(stack)
print(item2)
Output:
{101: 'nk', 102: 'suresh', 103: 'ramesh', 104: 'kishore'}
{101: 'nk', 102: 'suresh', 103: 'ramesh'}
(104, 'kishore')
{101: 'nk', 102: 'suresh'}
(103, 'ramesh')
clear()
Remove all items from the dictionary.
>>> d1=dict(zip(range(1,6),range(10,60,10)))
>>> print(d1)
{1: 10, 2: 20, 3: 30, 4: 40, 5: 50}
>>> d1.clear()
>>> print(d1)
{}
fromkeys(iterable[, value])
Create a new dictionary with keys from iterable and values set
to value.
>>> sales=dict.fromkeys(range(2000,2011),None)
>>> print(sales)
{2000: None, 2001: None, 2002: None, 2003: None, 2004: None, 2005:
None, 2006: None, 2007: None, 2008: None, 2009: None, 2010: None}
>>> sales[2009]=10000
>>> print(sales)
{2000: None, 2001: None, 2002: None, 2003: None, 2004: None, 2005:
None, 2006: None, 2007: None, 2008: None, 2009: 10000, 2010: None}
>>> stud=dict.fromkeys(range(1,11),None)
>>> print(stud)
{1: None, 2: None, 3: None, 4: None, 5: None, 6: None, 7: None, 8:
None, 9: None, 10: None}
>>> stud[1]="nk"
>>> print(stud)
{1: 'nk', 2: None, 3: None, 4: None, 5: None, 6: None, 7: None, 8:
None, 9: None, 10: None}
>>> stud[2]="suresh"
>>> print(stud)
{1: 'nk', 2: 'suresh', 3: None, 4: None, 5: None, 6: None, 7: None, 8:
None, 9: None, 10: None}
update([other])
Update the dictionary with the key/value pairs from other,
overwriting existing keys. Return None.
This method performs two operations
1. Adding, if key not exists in other
2. Update value, if key exist in other
Example:
d1={1:10,2:20,3:30,4:40,5:50}
print(f'Before Update {d1}')
d2={6:60,7:70,8:80,2:90,4:80}
d1.update(d2)
print(f'After Update {d1}')
Output:
Before Update {1: 10, 2: 20, 3: 30, 4: 40, 5: 50}
After Update {1: 10, 2: 90, 3: 30, 4: 80, 5: 50, 6: 60, 7: 70, 8: 80}
d | other
Create a new dictionary with the merged keys and values
of d and other, which must both be dictionaries. The values
of other take priority when d and other share keys.
stud_dict1={'nk':'python',
'suresh':'java',
'ramesh':'oracle'}
stud_dict2={'kishore':'java',
'ramesh':'c++'}
stud_dict=stud_dict1|stud_dict2
print(stud_dict1)
print(stud_dict2)
print(stud_dict)
Output:
{'nk': 'python', 'suresh': 'java', 'ramesh': 'oracle'}
{'kishore': 'java', 'ramesh': 'c++'}
{'nk': 'python', 'suresh': 'java', 'ramesh': 'c++', 'kishore': 'java'}
https://csiplearninghub.com/programs-on-dictionary-in-python-
class-11/
dict1={1:10,2:20,3:30,4:40,5:50}
print(f'Before Deleting {dict1}')
key=int(input("Enter any key "))
if key in dict1:
del dict1[key]
print(f'After Deleting {dict1}')
else:
print(f'{key} not found')
Extract Unique values dictionary values
Sometimes, while working with data, we can have problem in which
we need to perform the extraction of only unique values from
dictionary values list. This can have application in many domains
such as web development
Input:
The original dictionary is : {'gfg': [5, 6, 7, 8], 'is': [10, 11, 7, 5], 'best': [6,
12, 10, 8], 'for': [1, 2, 5]}
Output:
The unique values list is : [1, 2, 5, 6, 7, 8, 10, 11, 12]
dict1={'gfg': [5, 6, 7, 8], 'is': [10, 11, 7, 5], 'best': [6, 12, 10, 8], 'for': [1, 2,
5]}
list1=[]
for a in dict1.values():
list1.extend(a)
list1=list(set(list1))
print(list1)
Input
List1=[{"name": "Nandini", "age": 20},
{"name": "Manjeet", "age": 20},
{"name": "Nikhil", "age": 19}]
Output:
The list printed sorting by age:
[{'age': 19, 'name': 'Nikhil'}, {'age': 20, 'name': 'Nandini'}, {'age': 20,
'name': 'Manjeet'}]
print(list1)
list2=sorted(list1,key=itemgetter("age"))
print(list2)
list3=sorted(list1,key=itemgetter("name","age"))
print(list3)
Input:
The original dictionary is : {‘name’: [‘Jan’, ‘Feb’, ‘March’], ‘month’:
[1, 2, 3]}
Output:
Flattened dictionary : {1: ‘Jan’, 2: ‘Feb’, 3: ‘March’}
contacts={}
while True:
print("1.Add")
print("2.Update")
print("3.Remove")
print("4.Search")
print("5.List")
print("6.Exit")
opt=int(input("Enter your option "))
if opt==1:
name=input("Name ")
if name not in contacts:
mobileno=int(input("MobileNo "))
contacts[name]=mobileno
print("contact added...")
else:
print(f'{name} exists')
elif opt==2:
name=input("Name ")
if name in contacts:
mobileno=int(input("MobileNo "))
contacts[name]=mobileno
print("contact updated...")
else:
print(f'{name} is not found')
elif opt==3:
name=input("Name ")
if name in contacts:
del contacts[name]
print("contact deleted...")
else:
print(f'{name} is not found')
elif opt==4:
name=input("Name ")
if name in contacts:
print(f'{name} ---> {contacts[name]}')
else:
print(f'{name} is not found')
elif opt==5:
for name,mobileno in contacts.items():
print(f'{name}--->{mobileno}')
elif opt==6:
break
Output:
1.Add
2.Update
3.Remove
4.Search
5.List
6.Exit
Enter your option 1
Name nk
MobileNo 8877644556
contact added...
1.Add
2.Update
3.Remove
4.Search
5.List
6.Exit
Enter your option 1
Name suresh
MobileNo 9988977889
contact added...
1.Add
2.Update
3.Remove
4.Search
5.List
6.Exit
Enter your option 5
nk--->8877644556
suresh--->9988977889
1.Add
2.Update
3.Remove
4.Search
5.List
6.Exit
Dictionary Comprehension
We can create dictionary using dictionary comprehension.
Comprehension is a single line statement, where for loop and if are
included within curly braces.
Example:
# Creating dictionary using dictionary comprehension
Output:
{65: 'A', 66: 'B', 67: 'C', 68: 'D', 69: 'E', 70: 'F', 71: 'G', 72: 'H', 73: 'I', 74: 'J',
75: 'K', 76: 'L', 77: 'M', 78: 'N', 79: 'O', 80: 'P', 81: 'Q', 82: 'R', 83: 'S', 84: 'T',
85: 'U', 86: 'V', 87: 'W', 88: 'X', 89: 'Y', 90: 'Z'}
A
{97: 'a', 98: 'b', 99: 'c', 100: 'd', 101: 'e', 102: 'f', 103: 'g', 104: 'h', 105: 'i',
106: 'j', 107: 'k', 108: 'l', 109: 'm', 110: 'n', 111: 'o', 112: 'p', 113: 'q', 114: 'r',
115: 's', 116: 't', 117: 'u', 118: 'v', 119: 'w', 120: 'x', 121: 'y', 122: 'z'}
{1: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 2: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20], 3: [3, 6,
9, 12, 15, 18, 21, 24, 27, 30], 4: [4, 8, 12, 16, 20, 24, 28, 32, 36, 40], 5: [5,
10, 15, 20, 25, 30, 35, 40, 45, 50]}
Full Stack Python (Part-55)
Dictionary Comprehension
We can create dictionary using dictionary comprehension.
Comprehension is a single line statement, where for loop and if are
included within curly braces.
Example:
# Creating dictionary using dictionary comprehension
Output:
{65: 'A', 66: 'B', 67: 'C', 68: 'D', 69: 'E', 70: 'F', 71: 'G', 72: 'H', 73: 'I', 74: 'J',
75: 'K', 76: 'L', 77: 'M', 78: 'N', 79: 'O', 80: 'P', 81: 'Q', 82: 'R', 83: 'S', 84: 'T',
85: 'U', 86: 'V', 87: 'W', 88: 'X', 89: 'Y', 90: 'Z'}
A
{97: 'a', 98: 'b', 99: 'c', 100: 'd', 101: 'e', 102: 'f', 103: 'g', 104: 'h', 105: 'i',
106: 'j', 107: 'k', 108: 'l', 109: 'm', 110: 'n', 111: 'o', 112: 'p', 113: 'q', 114: 'r',
115: 's', 116: 't', 117: 'u', 118: 'v', 119: 'w', 120: 'x', 121: 'y', 122: 'z'}
{1: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 2: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20], 3: [3, 6,
9, 12, 15, 18, 21, 24, 27, 30], 4: [4, 8, 12, 16, 20, 24, 28, 32, 36, 40], 5: [5,
10, 15, 20, 25, 30, 35, 40, 45, 50]}
Syntax2: {key:value for variable in iterable if test}
This syntax allows adding key and values based on condition or test.
Example:
grade_dict={'nk':'A',
'suresh':'B',
'ramesh':'A',
'rajesh':'A',
'kishore':'B'}
print(grade_dict)
gradeA_dict={name:grade for name,grade in grade_dict.items() if
grade=='A'}
gradeB_dict={name:grade for name,grade in grade_dict.items() if
grade=='B'}
print(gradeA_dict)
print(gradeB_dict)
Output:
{'nk': 'A', 'suresh': 'B', 'ramesh': 'A', 'rajesh': 'A', 'kishore': 'B'}
{'nk': 'A', 'ramesh': 'A', 'rajesh': 'A'}
{'suresh': 'B', 'kishore': 'B'}
Example:
sales_dict={2000:45000,
2001:35000,
2002:25000,
2003:22000,
2004:47000,
2005:38000,
2006:65000,
2007:75000}
print(sales_dict)
sales_dict1={year:s for year,s in sales_dict.items() if s<50000}
sales_dict2={year:s for year,s in sales_dict.items() if s>=50000}
print(sales_dict1)
print(sales_dict2)
Output:
{2000: 45000, 2001: 35000, 2002: 25000, 2003: 22000, 2004: 47000, 2005:
38000, 2006: 65000, 2007: 75000}
{2000: 45000, 2001: 35000, 2002: 25000, 2003: 22000, 2004: 47000, 2005:
38000}
{2006: 65000, 2007: 75000}
Example:
>>> dict1={num:num**2 for num in range(1,11)}
>>> print(dict1)
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100}
>>>
Example:
# Create dictionary to store details of n players
Output:
Enter how many players ?3
Enter Name rohit
Score 50
Enter Name virat
Score 70
Enter Name shubham
Score 10
rohit--->50
virat--->70
shubham--->10
What is difference between list, set and dictionary?
What is function?
A function is small program within program.
A function is named block, which contain set of instructions to
perform some operations.
A function is small piece of program within program.
Functions are building blocks of procedural oriented programming.
Advantage of functions
1. Modularity: modularity is nothing but dividing programming
code according their functionality into small pieces
2. Reusability: functions are reusable code components, once
function is created that can be used one or more than one
time.
3. Simple/Readability: Easy to understand
4. Efficient: functions increase the performance of program by
decreasing code size.
def <function-name>([parameters]):
‘’’doc string’’’
statement-1
statement-2
def <function-name>([parameters]):
‘’’doc string’’’
statement-1
statement-2
Example:
print("Welcome")
def sayHello():
print("Hello, This is my first function")
Example:
def fun1():
print("inside fun1")
def fun2():
print("inside fun2")
def fun3():
print("inside fun3")
fun1()
fun2()
fun3()
Output:
inside fun1
inside fun2
inside fun3
Example:
def fun1():
print("function without parameters")
fun1()
fun1(10)
Output:
Traceback (most recent call last):
File "C:\Users\nit\PycharmProjects\pythonProject3\test3.py", line 6,
in <module>
fun1(10)
TypeError: fun1() takes 0 positional arguments but 1 was given
function without parameters
Example:
def drawLine():
for i in range(20):
print("*",end='')
print()
drawLine()
print("Python")
drawLine()
print("Programming Language")
drawLine()
Output:
********************
Python
********************
Programming Language
********************
Local Variables
A variable created inside function is called local variable. This
variable is used within function, but cannot accessed outside the
function.
Example:
def add():
n1=int(input("enter first number"))
n2=int(input("enter second number"))
n3=n1+n2
print(f'sum of {n1} and {n2} is {n3}')
add()
Output:
enter first number10
enter second number20
sum of 10 and 20 is 30
More than one function can have local variable with same name.
Example:
def fun1():
x=100 # Local variable
print(f'{x} of fun1')
def fun2():
x=200 # Local variable
print(f'{x} of fun2')
fun1()
fun2()
fun1()
Output:
100 of fun1
200 of fun2
100 of fun1
Global Variable
A variable created outside function is called global variable. Global
variables are created to share data between more than one
function.
Example:
num1=100 # Global variable
num2=200 # Global variable
def add():
print(f'sum of {num1} and {num2} is {num1+num2}')
def sub():
print(f'diff of {num1} and {num2} is {num1-num2}')
add()
sub()
Output:
sum of 100 and 200 is 300
diff of 100 and 200 is -100
Example:
x=100 # Global variable
def fun1():
y=200 # Local variable
print(f'Global variable x={x}')
print(f'Local variable y={y}')
def fun2():
z=300 # Local Variable
x=500 # Local Variable
print(f'Local variable z={z}')
print(f'Local variable x={x}')
fun1()
fun2()
Output:
Global variable x=100
Local variable y=200
Local variable z=300
Local variable x=500
Global variables can be accessed within function directly but
cannot modify or update directly.
Example
x=100 # Global variable
def fun1():
print(x)
def fun2():
x=500
print(x)
fun1()
fun2()
fun1()
Output
100
500
100
global keyword
global keyword is used to access and modify global variables within
function. Without global keyword a function can access global
variables but cannot modify or update.
Example:
a=100 # Global Variable
def fun1():
print(a)
def fun2():
global a
a=500
print(a)
fun1()
fun2()
fun1()
Output:
100
500
500
Example:
base=0.0 # Global Variable
height=0.0 # Global Variable
def read():
global base,height
base=float(input("Enter Base of Triangle "))
height=float(input("Enter Height of Triangle "))
def findArea():
a=0.5*base*height
print(f'Area of triangle is {a:.2f}')
read()
findArea()
Output:
Enter Base of Triangle 1.5
Enter Height of Triangle 1.9
Area of triangle is 1.42
Example:
x=100 # Global Variable
def fun1():
x=200 # Local Variable
y=300 # Local Variable
print(x)
print(y)
global x
print(x)
fun1()
Output:
global x
^^^^^^^^
SyntaxError: name 'x' is used prior to global declaration
globals()
This function return global dictionary object. This global dictionary
object contains global names (variables, function name,…)
fun1()
print(x)
Output:
200
300
100
900
Full Stack Python (Part-57)
Syntax:
def <function-name>(param-name1,param-name2,param-
name3,..):
statement-1
statement-2
Example:
def power(num,p):
res=num**p
print(res)
power(5,2)
power(6,3)
power(8,2)
Output
25
216
64
Example:
def add(a,b):
c=a+b
print(c)
add(100,200)
add(1.5,2.5)
add(1+2j,1+3j)
add("python","language")
Output:
300
4.0
(2+5j)
pythonlanguage
Example:
def fun1(a:int,b:int):
print(a,b)
fun1(100,200)
fun1(1.5,2.5)
Output
100 200
1.5 2.5
fun1(10,20,30,40)
fun1(c=100,a=500,d=600,b=200)
Output:
10 20 30 40
500 200 100 600
Example:
def maximum(a,b):
if a>b:
print(f'{a} is max')
else:
print(f'{b} is max')
def add(a,b):
c=a+b
print(c)
maximum(100,200)
maximum(300,200)
m1=max(100,200)
add(100,200)
res=sum((100,200))
print(res)
Output:
200 is max
300 is max
300
300
return keyword
return is keyword or passes control statement or branching
statement. This keyword is used inside function to return value.
Return keyword, after returning value, it terminates execution of
function.
Example:
def simple_interest(amt,t,r):
si=(amt*t*r)/100
return si
res1=simple_interest(5000,12,2.0)
print(f'Simple interest is {res1:.2f}')
Output:
Simple interest is 1200.00
Example:
def fun1():
return 10
return 20
return 30
a=fun1()
print(a)
Output:
10
Example:
def fun1():
return 10,20,30,40,50
a=fun1()
print(a)
Output:
(10, 20, 30, 40, 50)
Example:
def factorial(num:int)->int:
fact=1
for i in range(1,num+1):
fact=fact*i
return fact
Output:
Enter any number 4
factorial of 4 is 24
Output:
Enter any string abc
abc
ABC
Example:
users={'nk':'n123','ramesh':'r321','kishore':'k678'}
def signin(u,p):
if u in users and users[u]==p:
return True
else:
return False
user=input("UserName ")
pwd=input("Password ")
if signin(user,pwd):
print(f'{user} welcome')
else:
print("invalid username or password ")
Output:
UserName nk
Password x234
invalid username or password
Syntax:
def <function-name>(param-name=value,param-name=value,..):
statement-1
statement-2
Example
def fun1(a=100):
print(a)
fun1()
fun1(200)
Output
100
200
Default parameters or arguments (OR) optional arguments
Syntax:
def <function-name>(param-name=value,param-name=value,..):
statement-1
statement-2
Example
def fun1(a=100):
print(a)
fun1()
fun1(200)
Output
100
200
Example:
def drawLine(ch='*',length=40):
for i in range(length):
print(ch,end='')
print()
drawLine()
drawLine("$")
drawLine(length=20)
drawLine("^",50)
Output:
****************************************
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
********************
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
^
Example:
def sortData(a,reversed=False):
if reversed:
for i in range(len(a)):
for j in range(len(a)-1):
if a[j]<a[j+1]:
a[j],a[j+1]=a[j+1],a[j]
else:
for i in range(len(a)):
for j in range(len(a)-1):
if a[j]>a[j+1]:
a[j],a[j+1]=a[j+1],a[j]
list1=[5,2,6,3,1,4]
print(f'Before Sorting List is {list1}')
sortData(list1)
print(f'After Sorting in Ascending Order {list1}')
sortData(list1,reversed=True)
print(f'After Sorting in Descending Order {list1}')
Output
Before Sorting List is [5, 2, 6, 3, 1, 4]
After Sorting in Ascending Order [1, 2, 3, 4, 5, 6]
After Sorting in Descending Order [6, 5, 4, 3, 2, 1]
def fun2():
list1=[10,20,30]
print(f'Before calling function {list1}')
fun1(list1)
print(f'After calling function {list1}')
fun2()
Output:
Before calling function [10, 20, 30]
After calling function [99, 20, 30, 100]
Example:
def simple_interest(amt,t,r=1.5):
si=(amt*t*r)/100
return si
res1=simple_interest(5000,12)
print(f'Simple Interest is {res1:.2f}')
res2=simple_interest(9000,24,2.5)
print(f'Simple Interest is {res2:.2f}')
Output:
Simple Interest is 900.00
Simple Interest is 5400.00
Example:
def fun1(a=100,b):
print(a,b)
Output:
def fun1(a=100,b):
^
SyntaxError: parameter without a default follows parameter with a
default
Example:
def fun1(*a):
print(type(a))
print(a)
fun1()
fun1(10)
fun1(100,200,300,400,500)
fun1(101,"ramesh","python")
Output
<class 'tuple'>
()
<class 'tuple'>
(10,)
<class 'tuple'>
(100, 200, 300, 400, 500)
<class 'tuple'>
(101, 'ramesh', 'python')
Example:
def add(*values):
s=0
for value in values:
s=s+value
return s
res1=add(10,20)
res2=add(10,20,30,40,50)
print(f'Sum of two numbers {res1}')
print(f'Sum of five numbers {res2}')
Output:
Sum of two numbers 30
Sum of five numbers 150
Example:
def maximum(*values):
m=0
for i in range(len(values)):
if i==0:
m=values[i]
elif values[i]>m:
m=values[i]
return m
m1=maximum(10,20)
m2=maximum(40,20,10)
print(f'Maximum of two values {m1}')
print(f'Maximum of three values {m2}')
Output:
Maximum of two values 20
Maximum of three values 40
Example:
def fun1(a,b=10,*c):
print(a,b,c)
def fun2(a,*c,b=10):
print(a,b,c )
def fun3(*a,b):
print(a,b)
fun1(100)
fun1(100,200)
fun1(100,200,300,400,500,600)
fun2(10)
fun2(10,20,30,40,50,60,70)
fun2(10,20,30,40,50,b=90)
fun3(10,20,30,40,50,b=90)
Output:
100 10 ()
100 200 ()
100 200 (300, 400, 500, 600)
10 10 ()
10 10 (20, 30, 40, 50, 60, 70)
10 90 (20, 30, 40, 50)
(10, 20, 30, 40, 50) 90
Full Stack Python (Part-59)
Example:
def fun1(**kwargs):
print(type(kwargs))
print(kwargs)
fun1()
fun1(a=10)
fun1(rohit=100,virat=90)
Output:
<class 'dict'>
{}
<class 'dict'>
{'a': 10}
<class 'dict'>
{'rohit': 100, 'virat': 90}
Example:
def fun1(**a,**b):
print(a,b)
def fun2(*a,*b):
print(a,b)
Output:
File "C:\Users\nit\PycharmProjects\pythonProject3\test34.py", line 1
def fun1(**a,**b):
^^
SyntaxError: arguments cannot follow var-keyword argument
Example:
def add(*varg,**kwargs):
s=0
for value in varg:
s=s+value
return s
res1=add(10,20,30,40,50)
res2=add(a=10,b=20,c=30,d=40)
print(res1)
print(res2)
res3=add(10,20,30,a=40,b=50)
print(res3)
Output
150
100
150
Example:
def displayStudInfo(**kwargs):
for name,course in kwargs.items():
print(f'{name}-->{course}')
def displayTuple(*vararg):
for value in vararg:
print(value)
stud_dict={'nk':'python', 'suresh':'java','ramesh':'oracle','kishore':'c++'}
displayStudInfo(**stud_dict)
t1=(10,20,30,40,50)
displayTuple(*t1)
Output:
nk-->python
suresh-->java
ramesh-->oracle
kishore-->c++
10
20
30
40
50
Example:
def fun1(a,b,c):
print(a,b,c)
def fun2(**kwargs):
print(kwargs['a'],kwargs['b'],kwargs['c'])
fun1(a=10,b=20,c=30)
fun2(a=10,b=20,c=30)
Output:
10 20 30
10 20 30
Example:
def findResult(**kwargs):
print(f'Rollno {kwargs["rollno"]}')
print(f'Name {kwargs["name"]}')
print(f'Subject1 {kwargs["s1"]}')
print(f'Subject2 {kwargs["s2"]}')
if kwargs['s1']<40 or kwargs['s2']<40:
print("Result Fail ")
else:
print("Result Pass")
findResult(rollno=1,name="nk",s1=60,s2=70)
findResult(rollno=2,name="suresh",s1=30,s2=90)
Output:
Rollno 1
Name nk
Subject1 60
Subject2 70
Result Pass
Rollno 2
Name suresh
Subject1 30
Subject2 90
Result Fail
Example:
def fun1(a,b=10,*c,**d):
print(a,b,c,d,sep="\n")
fun1(100)
fun1(100,200)
fun1(100,200,300,400,500)
fun1(10,x=100,y=200)
fun1(a=100,b=200,x=300,y=400,z=500)
fun1(100,200,300,400,500,x=1,y=2,z=3)
Output:
100
10
()
{}
100
200
()
{}
100
200
(300, 400, 500)
{}
10
10
()
{'x': 100, 'y': 200}
100
200
()
{'x': 300, 'y': 400, 'z': 500}
100
200
(300, 400, 500)
{'x': 1, 'y': 2, 'z': 3}
Nested Function
Syntax:
def <outer-function-name>([parameters]):
statements
def <inner-function>/<nested function>([parameters]):
statements
Example:
def fun1(): # outer function
print("inside outer function")
def fun2():
print("inside inner function")
fun2()
fun1()
Output:
inside outer function
inside inner function
Example:
def fun1():
def fun2():
print("fun2")
def fun3():
print("fun3")
def fun4():
print("fun4")
print("inside fun1")
fun2()
fun4()
fun3()
fun1()
Output:
inside fun1
fun2
fun4
fun3
Inner function can access data of outer function but outer function
cannot access data of inner function.
Example:
def fun1():
a=100
def fun2():
print(a)
def fun3():
a=500 # Local variable of fun3
print(a)
fun2()
fun3()
print(a)
fun1()
Output:
100
500
100
nonlocal keyword
nonlocal variable-name
Example:
def fun1():
a=100
def fun2():
print(a)
def fun3():
nonlocal a
a=500
print(a)
fun2()
fun3()
print(a)
fun1()
Output
100
500
500
LEGB Rule
The LEGB rule is a kind of name lookup procedure, which determines
the order in which Python looks up names.
L Local
E Enclosed Block
G Global
B Built-ins module
Python's name resolution is sometimes called the LEGB rule, after the
scope names: When you use an unqualified name inside a function,
Python searches three scopes—the local (L), Enclosed Block (E) then
the global (G), and then the built-in (B)—and stops at the first place
the name is found.
fun1()
Output:
300
200
100
__main__
Example:
def calculator(num1,num2,opr):
res=None
def add():
nonlocal res
res=num1+num2
def sub():
nonlocal res
res=num1-num2
def multiply():
nonlocal res
res=num1*num2
def div():
nonlocal res
res=num1/num2
if opr=='+':
add()
if opr=='-':
sub()
if opr=='*':
multiply()
if opr=='/':
div()
return res
Output:
Enter First Number 5
Enter Second Number 2
Enter Operator -
Result is 3
Decorator function
Example:
def drawStars(a):
def draw():
print("*"*40)
a()
print("*"*40)
return draw
@drawStars
def display():
print("PYTHON")
@drawStars
def studInfo():
print("Rollno :101")
print("Name : Rajesh")
display()
studInfo()
# PVM Process
x=drawStars(display)
x()
Output:
****************************************
PYTHON
****************************************
****************************************
Rollno :101
Name : Rajesh
****************************************
****************************************
****************************************
PYTHON
****************************************
****************************************
Example:
def smartDiv(f):
def newDiv(n1,n2):
if n2==0:
return 0
else:
return f(n1,n2)
return newDiv
@smartDiv
def div(n1,n2):
n3=n1/n2
return n3
Output:
enter first number 6
enter second number 0
6/0=0.00
@decorator2
@decorator1
def function([parameters]):
statement-1
statement-2
Example:
def drawDollar(f):
def draw2():
print("$"*30)
f()
print("$"*30)
return draw2
def drawStars(f):
def draw1():
print("*"*30)
f()
print("*"*30)
return draw1
@drawDollar
@drawStars
def display():
print("PYTHON")
display()
Output:
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
******************************
PYTHON
******************************
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
Full Stack Python (Part-61)
Closure function
Example:
def calculator():
n1=int(input("Enter First Number "))
n2=int(input("Enter Second Number "))
def add():
n3=n1+n2
return n3
def sub():
n3=n1-n2
return n3
opr=input("Enter Operator ")
if opr=='+':
print(f'sum of {n1}+{n2}={add()}')
if opr=='-':
print(f'diff of {n1}-{n2}={sub()}')
calculator()
Output
Enter First Number 4
Enter Second Number 2
Enter Operator -
diff of 4-2=2
Example:
def power(num):
def findpow(p):
return num**p
return findpow
fp3=power(3)
res1=fp3(2)
res2=fp3(4)
print(res1,res2)
fp5=power(5)
res3=fp5(3)
res4=fp5(2)
print(res3,res4)
res5=fp3(6)
print(res5)
Output
9 81
125 25
729
Example
def draw(ch):
def drawLine(n):
print(ch*n)
return drawLine
drawstars=draw("*")
drawdollar=draw("$")
drawstars(10)
drawstars(20)
drawdollar(15)
drawdollar(40)
Output
**********
********************
$$$$$$$$$$$$$$$
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
Example:
def calculator(n1,n2):
def operation(opr):
if opr=='+':
return n1+n2
elif opr=='-':
return n1-n2
elif opr=='*':
return n1*n2
elif opr=='/':
return n1/n2
return operation
c1=calculator(5,2)
r1=c1('+')
r2=c1('-')
print(r1,r2 )
c2=calculator(10,4)
r3=c2('+')
r4=c2('*')
print(r3,r4)
Output:
73
14 40
Example:
def greet(msg):
def display(name):
print(name+" "+msg)
return display
greet1=greet("Hello")
greet1("nk")
greet1("suresh")
greet2=greet("Bye")
greet2("kishore")
greet2("ramesh")
greet1("rajesh")
Output:
nk Hello
suresh Hello
kishore Bye
ramesh Bye
rajesh Hello
Generator
Example:
def fun1(): # Generator Function
yield 4
yield 9
yield 18
yield 48
yield 39
a=fun1() # Creating Generator iterator object
v1=next(a)
v2=next(a)
print(v1)
print(v2)
for v in a:
print(v )
c=range(1,11)
for v in c:
print(v)
Output:
4
9
18
48
39
[4, 9, 18, 48, 39]
1
2
3
4
5
6
7
8
9
10
Example:
def reviter(s):
s=s[::-1]
for x in s:
yield x
list1=[10,20,30,40,50]
a=iter(list1) # iterator object
for x in a:
print(x,end=' ')
print()
Output:
10 20 30 40 50
50 40 30 20 10
Example:
def primeGenerator(start,stop):
for num in range(start,stop+1):
c=0
for i in range(1,num+1):
if num%i==0:
c+=1
if c==2:
yield num
Output:
5
7
11 13 17 19
Example:
even=(value for value in range(1,51) if value%2==0) # creating
generator iterator object using expression
for value in even:
print(value,end=' ')
print()
odd=(value for value in range(1,51) if value%2!=0)
for value in odd:
print(value,end=' ')
print()
list1=[10,20,30,40,50,60]
reviter=(value for value in list1[::-1])
for value in reviter:
print(value,end=' ')
print()
list1=
[1,3,6,8,9,24,56,89,34,12,11,13,16,78,49,85,76,97,37,65,45,54,34,32]
even=(value for value in list1 if value%2==0)
for value in even:
print(value,end=' ')
print()
odd=(value for value in list1 if value%2!=0)
for value in odd:
print(value,end=' ')
Output:
2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50
1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49
60 50 40 30 20 10
6 8 24 56 34 12 16 78 76 54 34 32
1 3 9 89 11 13 49 85 97 37 65 45
Lambda Functions or Lambda Expressions
Syntax:
Variable=lambda [parameters]:expression/statement
Example:
a=lambda:print('Hello')
a()
add=lambda a,b:a+b
sub=lambda a,b:a-b
multiply=lambda a,b:a*b
res1=add(10,20)
res2=add(10,5)
res3=sub(5,2)
res4=multiply(6,3)
print(res1,res2,res3,res4)
Output:
Hello
30 15 3 18
Example:
def calculator(n1,n2,f):
n3=f(n1,n2)
return n3
res1=calculator(10,20,lambda a,b:a+b)
print(res1)
res2=calculator(5,2,lambda a,b:a-b)
res3=calculator(5,8,lambda a,b:a*b)
res4=calculator(5,3,lambda a,b:a**b)
print(res2,res3,res4,sep="\n")
Output:
30
3
40
125
filter,map,reduce
filter(function, iterable)
Construct an iterator from those elements of iterable for
which function is true. iterable may be either a sequence, a
container which supports iteration, or an iterator. If function is None,
the identity function is assumed, that is, all elements of iterable that
are false are removed.
Example:
list1=
[1,3,6,8,9,24,56,89,34,12,11,13,16,78,49,85,76,97,37,65,45,54,34,32]
a=filter(lambda value:value%2==0,list1)
for value in a:
print(value,end=' ')
print()
b=filter(lambda value:value%2!=0,list1)
for value in b:
print(value,end=' ')
Output:
6 8 24 56 34 12 16 78 76 54 34 32
1 3 9 89 11 13 49 85 97 37 65 45
filter(function, iterable)
Construct an iterator from those elements of iterable for
which function is true. iterable may be either a sequence, a
container which supports iteration, or an iterator. If function is None,
the identity function is assumed, that is, all elements of iterable that
are false are removed.
Example:
list1=
[1,3,6,8,9,24,56,89,34,12,11,13,16,78,49,85,76,97,37,65,45,54,34,32]
a=filter(lambda value:value%2==0,list1)
for value in a:
print(value,end=' ')
print()
b=filter(lambda value:value%2!=0,list1)
for value in b:
print(value,end=' ')
Output:
6 8 24 56 34 12 16 78 76 54 34 32
1 3 9 89 11 13 49 85 97 37 65 45
Example:
names_list=["nk","suresh","kishore",'raman',"kiran"]
a=filter(lambda s:s[-1]=='h',names_list)
for name in a:
print(name)
Output:
nk
suresh
map(function, iterable, *iterables)
Return an iterator that applies function to every item of iterable,
yielding the results. If additional iterables arguments are
passed, function must take that many arguments and is applied to
the items from all iterables in parallel. With multiple iterables, the
iterator stops when the shortest iterable is exhausted.
Example:
list1=[1,2,3,4,5]
a=map(lambda num:num**2,list1)
for value in a:
print(value,end=' ')
print()
list2=["10","20","30","40","50"]
b=map(lambda value:int(value),list2)
list3=list(b)
print(list2)
print(list3)
list4=[1,2,3,4,5]
list5=[10,20,30,40,50]
c=map(lambda value1,value2:value1+value2,list4,list5)
list6=list(c)
print(list4)
print(list5)
print(list6)
names_list=["nk","suresh","kishore"]
d=map(lambda s:s.upper(),names_list)
names_list1=list(d)
print(names_list,names_list1,sep="\n")
Output:
1 4 9 16 25
['10', '20', '30', '40', '50']
[10, 20, 30, 40, 50]
[1, 2, 3, 4, 5]
[10, 20, 30, 40, 50]
[11, 22, 33, 44, 55]
['nk', 'suresh', 'kishore']
['NK', 'SURESH', 'KISHORE']
Example:
import functools
list1=[1,2,3,4,5,6,7,8,9,10]
res1=functools.reduce(lambda x,y:x+y,list1)
print(res1)
res2=functools.reduce(lambda x,y:x+y,list1,100)
print(res2)
res3=functools.reduce(lambda x,y:x if x>y else y,list1)
print(res3)
res4=functools.reduce(lambda x,y:x if x<y else y,list1)
print(res4)
res5=functools.reduce(lambda x,y:str(x)+str(y),list1)
print(res5)
Output
55
155
10
1
12345678910
Example:
import sys
def sayHello():
print("Hello")
sayHello() # recursive call
s=sys.getrecursionlimit()
print(s)
sys.setrecursionlimit(50)
s=sys.getrecursionlimit()
print(s )
s=sys.setrecursionlimit(2000)
s=sys.getrecursionlimit()
print(s)
sayHello()
Output:
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Recursion is evaluated using a data structure called stack (LIFO).
Whenever function is called or invoked, that function is pushed inside
stack, after execution of function it is popped from stack.
When function is called, the execution control switched from calling
function to called function and after execution of called function, it
returns to calling function.
# program to print 1 to 5 numbers without using looping statements
def printNum(num):
if num>1:
printNum(num-1) # Recursive Call
print(num)
def printNumRev(num):
if num<5:
printNumRev(num+1) # Recursive call
print(num)
printNum(5)
printNumRev(1)
Example:
# Write a program to find factorial of input number
def factorial(num):
if num==0:
return 1
else:
return num*factorial(num-1)
Output:
Enter any number 3
Factorial of 3 is 6
# Write a program to count digits or find length of number
res=-1
def countDigits(num):
global res
if num!=0:
countDigits(num//10)
res=res+1
Output:
Enter any number 3456
4
Example
def fun1():
print("fun1 without parameters")
def fun1(a):
print("fun1 with one parameter")
fun1(100)
Output:
fun1 with one parameter
module1.py module2.py
def fun1(): import module1,math
print("inside fun1")
def fun2(): module1.fun1()
print("inside fun2") module1.fun2()
def fun3(): module1.fun3()
print("inside fun3") module1.fun4()
def fun4(): res=math.factorial(4)
print("inside fun4") print(res)
Modules are two types
1. Reusable module
2. Executable module
module3.py module4.py
def isEven(num): import module3
return num%2==0
g=globals()
def isPrime(num): print(g)
c=0 res1=module3.factorial(4)
for i in range(1,num+1): res2=module3.isEven(9)
if num%i==0: res3=module3.isPrime(7)
c=c+1 print(res1,res2,res3)
return c==2
def factorial(num):
if num==0:
return 1
else:
return num*factorial(num-1)
Users.py Module5.py
user_dict={'naresh':'n123', import users as a
'suresh':'s321',
'ramesh':'r567'}
uname=input("UserName : ")
def login(uname,pwd): pwd=input("Password ")
if uname in user_dict and if a.login(uname,pwd):
user_dict[uname]==pwd: print(f'{uname}, welcome')
return True else:
else: print("invalid username or
return False password")
Module6.py Module7.py
x=100 # Global Variable from module6 import *
def fun1():
print("inside fun1") g=globals()
def fun2(): print(g)
print("inside fun2")
print(x)
fun1()
fun2()
Module8.py Module9.py
x=100 from module8 import x,y,fun2
y=200
z=300 print(x)
print(y)
def fun1(): fun2(
print("inside fun1")
def fun2():
print("inside fun2")
Syntax5: from <module-name> import <identifier> as <alias-name>
Module8.py Module10.py
x=100 from module8 import x as p,y as
y=200 q,fun1 as f1
z=300
If __name__==’__main__’:
Statement-1
Statement-2
Module11.py Module12.py
def fun1(): import module11
print("inside fun1")
module11.fun1()
def fun2():
print("inside fun2")
def fun3():
print("inside fun3")
if __name__=='__main__':
fun1()
fun2()
fun3()
Packages
What is package?
A package is collection of modules (.py).
A package is folder or directory, which contains .py files.
What is __init__.py?
__init__.py is a package configuration program or module.
This module is executed automatically when ever package is
imported.
Without pycharm
1. Create folder outside
2. Give name to folder
How to import modules outside package?
import package-name.module-name
from package-name import module-name
What is __init__.py?
It is a special program or module, which is executed automatically
whenever package is imported.
It is package configuration file.
Use of __init__.py
1. Creating package level variables
2. Creating package level functions
3. Creating package level classes
4. Importing modules and module content at package level
Example:
Outside the pacakge2 create a module and import pacakge2
Example:
Outside the package create module to test
Example:
Create module outside package for testing
Monkey Patching
Example:
import package1.m1
def patch():
print("this is patch function")
package1.m1.fun1=patch
package1.m1.fun1()
package1.m1.fun2()
Output:
this is patch function
fun2 of m1 module of pacakge1
pip
pip is a package-management system written in Python and is used
to install and manage software packages. The Python Software
Foundation recommends using pip for installing Python applications
and its dependencies during deployment.
Python software provides only standard libraries but does not provide
application specific libraries.
pip list
1. Encapsulation
2. Polymorphism
3. Inheritance
4. Class
5. Object
6. Abstraction
Advantage of OOP
1. Simplicity/Readability
2. Modularity
3. Reusability
4. Efficiency
5. Security
6. Extensibility
Object
In object oriented application development data is represented as
object.
Object is a real world entity.
Every object is having two characteristics.
1. Properties
2. Behavior
Advantages of encapsulation
1. Data Hiding
2. Binding
What is binding?
Linking data with related operations is called binding.
What is “self”?
Syntax:
def method-name(self,arg1,arg2,arg3,…):
statement-1
statement-2
Example:
class Car:
def start(self): # Instance method
print(self,"Car Start....")
def stop(self): # Instance method
print(self,"Car Stop....")
Output:
<__main__.Car object at 0x0000023D56541460> Car Start....
<__main__.Car object at 0x0000023D5633A390> Car Start....
<__main__.Car object at 0x0000023D56541460> Car Stop....
<__main__.Car object at 0x0000023D5633A390> Car Stop....
Example:
class List:
def append(self):
print("append method")
def remove(self):
print("remove method")
def insert(self):
print("insert method")
list1=List()
list1.append()
list1.remove()
list1.insert()
list2=List()
list2.append()
list2.insert()
list2.remove()
Output:
append method
remove method
insert method
append method
insert method
remove method
Example of instance method with parameters
class Calculator:
def add(self,n1,n2):
return n1+n2
def sub(self,n1,n2):
return n1-n2
calc1=Calculator()
res1=calc1.add(10,20)
res2=calc1.sub(10,5)
print(res1)
print(res2)
Output:
30
5
Example:
class Robo:
def talk(self,msg):
print(msg)
robo1=Robo()
robo1.talk("Hello")
robo2=Robo()
robo2.talk("Bye")
Output:
Hello
Bye
Full Stack Python (Part-69)
Inside the class instance variables bind with “self” and outside the
class binds with object name. These variables cannot be accessed
without creating object.
Example:
# Creating and accessing instance variables outside the class
class Student:
pass
Output:
101 nk
102 suresh
Constructor Method or Constructor
Constructor is defined,
1. Without parameters
2. With parameters
Syntax:
def __init__(self,[para1,para2,…]):
statement-1
statement-2
Example:
class Student:
def __init__(self):
print("student object is created...")
Output:
student object is created...
student object is created...
stud1=Student()
stud2=Student()
print(stud1.rollno,stud1.name,stud1.course)
print(stud2.rollno,stud2.name,stud2.course)
Output:
0 None None
0 None None
Example:
class Student:
def __init__(self,r,n,c):
self.rollno=r
self.name=n
self.course=c
stud1=Student(101,"nk","python")
stud2=Student(102,"suresh","java")
print(stud1.rollno,stud1.name,stud1.course)
print(stud2.rollno,stud2.name,stud2.course)
comp1=complex()
print(comp1.real,comp1.imag)
comp2=complex(1.2,2.5)
print(comp2.real,comp2.imag)
Output:
101 nk python
102 suresh java
0.0 0.0
1.2 2.5
Example:
class Date:
def __init__(self,d=0,m=0,y=0):
self.dd=d
self.mm=m
self.yy=y
d1=Date()
print(d1.dd,d1.mm,d1.yy)
d2=Date(6,1,2024)
print(d2.dd,d2.mm,d2.yy)
Output:
000
6 1 2024
Example:
class Employee:
def __init__(self,eno,en,s):
self.empno=eno
self.ename=en
self.salary=s
def printEmployee(self):
print(self.empno,self.ename,self.salary)
emp1=Employee(101,"nk",50000)
emp2=Employee(102,"suresh",60000)
#print(emp1.empno,emp1.ename,emp1.salary)
#print(emp2.empno,emp2.ename,emp2.salary)
emp1.printEmployee()
emp2.printEmployee()
Output:
101 nk 50000
102 suresh 60000
Example:
class Calculator:
def __init__(self):
self.num1=10
self.num2=5
def add(self):
return self.num1+self.num2
def sub(self):
return self.num1-self.num2
class Triangle:
def __init__(self,b=0.0,h=0.0):
self.base=b
self.height=h
def findArea(self):
a=self.base*self.height*0.5
return a
calc1=Calculator()
res1=calc1.add()
res2=calc1.sub()
print(res1,res2)
t1=Triangle(1.2,1.5)
area1=t1.findArea()
print(f'Area of triangle 1{area1:.2f}')
Output:
15 5
Area of triangle 10.90
Full Stack Python (Part-70)
Example:
class Triangle:
def __init__(self):
self.base=0.0
self.height=0.0
def setBase(self,b):
self.base=b
def setHeight(self,h):
self.height=h
def findArea(self):
return self.base*self.height*0.5
t1=Triangle()
t1.setBase(1.5)
t1.setHeight(1.7)
area1=t1.findArea()
print(f'Area of triangle is {area1:.2f}')
t1.setBase(1.2)
area2=t1.findArea()
print(f'Area of triangle is {area2:.2f}')
Output:
Area of triangle is 1.27
Area of triangle is 1.02
1. Private
2. Protected
3. Public
Private
Private members (variables and methods) of class are accessed
within class but cannot accessible outside the class.
Private members are declared prefix with __ (double score)
Data hiding in object oriented is achieved using private.
class A:
def __init__(self):
self.__x=10
self.__y=20
self.z=30
def __m1(self):
print("private method")
obja=A()
#print(obja.__x)
#print(obja.__y)
print(obja.z)
#obja.__m1()
Output:
30
Example:
class Student:
def __init__(self,r,n,c):
self.__rollno=r
self.__name=n
self.__course=c
def printStudent(self):
print(f'{self.__rollno},{self.__name},{self.__course}')
def setCourse(self,c):
self.__course=c
stud1=Student(101,"nk","python")
stud1.printStudent()
stud1.setCourse('jython')
stud1.printStudent()
Output:
101,nk,python
101,nk,jython
Protected
If members of class are protected, these members are accessible
within class and inside derived class (child class) but cannot
accessible outside the class. Protected members prefix with _ (one
underscore)
Public
Public members of class are accessible within class, child class and
outside the class. Public members are not prefix with any underscore.
Example:
class A:
def __m1(self):
print("private method")
def m2(self):
print("public method")
self.__m1()
obja=A()
#obja.__m1()
obja.m2()
Output:
public method
private method
Example:
class Account:
def __init__(self,a,c,b):
self.__accno=a
self.__cname=c
self.__balance=b
def deposit(self,t):
self.__balance=self.__balance+t
def withdraw(self,t):
if self.__balance<t:
print("Insuff Balance ")
else:
self.__balance=self.__balance-t
def getBalance(self):
return self.__balance
def printAccount(self):
print(f'{self.__accno},{self.__cname},{self.__balance}')
while True:
print("1.Create Account ")
print("2.Deposit")
print("3.Withdraw")
print("4.Find Bal")
print("5.Print Account Info")
print("6.Exit")
opt=int(input("Enter your option "))
if opt==1:
a=int(input("AccountNo :"))
c=input("CustomerName :")
b=float(input("Balance :"))
acc=Account(a,c,b)
print("Account Created...")
elif opt==2:
amt=float(input("Amount "))
acc.deposit(amt)
print("Amount Deposited...")
elif opt==3:
amt=float(input("Amount "))
acc.withdraw(amt)
elif opt==4:
bal=acc.getBalance()
print(f'Balance is {bal:.2f}')
elif opt==5:
acc.printAccount()
elif opt==6:
break
Output:
1.Create Account
2.Deposit
3.Withdraw
4.Find Bal
5.Print Account Info
6.Exit
Enter your option 1
AccountNo :101
CustomerName :nk
Balance :7000
Account Created...
Example:
# Write a program to read the scores of n players and display
class Player:
def __init__(self,n,s):
self.__name=n
self.__score=s
def getName(self):
return self.__name
def getScore(self):
return self.__score
for p in list1:
name=p.getName()
score=p.getScore()
Output:
Enter how players2
Enter Name virat
Enter Score 100
Enter Name rohit
Enter Score 200
virat,100
rohit,200
Syntax:
class <class-name>/<class-type-name>:
class-level-variable
class-level-variable
def __init__(self):
self.<object-level-variable>
self.<object-level-variable>
Example:
class A:
x=100 # class level variable
def __init__(self):
self.y=200 # instance variable or OLV
print(A.x)
obj1=A()
print(obj1.y)
obj2=A()
print(obj2.y)
print(obj1.x)
print(obj2.x)
Output:
100
200
200
100
100
Example:
class Product:
count=0
def __init__(self,n,p):
self.__name=n
self.__price=p
Product.count=Product.count+1
def printProduct(self):
print(f'{self.__name},{self.__price}')
print(Product.count)
p1=Product("mouse",100)
p2=Product("keyboard",2000)
p1.printProduct()
p2.printProduct()
print(Product.count)
Output:
0
mouse,100
keyboard,2000
2
Example:
class Account:
minBalance=5000
def __init__(self,a,n,b):
self.__accno=a
self.__cname=n
self.__balance=b
def deposit(self,t):
self.__balance=self.__balance+t
def withdraw(self,t):
if (self.__balance-t)<Account.minBalance:
print("insuff funds")
else:
self.__balance=self.__balance-t
def printAccount(self):
print(f'AccountNo: {self.__accno}')
print(f'CustomerName: {self.__cname}')
print(f'Balance: {self.__balance}')
cust1=Account(101,"nk",50000)
cust2=Account(102,"suresh",70000)
cust1.printAccount()
cust2.printAccount()
cust1.deposit(9000)
cust1.printAccount()
cust2.withdraw(68000)
cust2.withdraw(10000)
cust2.printAccount()
Output:
AccountNo: 101
CustomerName: nk
Balance: 50000
AccountNo: 102
CustomerName: suresh
Balance: 70000
AccountNo: 101
CustomerName: nk
Balance: 59000
insuff funds
AccountNo: 102
CustomerName: suresh
Balance: 60000
Class level method is bind with class name and this method can be
called without creating object.
Class level methods access only class level variables but cannot
access object level variables.
Syntax:
@classmethod
def method-name(cls,arg1,arg2,arg3,…):
statement-1
statement-2
Example:
class Student:
__count=0
@classmethod
def getStudentCount(cls):
return cls.__count
def __init__(self):
self.__rollno=0
self.__name=None
Student.__count=Student.__count+1
k=Student.getStudentCount()
print(k)
stud1=Student()
stud2=Student()
k=Student.getStudentCount()
print(k)
#print(Student.__count)
Output:
0
2
Example:
import datetime
class Person:
def __init__(self,n,a):
self.__name=n
self.__age=a
def getName(self):
return self.__name
def getAge(self):
return self.__age
@classmethod
def createPerson(cls,n,dy):
cy=datetime.date.today().year
a=cy-dy
p=Person(n,a)
return p
p1=Person("nk",40)
print(p1.getName(),p1.getAge())
p2=Person.createPerson("suresh",2000)
print(p2.getName(),p2.getAge())
Output:
nk 40
suresh 24
Example:
class Circle:
__pi=3.14
def __init__(self,x):
self.__r=x
def findArea(self):
return self.__r*self.__r*Circle.__pi
@classmethod
def setPI(cls,p):
cls.__pi=p
c1=Circle(1.5)
c2=Circle(2.5)
Circle.setPI(3.147)
area1=c1.findArea()
area2=c2.findArea()
print(f'Area of circle1 {area1:.2f}')
print(f'Area of circle2 {area2:.2f}')
Output:
Area of circle1 7.08
Area of circle2 19.67
Static method
A method defined inside class without first implicit argument is called
static method. @staticmethod decorator is used to declare method
as static. Static method defines global operation. This method does
not access class level or object level data or variables.
This method is bind with class name and can be invoked without
creating object.
Syntax:
class <class-name>:
@staticmethod
def <method-name>(arg1,arg2,arg3,…):
statement1
statement2
Static method
A method defined inside class without first implicit argument is called
static method. @staticmethod decorator is used to declare method
as static. Static method defines global operation. This method does
not access class level or object level data or variables.
This method is bind with class name and can be invoked without
creating object.
Syntax:
class <class-name>:
@staticmethod
def <method-name>(arg1,arg2,arg3,…):
statement1
statement2
Example:
class Math:
@staticmethod
def power(num,p):
return num**p
@staticmethod
def factorial(num):
if num==0:
return 1
else:
return num*Math.factorial(num-1)
@staticmethod
def isEven(num):
return num%2==0
@staticmethod
def isOdd(num):
return num%2!=0
res1=Math.power(2,4)
res2=Math.factorial(4)
res3=Math.isEven(3)
res4=Math.isOdd(4)
print(res1,res2,res3,res4)
Output:
16 24 False False
Class Reusability
1. Composition (Has-A)
2. Aggregation (Use-A)
3. Inheritance (IS-A)
Composition
In object oriented programming composition is used to define HAS-A
relationship between classes.
Composition is process of creating object of one class inside another
class.
Composition relationship always between unrelated classes.
Composition is the process of making one class as data member of
another class.
class Car:
def __init__(self):
self.e=Engine()
def carStart(self):
self.e.start()
def carStop(self):
self.e.stop()
audi=Car()
audi.carStart()
audi.carStop()
Output:
Engine Start....
Engine Stop....
Example:
class Address:
def __init__(self):
self.__street=None
self.__city=None
def readAddress(self):
self.__street=input("Street ")
self.__city=input("City ")
def printAddress(self):
print(f'{self.__street},{self.__city}')
class Person:
def __init__(self):
self.__name=None
self.__add=Address()
def readPerson(self):
self.__name=input("Name ")
self.__add.readAddress()
def printPerson(self):
print(f'{self.__name}')
self.__add.printAddress()
p1=Person()
p1.readPerson()
p1.printPerson()
Output:
Name naresh
Street ameerpet
City hyd
naresh
ameerpet,hyd
Example:
# Aggregation
class Engine:
def start(self):
print("Engine Start...")
def stop(self):
print("Engine Stop...")
class Car:
def __init__(self,eg):
self.e=eg
def carStart(self):
self.e.start()
def carStop(self):
self.e.stop()
e=Engine()
audi=Car(e)
audi.carStart()
audi.carStop()
Output:
Engine Start...
Engine Stop...
Example:
class Department:
def __init__(self,d,dn):
self.deptno=d
self.dname=dn
def getDeptno(self):
return self.deptno
def getDeptName(self):
return self.dname
class Employee:
def __init__(self,en,ena,d):
self.empno=en
self.ename=ena
self.dept=d
def printEmployee(self):
print(f'''EmployeeNo {self.empno},
EmployeeName {self.ename},
DepartmentNo {self.dept.getDeptno()},
DepartmentName {self.dept.getDeptName()}''')
dept1=Department(10,"HR")
emp1=Employee(101,"naresh",dept1)
emp1.printEmployee()
emp2=Employee(102,"suresh",dept1)
emp2.printEmployee()
Output:
EmployeeNo 101,
EmployeeName naresh,
DepartmentNo 10,
DepartmentName HR
EmployeeNo 102,
EmployeeName suresh,
DepartmentNo 10,
DepartmentName HR
Inheritance
Full Stack Python (Part-73)
Inheritance
Inheritance is process of acquiring the properties and behavior of
one class inside another class.
Advantage of inheritance
Syntax:
class <derived-class-name>(<base-class-name>,<base-class-
name>,..):
variables
methods
objb=B()
objb.m1()
objb.m2()
objb.m3()
objb.m4()
Output:
m1 of A
m2 of A
m3 of B
m4 of B
super().method-name
super().variable-name
Example:
class A:
def __init__(self):
self.x=100
self.y=200
class B(A):
def __init__(self):
super().__init__(self)
self.p=300
self.q=400
objb=B()
print(objb.p,objb.q)
print(objb.x,objb.y)
Output:
300 400
100 200
300 400
100 200
Example:
# Single Level Inheritance
class Person:
def __init__(self):
self.__name=None
def setName(self,n):
self.__name=n
def getName(self):
return self.__name
class Student(Person):
def __init__(self):
super().__init__()
self.__course=None
def setCourse(self,c):
self.__course=c
def getCourse(self):
return self.__course
stud1=Student()
stud1.setName("nk")
stud1.setCourse("Python")
name=stud1.getName()
course=stud1.getCourse()
print(f'Name is {name}')
print(f'Course is {course}')
Output:
Name is nk
Course is Python
Multilevel inheritance
More than one level of inheritance is called multilevel inheritance
(OR) if a class is derived from another derived class it is called
multilevel inheritance.
Example:
# Multilevel inheritance
class Person:
def __init__(self):
self.__name=None
def setName(self,n):
self.__name=n
def getName(self):
return self.__name
class Employee(Person):
def __init__(self):
super().__init__()
self.__job=None
def setJob(self,j):
self.__job=j
def getJob(self):
return self.__job
class SalariedEmployee(Employee):
def __init__(self):
super().__init__()
self.__salary=None
def setSalary(self,s):
self.__salary=s
def getSalary(self):
return self.__salary
emp1=SalariedEmployee()
emp1.setName("nk")
emp1.setJob("manager")
emp1.setSalary(50000)
name=emp1.getName()
job=emp1.getJob()
salary=emp1.getSalary()
print(name,job,salary)
Output:
nk manager 50000
Multiple Inheritance
If a class is derived from more than one base class, it is called
multiple inheritance.
Example:
class A:
def __init__(self):
self.x=100
class B:
def __init__(self):
self.y=200
class C(A,B):
def __init__(self):
super().__init__()
B.__init__(self)
self.z=300
objc=C()
print(objc.x,objc.y,objc.z)
Output:
100 200 300
Method Overriding (Inheritance+Polymorphism)
Defining method inside derived class with same name and number
of arguments of method exists in base class is called method
overriding.
Example:
class Person:
def __init__(self):
self.__name=None
def read(self): # Overriden method
self.__name=input("Enter Name ")
def print_info(self): # Overriden method
print(f'Name :{self.__name}')
class Employee(Person):
def __init__(self):
super().__init__()
self.__job=None
def read(self): # Overriding method
super().read()
self.__job=input("Enter Job ")
def print_info(self): # Overriding method
super().print_info()
print(f'Job {self.__job}')
emp1=Employee()
emp1.read()
emp1.print_info()
Output:
Enter Name nk
Enter Job manager
Name :nk
Job manager
Object class
Every class in python is inherited from object class (OR) every class in
python is object type.
The methods of object class are used by PVM for managing objects.
Example:
class A:
def m1(self):
print("m1 of A")
print(dir(A))
Output:
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__',
'__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__',
'__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__',
'__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
'__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__',
'm1']
The methods of object class are magic methods. These methods get
executed automatically.
Any method which is prefix and suffix with __ is called magic method.
__str__(self)
class Student:
def __init__(self,r,n):
self.__rollno=r
self.__name=n
def __str__(self): # Overriding method
return f'{self.__rollno},{self.__name}'
s1=Student(101,"nk")
print(s1)
print(s1.__str__())
list1=list([10,20,30,40,50])
print(list1)
c1=complex(1,2)
print(c1)
Output:
101,nk
101,nk
[10, 20, 30, 40, 50]
(1+2j)
Example:
>>> c1=1+2j
>>> c1.__str__()
'(1+2j)'
>>> c1.__repr__()
'(1+2j)'
>>> list1=[10,20,30,40,50]
>>> list1.__str__()
'[10, 20, 30, 40, 50]'
>>> list1.__repr__()
'[10, 20, 30, 40, 50]'
Example:
class Student:
def __init__(self,r,n):
self.__rollno=r
self.__name=n
def __str__(self): # Overriding method
return f'{self.__rollno},{self.__name}'
def __repr__(self):
return f'{type(self)}({self.__rollno},{self.__name})'
s1=Student(101,"nk")
print(s1)
print(s1.__str__())
list1=list([10,20,30,40,50])
print(list1)
c1=complex(1,2)
print(c1)
print(repr(s1))
Output:
101,nk
101,nk
[10, 20, 30, 40, 50]
(1+2j)
<class '__main__.Student'>(101,nk)
__eq__(self,other)
class Employee:
def __init__(self,e,en,s):
self.__empno=e
self.__ename=en
self.__salary=s
def __str__(self): # Overriding method
return f'{self.__empno},{self.__ename},{self.__salary}'
def __eq__(self,other): # Overriding method
return self.__empno==other.__empno
emp1=Employee(101,"nk",50000)
print(emp1)
emp2=Employee(101,"nk",50000)
print(emp2)
print(emp1==emp2) # emp1.__eq__(emp2)
Output
101,nk,50000
101,nk,50000
True
Example:
class Employee:
def __init__(self,e,en,s):
self.__empno=e
self.__ename=en
self.__salary=s
def __str__(self): # Overriding method
return f'{self.__empno},{self.__ename},{self.__salary}'
def __eq__(self,other): # Overriding method
return self.__empno==other.__empno
def __hash__(self): # Overriding method
return self.__empno
set1=set()
set1.add(Employee(101,"nk",5000))
set1.add(Employee(102,"suresh",6000))
set1.add(Employee(101,"kishore",8000))
for emp in set1:
print(emp)
Output:
101,nk,5000
102,suresh,6000
Abstract class defines set of rules and regulations for building classes.
Abstract class is collection of abstract methods, non abstract
methods and properties.
class <abstract-class-name>(abc.ABC):
variables
abstract methods
non abstract methods
abstract class is used for inheriting but cannot used for creating
object.
Abstract methods
# obj=A() Error
objb=B()
objb.m1()
Output:
overriding method
Example:
import abc
class Animal(abc.ABC):
@abc.abstractmethod
def eat(self):
pass
class Dog(Animal):
def eat(self): # overriding method
print("dog eat non veg")
class Cow(Animal):
def eat(self): # overriding method
print("cow eat veg")
class Cat(Animal):
def sleep(self):
print("cat sleep")
def eat(self):
print("cat eat")
c1=Cow()
d1=Dog()
c1.eat()
d1.eat()
cat1=Cat()
cat1.eat()
Output:
cow eat veg
dog eat non veg
cat eat
When more than one class having similar role with different
implementation that method declared as abstract method.
Example:
import abc
class Shape(abc.ABC):
def __init__(self):
self.dim1=None
self.dim2=None
def readDim(self):
self.dim1=float(input("Dim1 "))
self.dim2=float(input("Dim2 "))
@abc.abstractmethod
def findArea(self):
pass
class Triangle(Shape):
def __init__(self):
super().__init__()
def findArea(self):
return self.dim1*self.dim2*0.5
class Rectangle(Shape):
def __init__(self):
super().__init__()
def findArea(self):
return self.dim1*self.dim2
t1=Triangle()
t1.readDim()
area1=t1.findArea()
print(f'Area of triangle is {area1:.2f}')
r1=Rectangle()
r1.readDim()
area2=r1.findArea()
print(f'Area of rectangle is {area2:.2f}')
Output:
Dim1 1.2
Dim2 1.5
Area of triangle is 0.90
Dim1 1.5
Dim2 1.6
Area of rectangle is 2.40
duck-typing
A programming style which does not look at an object’s type to
determine if it has the right interface; instead, the method or
attribute is simply called or used (“If it looks like a duck and quacks
like a duck, it must be a duck.”)
Example:
import abc
class Debitcard(abc.ABC):
@abc.abstractmethod
def withdraw(self):
pass
class HDFCDebitcard(Debitcard):
def withdraw(self):
print("withdraw 50000")
class SBIDebitcard(Debitcard):
def withdraw(self):
print("withdraw 20000")
class ICICIATM:
def insert(self,d):
d.withdraw()
card1=HDFCDebitcard()
card2=SBIDebitcard()
atm1=ICICIATM()
atm1.insert(card1)
atm1.insert(card2)
Output:
withdraw 50000
withdraw 20000
Example:
import abc
class Sim(abc.ABC):
@abc.abstractmethod
def connect(self):
pass
class AirtelSim(Sim):
def connect(self):
print("connect to airtel network")
class BsnlSim(Sim):
def connect(self):
print("connect to bsnl netowrk")
class Mobile:
def insert(self,s):
s.connect()
s1=AirtelSim()
s2=BsnlSim()
m1=Mobile()
m1.insert(s1)
m1.insert(s2)
Output:
connect to airtel network
connect to bsnl netowrk
Member class
Example:
Example:
class Person:
class Address: # Inner class/Member class
def __init__(self):
self.__hno=None
self.__street=None
self.__city=None
def readAddress(self):
self.__hno=input("HouseNo ")
self.__street=input("Street ")
self.__city=input("City ")
def printAddress(self):
print(f'{self.__hno},{self.__street},{self.__city}')
def __init__(self):
self.__name=None
self.__add=Person.Address()
def readPerson(self):
self.__name=input("Name ")
self.__add.readAddress()
def printPerson(self):
print(f'{self.__name}')
self.__add.printAddress()
p1=Person()
p1.readPerson()
p1.printPerson()
Output:
Name nk
HouseNo 11
Street hussaini
City hyd
nk
11,hussaini,hyd
Example:
class A:
class B: # Public Member class
def m1(self):
print("m1 of B class")
objb=A.B()
objb.m1()
class X:
class __Y: # Private Member Class
def m1(self):
print("m1 of Y class")
def m2(self):
objy=X.__Y()
objy.m1()
#objy=X.__Y()
#objy.m1()
objx=X()
objx.m2()
Output:
m1 of B class
m1 of Y class
Example:
class Person:
class __Date: # Member class
def __init__(self):
self.__dd,self.__mm,self.__yy=0,0,0
def setDate(self,dd,mm,yy):
self.__dd=dd
self.__mm=mm
self.__yy=yy
def printDate(self):
print(f'{self.__dd}/{self.__mm}/{self.__yy}')
def __init__(self):
self.__name=None
self.__dob=Person.__Date()
def setPerson(self,n,d,m,y):
self.__name=n
self.__dob.setDate(d,m,y)
def printPerson(self):
print(f'{self.__name}')
self.__dob.printDate()
p1=Person()
p1.setPerson("nk",4,7,2000)
p1.printPerson()
Output:
nk
4/7/2000
Local class
Example:
class A:
def m1(self):
print("inside m1 method")
class B: # Local class
def m2(self):
print("m2 of B(Local class)")
objb=B()
objb.m2()
obja=A()
obja.m1()
Output:
inside m1 method
m2 of B(Local class)
Exception Handling
Types of Errors
1. Compile time errors
2. Logical error
3. Runtime errors
Logical Errors
Logic is an algorithm applied to solve given problem.
If there is logical error within program, it gives wrong result or output.
Example:
n1=int(input("Enter First Number "))
n2=int(input("Enter Second Number "))
if n1>n2:
print(f'{n2} is max')
else:
print(f'{n1} is max')
Output:
Enter First Number 10
Enter Second Number 20
10 is max
Runtime Errors
The error which occurs during execution of program is called runtime
error. These runtime errors occur because of wrong input given by
end user.
Example:
n1=int(input("Enter First Number "))
n2=int(input("Enter Second Number "))
n3=n1/n2
print(n1,n2,n3)
Output:
Enter First Number 6
Enter Second Number 2
6 2 3.0
What is exception?
Exception is a runtime error
Exception is an error which occurs during execution of program.
When there is an exception with program, program execution is
terminated.
These runtime errors and exceptions are handled by using exception
handling mechanism.
Predefined exception
The existing exception types are predefined exception.
These exceptions are used by python and python libraries.
Syntax:
try:
statement-1
statement-2
except block
try:
statement-1
statement-2
except error-type:
statement-1
except error-type:
statement-1
Example:
n1=int(input("Enter First Number "))
n2=int(input("Enter Second Number "))
try:
n3=n1/n2
print(n1,n2,n3)
except ZeroDivisionError:
print("cannot divide number with zero")
Output
Enter First Number 5
Enter Second Number 2
5 2 2.5
set1=set()
n=int(input("enter how many elements?"))
for i in range(n):
value=int(input("enter any value "))
set1.add(value)
print(set1)
value=int(input("enter value to remove "))
try:
set1.remove(value)
print(set1)
except KeyError:
print("Given value not exists within set")
Output:
enter how many elements?5
enter any value 10
enter any value 20
enter any value 30
enter any value 40
enter any value 50
{40, 10, 50, 20, 30}
enter value to remove 90
Given value not exists within set
print(set1)
value=int(input("enter value to remove "))
try:
set1.remove(value)
print(set1)
except KeyError as k:
print("Given value not exists within set")
print(k)
Output
enter how many elements?5
enter any value 10
enter any value 20
enter any value 30
enter any value 40
enter any value 50
{40, 10, 50, 20, 30}
enter value to remove 90
Given value not exists within set
90
try:
statement-1
statement-2
except <error-type> as <object-name>:
statement
except <error-type> as <object-name>:
statement
Example:
# Write a program to divide two numbers
try:
n1=int(input("Enter first number "))
n2=int(input("Enter second number "))
n3=n1/n2
print(f'{n1}/{n2}={n3:.2f}')
except ValueError:
print("input value must be integer type")
except ZeroDivisionError:
print("cannot divide number with zero")
Output
Enter first number 5
Enter second number 2
5/2=2.50
sys.exc_info()
This function returns the old-style representation of the handled
exception. If an exception e is currently handled
(so exception() would return e), exc_info() returns the
tuple (type(e), e, e.__traceback__).
Exmaple:
# Write a program to divide two numbers
import sys
try:
n1=int(input("Enter first number "))
n2=int(input("Enter second number "))
n3=n1/n2
print(f'{n1}/{n2}={n3:.2f}')
except:
t=sys.exc_info()
print(t[1])
Output:
Enter first number 5
Enter second number 0
division by zero
finally
Syntax-1:
try:
statement-1
statement-2
except <error-type>:
statement-3
except <error-type>:
statement-4
finally:
statement-5
Syntax-2
try:
statement-1
finally:
statement-2
try:
establishing connection to printer
print document
except XError:
print("xerror")
finally:
close printer connection
Example:
try:
print("inside try block")
n1=int(input("enter first number "))
n2=int(input("enter second number "))
n3=n1/n2
print(n1,n2,n3)
except ZeroDivisionError:
print("inside except block")
finally:
print("inside finally block")
print("continue...")
Output:
inside try block
enter first number 5
enter second number 2
5 2 2.5
inside finally block
continue...
Example:
def multiply(n1,n2):
if n1==0 or n2==0:
raise ValueError()
else:
return n1*n2
Output:
Enter First Number 5
Enter Second Number 0
numbers cannot multiply with zero
Example:
class MultiplyError(Exception):
def __str__(self):
return "cannot multiply number with zero"
def multiply(n1,n2):
if n1==0 or n2==0:
raise MultiplyError()
else:
return n1*n2
try:
num1=int(input("Enter First Number "))
num2=int(input("Enter Second Number "))
num3=multiply(num1,num2)
print(num1,num2,num3,sep="\n")
except ValueError:
print("input value must be integer")
except MultiplyError as a:
print(a)
Output:
Enter First Number 5
Enter Second Number 2
5
2
10
Enter First Number 0
Enter Second Number 5
cannot multiply number with zero
Example:
users={'nk':'n123',
'nit':'n321',
'ramesh':'r456'}
class LoginError(Exception):
def __init__(self,msg):
super().__init__()
self.__msg=msg
def __str__(self):
return self.__msg
def login(user,pwd):
if user in users and users[user]==pwd:
print(f'{user} welcome')
else:
raise LoginError("invalid username or password")
def main():
uname=input("UserName ")
pwd=input("Password ")
try:
login(uname,pwd)
except LoginError as a:
print(a)
Output:
UserName nk
Password n123
nk welcome
UserName nk
Password nit123
invalid username or password
UserName abc
Password xyz
invalid username or password
Example:
class InsuffFundsError(Exception):
def __str__(self):
return "insuff balance"
class Account:
def __init__(self,ac,cn,b):
self.__accno=ac
self.__cname=cn
self.__balance=b
def deposit(self,a):
self.__balance=self.__balance+a
def withdraw(self,a):
if a>self.__balance:
raise InsuffFundsError()
else:
self.__balance=self.__balance-a
def __str__(self):
return f'{self.__accno},{self.__cname},{self.__balance}'
def main():
acc1=Account(101,"nk",5000)
print(acc1)
try:
acc1.deposit(4000)
print(acc1)
acc1.withdraw(2000)
print(acc1)
acc1.withdraw(9000)
except InsuffFundsError as a:
print(a)
main()
Output:
101,nk,5000
101,nk,9000
101,nk,7000
insuff balance
Files
Text file
In text file data is stored in character format.
Text file is collection of characters (OR) text file allows only string
data.
Full Stack Python (Part-80)
Files
Text file
In text file data is stored in character format.
Text file is collection of characters (OR) text file allows only string
data.
Binary file
Binary file is a collection of bytes
In binary file data is stored in 1 byte format.
open(path,mode)
path is a filename
mode: mode represents file opening mode.
Character Meaning
'r' open for reading (default)
'w' open for writing, truncating the file first
open for exclusive creation, failing if the file already
'x'
exists
'a' open for writing, appending to the end of file if it exists
'b' binary mode
't' text mode (default)
'+' open for updating (reading and writing)
The default mode is 'r' (open for reading text, a synonym of 'rt').
Modes 'w+' and 'w+b' open and truncate the file.
Modes 'r+' and 'r+b' open the file with no truncation.
Text files
In text file data is stored in character format.
Text file is collection of characters (OR) text file allows only string
data.
Example:
# Creating text file
import sys
try:
f=open("file1.txt", "w")
f.write("python")
f.write("3.12")
f.write('''python is a
programming
language''')
print("data is written inside file")
except:
e=sys.exc_info()
print(e[0])
finally:
f.close()
Output:
data is written inside file
Example:
# Write a program to create employee.txt file and store employee
details
import sys
try:
f=open("emp.txt","a")
while True:
empno=int(input("EmployeeNo "))
ename=input("EmployeeName ")
sal=float(input("Salary "))
print(empno,ename,sal,sep=",",file=f)
ans=input("add another employee?")
if ans=="no":
break
except:
t=sys.exc_info()
print(t[0])
finally:
f.close()
Output:
EmployeeNo 1
EmployeeName nk
Salary 5000
add another employee?yes
EmployeeNo 2
EmployeeName suresh
Salary 7000
add another employee?yes
EmployeeNo 3
EmployeeName kishore
Salary 60000
add another employee?yes
EmployeeNo 4
EmployeeName kiran
Salary 7000
add another employee?yes
EmployeeNo 5
EmployeeName ramesh
Salary 70000
add another employee?no
To read data from text file, file must be open in “r” mode.
The following methods are used to read data from text file
1. read()
2. readline()
read(size=-1)
read size characters from file.
If size is not defined or -1, it read complex file and return as one string
If size is defined, it read size characters from file and return as one
string
Example:
# Reading text from file1.txt
import sys
try:
f=open("file1.txt","r")
s=f.read()
print(s)
except:
t=sys.exc_info()
print(t[0])
finally:
f.close()
Output:
python3.12python is a
programming
language
Example:
# Write a program to count vowels in file1.txt
import sys
try:
f=open("file1.txt","r")
c=0
while True:
s=f.read(1)
if s=="":
break
if s in "aeiouAEIOU":
c+=1
print(f'Count of vowels {c}')
except:
t=sys.exc_info()
print(t[0])
finally:
f.close()
Output:
Count of vowels 11
readline(size=-1)
if size is not defined, it read one line as one string
if size if defined, it read size characters from file
Example:
# Write a program to read employees data from emp.txt
import sys
try:
f=open("emp.txt","r")
tot=0
while True:
e=f.readline()
if e=='':
break
list1=e.split(",")
sal=float(list1[2])
tot=tot+sal
print(e,end='')
print("Total Salaries paid to employees ",tot)
except:
t=sys.exc_info()
print(t[0])
finally:
f.close()
Output:
1,nk,5000.0
2,suresh,7000.0
3,kishore,60000.0
4,kiran,7000.0
5,ramesh,70000.0
Total Salaries paid to employees 149000.0
CSV file
The so-called CSV (Comma Separated Values) format is the most
common import and export format for spreadsheets and databases.
The csv module implements classes to read and write tabular data
in CSV format. It allows programmers to say, “write this data in the
format preferred by Excel,” or “read data from this file which was
generated by Excel,” without knowing the precise details of the CSV
format used by Excel. Programmers can also describe the CSV
formats understood by other applications or define their own
special-purpose CSV formats.
Full Stack Python (Part-81)
CSV file
The so-called CSV (Comma Separated Values) format is the most
common import and export format for spreadsheets and databases.
The csv module implements classes to read and write tabular data
in CSV format. It allows programmers to say, “write this data in the
format preferred by Excel,” or “read data from this file which was
generated by Excel,” without knowing the precise details of the CSV
format used by Excel. Programmers can also describe the CSV
formats understood by other applications or define their own
special-purpose CSV formats.
The csv module’s reader and writer objects read and write
sequences. Programmers can also read and write data in dictionary
form using the DictReader and DictWriter classes.
csv.writer(csvfile)
Return a writer object responsible for converting the user’s data into
delimited strings on the given file-like object. csvfile can be any
object with a write() method. If csvfile is a file object, it should be
opened with newline=''
Example
import csv
import sys
try:
f=open("e:\\stud.csv","w",newline='')
cw=csv.writer(f)
while True:
rollno=int(input("Rollno "))
name=input("Name ")
course=input("Course")
cw.writerow([rollno,name,course])
ans=input("Add another student?")
if ans=="no":
break
except:
t=sys.exc_info()
print(t)
finally:
f.close()
Output
Rollno 1
Name nk
Coursepython
Add another student?yes
Rollno 2
Name suresh
Coursejava
Add another student?yes
Rollno 3
Name kishore
Coursec++
Add another student?yes
Rollno 4
Name kiran
Courseoracle
Add another student?no
csv.reader(csvfile)
Return a reader object which will iterate over lines in the
given csvfile. csvfile can be any object which supports
the iterator protocol and returns a string each time
its __next__() method is called
Example:
import csv
with open("e:\\stud.csv","r") as f:
cr=csv.reader(f)
for row in cr:
print(row)
with open("e:\\stud.csv","r") as f:
cr=csv.reader(f)
stud_details=list(cr)
print(stud_details)
for s in stud_details:
print(s)
Output:
['1', 'nk', 'python']
['2', 'suresh', 'java']
['3', 'kishore', 'c++']
['4', 'kiran', 'oracle']
[['1', 'nk', 'python'], ['2', 'suresh', 'java'], ['3', 'kishore', 'c++'], ['4', 'kiran',
'oracle']]
['1', 'nk', 'python']
['2', 'suresh', 'java']
['3', 'kishore', 'c++']
['4', 'kiran', 'oracle']
Example:
import csv
with open("e:\\products.csv","w",newline='') as f:
cw=csv.DictWriter(f,fieldnames=['pname','price'])
cw.writeheader()
while True:
pn=input("Product Name ")
p=float(input("Price "))
d={'pname':pn,'price':p}
cw.writerow(d)
ans=input("Add another product?")
if ans=="no":
break
Output:
Product Name keyboard
Price 1000
Add another product?yes
Product Name mouse
Price 200
Add another product?yes
Product Name monitor
Price 5000
Add another product?no
Example:
import csv
with open("e:\\products.csv","r") as f:
dr=csv.DictReader(f)
for row in dr:
print(row)
with open("e:\\products.csv","r") as f:
dr=csv.DictReader(f)
for row in dr:
print(row['pname'],row['price'])
Output:
{'pname': 'keyboard', 'price': '1000.0'}
{'pname': 'mouse', 'price': '200.0'}
{'pname': 'monitor', 'price': '5000.0'}
keyboard 1000.0
mouse 200.0
monitor 5000.0
JSON
JSON
JSON Python
object dict
array list
string str
number (int) int
number
float
(real)
true True
false False
null None
json.dump(obj, fp)
This function convert python object into json format and write inside
file.
Example:
import json
with open("emp.json","w") as f:
emp_dict={'empno':[1,2,3],
'ename':['nk','suresh','kishore'],
'salary':[4500,5000,6000]}
json.dump(emp_dict,f)
print("data is written inside emp.json file")
Output:
data is written inside emp.json file
json.load(f)
This function returns python representation of json object.
Example:
import json
'''with open("ipl.json","r") as f:
d1=json.load(f)
for k,v in d1.items():
print(k,v)
'''
with open("emp.json","r") as f:
emp_dict=json.load(f)
print(emp_dict)
with open("emp.json","r") as f:
emp_dict=json.load(f)
for k,v in emp_dict.items():
print(k,v)
Output:
{'empno': [1, 2, 3], 'ename': ['nk', 'suresh', 'kishore'], 'salary': [4500,
5000, 6000]}
empno [1, 2, 3]
ename ['nk', 'suresh', 'kishore']
salary [4500, 5000, 6000]
XML
What is XML?
XML stands for eXtensible Markup Language
XML is a markup language much like HTML
XML was designed to store and transport data
XML was designed to be self-descriptive
XML is a W3C Recommendation
XML VS JSON
As a markup language, XML is more complex and requires a tag
structure. In contrast, JSON is a data format that extends from
JavaScript. It does not use tags, which makes it more compact and
easier to read for humans. JSON can represent the same data in a
smaller file size for faster data transfer.
XML
What is XML?
XML stands for eXtensible Markup Language
XML is a markup language much like HTML
XML was designed to store and transport data
XML was designed to be self-descriptive
XML is a W3C Recommendation
XML VS JSON
As a markup language, XML is more complex and requires a tag
structure. In contrast, JSON is a data format that extends from
JavaScript. It does not use tags, which makes it more compact and
easier to read for humans. JSON can represent the same data in a
smaller file size for faster data transfer.
<students>
<student>
<name>Rick Grimes</name>
<age>35</age>
<subject>Maths</subject>
<gender>Male</gender>
</student>
<student>
<name>Daryl Dixon </name>
<age>33</age>
<subject>Science</subject>
<gender>Male</gender>
</student>
<student>
<name>Maggie</name>
<age>36</age>
<subject>Arts</subject>
<gender>Female</gender>
</student>
</students>
Example
import xml.etree.ElementTree as ET
tree = ET.parse('students.xml')
root = tree.getroot()
print(root.tag)
print(root.attrib)
for child in root:
print(child.tag)
Output:
students
{}
student
student
student
Rick Grimes
Daryl Dixon
Maggie
35
33
36
Maths
Science
Arts
Binary files
Example:
# Creating binary file
with open("file1.dat","wb") as f:
b=bytes([65,66,67,68,69,70])
f.write(b)
Output:
data is written inside file
Example:
# Reading data from binary file
with open("file1.dat","rb") as f:
b=f.read()
print(b)
for x in b:
print(x)
Output:
b'ABCDEF'
65
66
67
68
69
70
Pickle module
“pickle” is a default module comes with python software.
The pickle module implements binary protocols for serializing and de-
serializing a Python object structure. “Pickling” is the process
whereby a Python object hierarchy is converted into a byte stream,
and “unpickling” is the inverse operation, whereby a byte stream
(from a binary file or bytes-like object) is converted back into an
object hierarchy. Pickling (and unpickling) is alternatively known as
“serialization”, “marshalling,” or “flattening”; however, to avoid
confusion, the terms used here are “pickling” and “unpickling”.
Pickle module
“pickle” is a default module comes with python software.
The pickle module implements binary protocols for serializing and de-
serializing a Python object structure. “Pickling” is the process
whereby a Python object hierarchy is converted into a byte stream,
and “unpickling” is the inverse operation, whereby a byte stream
(from a binary file or bytes-like object) is converted back into an
object hierarchy. Pickling (and unpickling) is alternatively known as
“serialization”, “marshalling,” or “flattening”; however, to avoid
confusion, the terms used here are “pickling” and “unpickling”.
Example of pickling:
import pickle
with open("file1.ser","wb") as f:
pickle.dump(65,f)
pickle.dump(1.5,f)
pickle.dump(1+2j,f)
pickle.dump([10,20,30,40,50],f)
pickle.dump({'empno':[1,2,3],'ename':
["naresh","ramesh","suresh"]},f)
Example:
import pickle
with open("file1.ser","rb") as f:
a=pickle.load(f)
print(a)
b=pickle.load(f)
print(b)
c=pickle.load(f)
print(c)
d=pickle.load(f)
print(d)
e=pickle.load(f)
print(e)
Output:
65
1.5
(1+2j)
[10, 20, 30, 40, 50]
{'empno': [1, 2, 3], 'ename': ['naresh', 'ramesh', 'suresh']}
import pickle
import emp
with open("employee.ser","wb") as f:
emp1=emp.Employee()
emp2=emp.Employee()
emp1.setData(101,"naresh",5000)
emp2.setData(102,"suresh",8000)
pickle.dump(emp1,f)
pickle.dump(emp2,f)
import pickle
import emp
with open("employee.ser","rb") as f:
emp1=pickle.load(f)
emp2=pickle.load(f)
print(emp1)
print(emp2)
>>> p1=r'python'
>>> print(p1)
python
>>> print(type(p1))
<class 'str'>
>>> import re
>>> p2=re.compile("python")
>>> print(p2)
re.compile('python')
>>> print(type(p2))
re.match(pattern, string, flags=0)
If zero or more characters at the beginning of string match
the regular expression pattern, return a corresponding Match.
Return None if the string does not match the pattern.
Example:
>>> import re
>>> m=re.match(r'py','python')
>>> print(m)
<re.Match object; span=(0, 2), match='py'>
>>> m=re.match(r'jy','python')
>>> print(m)
None
m=re.match(r'py','PYTHON',re.IGNORECASE)
print(m)
<re.Match object; span=(0, 2), match='PY'>
Example
>>> m=re.search(r'python','this is python language')
>>> print(m)
<re.Match object; span=(8, 14), match='python'>
>>> m=re.search(r'python','python is easy, python simple')
>>> print(m)
<re.Match object; span=(0, 6), match='python'>
>>> m=re.search(r'python','java is language')
>>> print(m)
None
Example
>>> list1=re.findall(r'python','java python oracle python .net python')
>>> print(list1)
['python', 'python', 'python']
>>> list2=re.findall(r'java','java python oracle python .net python')
>>> print(list2)
['java']
>>> list3=re.findall(r'jython','java python oracle python .net python')
>>> print(list3)
[]
>>> m=re.fullmatch(r'python','python')
>>> print(m)
<re.Match object; span=(0, 6), match='python'>
>>> m=re.fullmatch(r'python','python jython')
>>> print(m)
None
.
(Dot.) In the default mode, this matches any character except a
newline. If the DOTALL flag has been specified, this matches any
character including a newline.
Example
>>> list1=re.findall(r'.','python')
>>> print(list1)
['p', 'y', 't', 'h', 'o', 'n']
>>> list2=re.findall(r'.','python\nlanguage')
>>> print(list2)
['p', 'y', 't', 'h', 'o', 'n', 'l', 'a', 'n', 'g', 'u', 'a', 'g', 'e']
>>> list3=re.findall(r'.','python\nlanguage',re.DOTALL)
>>> print(list3)
['p', 'y', 't', 'h', 'o', 'n', '\n', 'l', 'a', 'n', 'g', 'u', 'a', 'g', 'e']
>>> list4=re.findall(r'p.','python pypy jython rpython programming')
>>> print(list4)
['py', 'py', 'py', 'py', 'pr']
>>> list5=re.findall(r'p.t','python programming pot')
>>> print(list5)
['pyt', 'pot']
>>> list6=re.findall(r'..','python programming language')
>>> print(list6)
['py', 'th', 'on', ' p', 'ro', 'gr', 'am', 'mi', 'ng', ' l', 'an', 'gu', 'ag']
^
(Caret.) Matches the start of the string, and in MULTILINE mode also
matches immediately after each newline.
>>> m=re.search(r'^py','python')
>>> print(m)
<re.Match object; span=(0, 2), match='py'>
Example:
# find names begin with r
import re
names=['ramesh','kishore','rajesh','rakesh','nk']
for name in names:
m=re.search(r'^r',name)
if m:
print(name)
Output
ramesh
rajesh
rakesh
Example:
>>> str1='''python is easy
... python is high level
... python is object oriented
... jython is python implementation'''
>>> list1=re.findall(r'^py',str1,re.MULTILINE)
>>> print(list1)
['py', 'py', 'py']
$
Matches the end of the string or just before the newline at the end of
the string, and in MULTILINE mode also matches before a newline
Example:
# find names end with h
import re
names=['ramesh','kishore','rajesh','rakesh','nk','harsha']
for name in names:
m=re.search(r'h$',name)
if m:
print(name)
Output:
ramesh
rajesh
rakesh
nk
*
Causes the resulting RE to match 0 or more repetitions of the
preceding RE, as many repetitions as are possible. ab* will match ‘a’,
‘ab’, or ‘a’ followed by any number of ‘b’s.
Example:
>>> str1="ab a abb acb dcb abbbb abbb"
>>> list1=re.findall(r'ab*',str1)
>>> print(list1)
['ab', 'a', 'abb', 'a', 'abbbb', 'abbb']
Example:
# finding all the names whose name starts with r and end with n
import re
names=['ramesh','kishore','rajesh','rakesh','nk','harsha','raman']
for name in names:
m=re.fullmatch(r'^r.*n$',name)
if m:
print(name)
Output
raman
+
Causes the resulting RE to match 1 or more repetitions of the
preceding RE. ab+ will match ‘a’ followed by any non-zero number
of ‘b’s; it will not match just ‘a’.
+
Causes the resulting RE to match 1 or more repetitions of the
preceding RE. ab+ will match ‘a’ followed by any non-zero number
of ‘b’s; it will not match just ‘a’.
?
Causes the resulting RE to match 0 or 1 repetitions of the preceding
RE. ab? will match either ‘a’ or ‘ab’.
{m}
Specifies that exactly m copies of the previous RE should be
matched; fewer matches cause the entire RE not to match. For
example, a{6} will match exactly six 'a' characters, but not five.
{m,n}
Causes the resulting RE to match from m to n repetitions of the
preceding RE, attempting to match as many repetitions as possible.
For example, a{3,5} will match from 3 to 5 'a' characters.
Omitting m specifies a lower bound of zero, and omitting n specifies
an infinite upper bound. As an example, a{4,}b will match 'aaaab' or
a thousand 'a' characters followed by a 'b', but not 'aaab'. The
comma may not be omitted or the modifier would be confused with
the previously described form.
[]
Used to indicate a set of characters. In a set:
Characters can be listed individually, e.g. [amk] will match 'a', 'm',
or 'k'.
Example:
import re
names=['naresh','ramesh','kishore','rajesh','kiran','raman','suresh']
for name in names:
m=re.fullmatch(r'^[rk].*',name)
if m:
print(name)
print("========================")
for name in names:
m=re.fullmatch(r'^[rk].*[hn]$',name)
if m:
print(name)
Output:
ramesh
kishore
rajesh
kiran
raman
========================
ramesh
rajesh
kiran
raman
Example:
# name validation
import re
name=input("Enter Name ")
m=re.fullmatch(r'[A-Z]{3,20}',name)
if m:
print(f'{name} valid')
else:
print(f'{name} is invalid')
Output:
Enter Name NARESH1
NARESH1 is invalid
Example:
# email-id validation
# [email protected]
# [email protected]
import re
email=input("Enter Your Email-ID ")
m=re.fullmatch(r'^[a-zA-Z]{1}[a-zA-Z0-9]*@[a-z]+\.[a-z]{2,3}',email)
if m:
print(f'valid email')
else:
print(f'invalid email')
Output:
Enter Your Email-ID [email protected]
valid email
Example
# Extracting date from string
import re
Output:
<re.Match object; span=(19, 29), match='12-05-2020'>
12-05-2020
12
05
2020
Match.group([group1, ...])
Returns one or more subgroups of the match. If there is a single
argument, the result is a single string; if there are multiple arguments,
the result is a tuple with one item per argument. Without
arguments, group1 defaults to zero (the whole match is returned). If
a groupN argument is zero, the corresponding return value is the
entire matching string; This grouping is done using ()
Example:
# Extracting date from string
import re
Output:
<re.Match object; span=(19, 29), match='12-05-2020'>
12
05
2020
12-05-2020
12
('12', '05', '2020')
Example:
# IFSC code validation
import re
ifsc_code=input("input IFSC code ")
m=re.fullmatch(r'[a-zA-Z]{4}[0-9]{7}',ifsc_code)
if m:
print("valid ifsc code")
else:
print("invalid ifsc code")
Output:
input IFSC code HDFC0000123
valid ifsc code
The special sequences consist of '\' and a character from the list
below. If the ordinary character is not an ASCII digit or an ASCII
letter, then the resulting RE will match the second character. For
example, \$ matches the character '$'.
re.sub(pattern, repl, string, count=0, flags=0)
Return the string obtained by replacing the leftmost non-overlapping
occurrences of pattern in string by the replacement repl. If the
pattern isn’t found, string is returned unchanged. repl can be a string
or a function.
What is networking?
Networking is nothing but logical or physical link between two or
more devices.
Advantage of networking is sharing resources; these resources can
be hardware and software.
Basics of networking
What is ip-address?
In networking every system or device is identified with unique
number called ip-address.
What is host name?
Host name is wrapper of ip-address.
What is protocol?
A protocol defines set of rules and regulations for exchanging or
communication between two programs (Client/Server).
1. HTTP Hyper Text Transfer Protocol
2. SMTP Simple Mail Transfer Protocol
3. FTP File Transfer Protocol
4. TCP Transmission control protocol
5. UDP User Datagram Protocol
What is portno?
Server program is identifier with unique number called portno.
What is socket?
Socket is an implementation of client and server programs.
Socket is an endpoint communication between two programs.
1. Client
2. Server
Connection oriented implementation is done using TCP sockets.
Create a new socket using the given address family, socket type
and protocol number. The address family should be AF_INET (the
default), AF_INET6, AF_UNIX, AF_CAN, AF_PACKET, or AF_RDS.
The socket type should be SOCK_STREAM (the
default), SOCK_DGRAM, SOCK_RAW or perhaps one of the
other SOCK_ constants.
socket.accept()
Accept a connection. The socket must be bound to an address and
listening for connections. The return value is a
pair (conn, address) where conn is a new socket object usable to
send and receive data on the connection, and address is the
address bound to the socket on the other end of the connection.
socket.bind(address)
Bind the socket to address. The socket must not already be bound.
socket.close()
Mark the socket closed.
socket.connect(address)
Connect to a remote socket at address.
socket.recv(bufsize[, flags])
Receive data from the socket. The return value is a bytes object
representing the data received.
socket.send(bytes[, flags])
Send data to the socket. The socket must be connected to a
remote socket.
socket.listen([backlog])
Enable a server to accept connections.
Server.py Client.py
import socket import socket
s=socket.socket() s=socket.socket()
s.bind(("localhost",50)) s.connect(("localhost",50))
s.listen(5)
print("Server is running...")
s.accept()
print("Connection established...")
Output
Server2.py Client2.py
# Message Server # Message Client
ss=socket.socket() s=socket.socket()
ss.bind(("localhost",40)) s.connect(("localhost",40))
ss.listen(10) s.send("Hello Server".encode())
print("Message Server is b=s.recv(1024)
Running...") print(b.decode())
t=ss.accept()
c=t[0] # connection of
client/socket
b=c.recv(1024)
print(b.decode())
c.send("Hello Client".encode())
Output
Example:
Mathserver.py Mathclient.py
# MathServer/CalcServer # Math client
ss=socket.socket() s=socket.socket()
ss.bind(("localhost",40)) s.connect(("localhost",40))
ss.listen(5) expr=input("Enter Expression :")
print("Math Server is Running ") s.send(expr.encode())
while True: b=s.recv(2048)
t=ss.accept() print(b.decode())
c=t[0]
b=c.recv(2048)
expr=b.decode()
res=eval(expr)
result=f'Result is {res}'
c.send(result.encode())
Output:
Syntax:
socket.socket(type= SOCK_DGRAM)
Connection less implementation using UDP (User Datagram Protocol)
Syntax:
socket.socket(type= SOCK_DGRAM)
socket.recvfrom(bufsize)
Receive data from the socket. The return value is a
pair (bytes, address) where bytes is a bytes object representing the
data received and address is the address of the socket sending the
data
socket.sendto(bytes, address)
Send data to the socket. The socket should not be connected to a
remote socket, since the destination socket is specified by address
Upd1.py Udp2.py
# UDP Implementation # UDP implementation
s=socket.socket(type=socket.SO s=socket.socket(type=socket.SO
CK_DGRAM) CK_DGRAM)
s.bind(("localhost",40)) s.bind(("localhost",30))
msg="Hello" while True:
s.sendto(msg.encode(), t=s.recvfrom(1024)
("localhost",30)) print(t[0].decode())
PYTHON DATABASE COMMUNICATION (PDBC)
Every application or project required persistence.
Persistence is nothing but saving data permanently.
Data can be saved permanently using two systems.
1. File System
2. Database System
SQL
SQL stands for Structured Query Language. It is a language
understood by many database applications or softwares.
SQL standard defined by ASNI, this standard is followed by database
software’s for developing SQL engine/SQL compiler.
Oracle Database
Install Oracle Software
Oracle 11g Expression Edition
DDL commands
Data definition language commands are used to create, modify
and delete database objects ( tables, views, index,… )
Creating table
create table <table-name>(col-name datatype,
col-name datatype,
col-name datatype,…)
Datatypes of Oracle
1. NUMBER 🡪 integer,float
2. VARCHAR2 🡪 String
3. Date
4. Time
Example:
Create table emp(empno number(4) primary key,
ename varchar2(20) not null,
salary number(10,2));
Alter table
Alter table command is used for modifying the structure of table
Drop table
Drop table command is used for deleting table from database.
DML commands
Data manipulation language commands, these commands are
used to manipulate (insert, update, deleting) data.
SQL
SQL stands for Structured Query Language. It is a language
understands by many database applications or software’s.
SQL standard defined by ASNI, this standard is followed by database
software’s for developing SQL engine/SQL compiler.
SQL provides set of commands to perform operations on database.
Based on the operations, these commands are classified into
different categories
Oracle Database
Install Oracle Software
Oracle 11g Expression Edition
https://www.oracle.com/database/technologies/xe-
downloads.html
DDL commands
Data definition language commands are used to create, modify
and delete database objects ( tables, views, index,… )
Creating table
create table <table-name>(col-name datatype,
col-name datatype,
col-name datatype,…)
Datatypes of Oracle
1. NUMBER integer,float
2. VARCHAR2 String
3. Date
4. Time
Example:
Create table emp(empno number(4) primary key,
ename varchar2(20) not null,
salary number(10,2));
Alter table
Alter table command is used for modifying the structure of table
Drop table
Drop table command is used for deleting table from database.
DML commands
Data manipulation language commands, these commands are
used to manipulate (insert, update, deleting) data.
Inserting data into database table
Insert command is used to insert data into database table.
Update command
This command is used to replace value of one more than one
column.
Syntax:
update <table-name> set <col-name>=value,<col-name>=value
where <condition>;
Delete command
This command is used to delete rows from database table.
Syntax:
delete from <table-name> where condition;
SELECT command
This command is used to read data from database table.
Rollback
Undo changes of database table.
connect() function
This function establish connection to database and return
connection object.
connect(url)
connect(url,user,password,host)
Syntax-1
>>> import cx_Oracle
>>> cn=cx_Oracle.connect("system/manager@XE")
>>> print(cn)
<cx_Oracle.Connection to system@XE>
>>>
Syntax-2
>>> connection = cx_Oracle.connect(user="system",
password="manager",
dsn="localhost:1521/XE")
>>> print(connection)
<cx_Oracle.Connection to system@localhost:1521/XE>
Full Stack Python (Part-92)
Example:
import cx_Oracle
cn=cx_Oracle.connect(user="system",password="manager",dsn="loc
alhost:1521/XE")
print("connection established...")
c=cn.cursor()
print("cursor object is created...")
Output:
connection established...
cursor object is created...
1. execute()
2. executemany()
3. executescript()
execute(sql)
This method is used for sending SQL statement to database server.
SQL statements are two types
1. Static SQL statements
2. Dynamic SQL statements
Example:
# Write a program to insert data into emp table
import cx_Oracle
cn=cx_Oracle.connect("system/manager@XE")
c=cn.cursor()
c.execute("insert into emp values(105,'kishore',5000)")
k=c.rowcount
print(k)
cn.commit()
cn.close()
Output:
1
Example:
# Dynamic SQL statement
import cx_Oracle
try:
cn=cx_Oracle.connect(user="system",password="manager",dsn="loc
alhost:1521/XE")
c=cn.cursor()
while True:
eno=int(input("EmployeeNo :"))
ename=input("EmployeeName :")
sal=float(input("Salary :"))
try:
c.execute("insert into emp values(:1,:2,:3)",(eno,ename,sal))
k=c.rowcount
if k==1:
print("Employee inserted...")
cn.commit()
except cx_Oracle.IntegrityError:
print("employee no exists")
Output:
EmployeeNo :106
EmployeeName :rajesh
Salary :6000
Employee inserted...
Add another employee?yes
EmployeeNo :107
EmployeeName :kiran
Salary :9000
Employee inserted...
Add another employee?yes
EmployeeNo :106
EmployeeName :abc
Salary :7000
employee no exists
Add another employee?no
Example:
# Write a program to increment salary (updating) of input employee
import cx_Oracle
import sys
try:
cn=cx_Oracle.connect("system/manager@XE")
c=cn.cursor()
while True:
eno=int(input("EmployeeNo :"))
value=float(input("Increment Value/Sal "))
c.execute("update emp set salary=salary+:1 where empno=:2",
(value,eno))
k=c.rowcount
if k>0:
print(f'{eno} salary is updated....')
cn.commit()
else:
print(f'{eno} not found')
Output
EmployeeNo :101
Increment Value/Sal 1000
101 salary is updated....
Update another employee salaryyes
EmployeeNo :201
Increment Value/Sal 900
Update another employee salaryno
>>>
EmployeeNo :201
Increment Value/Sal 900
201 not found
Update another employee salaryno
import cx_Oracle
Output:
EmployeeNo 107
employee deleted from database table
Delete another employee? yes
EmployeeNo 107
107 not found
Delete another employee? No
Example:
# Write a program to create table in oracle database
import cx_Oracle
Output:
Table Created
How to read data from database table?
1. fetchone()
2. fetchmany()
3. fetchall()
fetchone() : this method read each time one row from cursor object.
fetchmany(n): This method read “n” rows from cursor object.
fetchall() : This method read all rows from cursor object.
Example:
# Read data from emp table
import cx_Oracle
cn=cx_Oracle.connect("system/manager@XE")
c=cn.cursor()
c.execute("select * from emp")
row1=c.fetchone()
print(row1)
row2=c.fetchone()
print(row2)
row3=c.fetchone()
print(row3)
row4=c.fetchone()
print(row4)
row5=c.fetchone()
print(row5)
row6=c.fetchone()
print(row6)
row7=c.fetchone()
print(row7)
Output
(101, 'naresh', 6000.0)
(102, 'suresh', 6000.0)
(103, 'kishore', 7000.0)
(104, 'ramesh', 8400.0)
(105, 'kishore', 5000.0)
(106, 'rajesh', 6000.0)
None
>>>
Example:
# Read data from emp table
import cx_Oracle
cn=cx_Oracle.connect("system/manager@XE")
c=cn.cursor()
c.execute("select * from emp")
while True:
row=c.fetchone()
if row==None:
break
empno,ename,salary=row
print(empno,ename,salary)
Output:
101 naresh 6000.0
102 suresh 6000.0
103 kishore 7000.0
104 ramesh 8400.0
105 kishore 5000.0
106 rajesh 6000.0
Example:
# Read data from emp table
import cx_Oracle
cn=cx_Oracle.connect("system/manager@XE")
c=cn.cursor()
c.execute("select * from emp")
rows=c.fetchmany(2)
print(rows)
rows=c.fetchmany(2)
print(rows)
Output:
[(101, 'naresh', 6000.0), (102, 'suresh', 6000.0)]
[(103, 'kishore', 7000.0), (104, 'ramesh', 8400.0)]
Example:
# Read data from emp table
import cx_Oracle
cn=cx_Oracle.connect("system/manager@XE")
c=cn.cursor()
c.execute("select * from emp")
rows=c.fetchall()
print(rows)
tot=0
for row in rows:
empno,ename,sal=row
tot=tot+sal
print(f'{empno}\t{ename}\t{sal}')
executemany()
cursor.executemany(operation, seq_of_params)
Example:
# Write a program to insert 3 employees
import cx_Oracle
data=[(113,'aaa',5000),(114,'bbb',6000),(115,'ccc',9000)]
cn=cx_Oracle.connect("system/manager@XE")
c=cn.cursor()
c.executemany("insert into emp values(:1,:2,:3)",data)
cn.commit()
Example:
# Write a program to update 3 employees
import cx_Oracle
cn=cx_Oracle.connect("system/manager@XE")
c=cn.cursor()
data=[(101,200),(105,100),(109,800)]
c.executemany("update emp set salary=salary+:2 where
empno=:1",data)
cn.commit()
executescript(sql_script, /)
Create a new Cursor object and call executescript() on it with the
given sql_script. Return the new cursor object.
S1.sql
create table temp(col1 varchar2(20),
col2 varchar2(20));
Example:
# Example of executescript
import cx_Oracle
cn=cx_Oracle.connect("system/manager@XE")
c=cn.cursor()
f=open("s1.sql","r")
s=f.read()
c.executescript(s)
cn.commit()
cn.close()
Output:
Oracle does not implement executescript method.
Python and MySQL database communication
https://dev.mysql.com/downloads/installer/
Installing mysql-connector-python library
Example:
# Program to establish connection to Mysql Database
import mysql.connector
cn=mysql.connector.connect(database="database1",user="root",pa
ssword="root",host="localhost")
print("Connection Established...")
print(cn)
(OR)
import mysql.connector
cn=mysql.connector.connect(database="database1",user="root",pa
ssword="root",host="127.0.0.1")
print("Connection Established...")
print(cn)
Output:
Connection Established...
<mysql.connector.connection_cext.CMySQLConnection object at
0x000001A8E7AD4380>
Example:
# write a program to insert data into stud_marks
cn=mysql.connect(database="database1",user="root",password="ro
ot",host="127.0.0.1")
c=cn.cursor()
while True:
rollno=int(input("Enter Rollno "))
name=input("Enter Name ")
sub1=float(input("Subject1 "))
sub2=float(input("Subject2 "))
try:
c.execute("insert into stud_marks(rollno,name,sub1,sub2)
values(%s,%s,%s,%s)",params=(rollno,name,sub1,sub2))
print("student details are inserted...")
except:
print("error in inserting student details")
cn.close()
Output:
Enter Rollno 1
Enter Name naresh
Subject1 60
Subject2 70
student details are inserted...
Add another student ?yes
Enter Rollno 2
Enter Name suresh
Subject1 70
Subject2 80
student details are inserted...
Add another student ?yes
Enter Rollno 3
Enter Name kishore
Subject1 60
Subject2 50
student details are inserted...
Add another student ?yes
Enter Rollno 4
Enter Name ramesh
Subject1 98
Subject2 30
student details are inserted...
Add another student ?yes
Enter Rollno 5
Enter Name kiran
Subject1 60
Subject2 80
student details are inserted...
Add another student ?no
dbconfig.py
import mysql.connector as mysql
database="database1"
user="root"
password="root"
host="127.0.0.1"
def get_connection():
cn=mysql.connect(database=database,user=user,password=passw
ord,host=host)
return cn
dbtest.py
# Write a program to update total and avg_marks
import dbconfig
cn=dbconfig.get_connection()
c=cn.cursor()
c.execute("update stud_marks set total=sub1+sub2")
c.execute("update stud_marks set avg_marks=total/2")
cn.commit()
cn.close()
Output
import dbconfig
cn=dbconfig.get_connection()
c=cn.cursor()
rollno=int(input("Enter Rollno of Student to Delete ?"))
c.execute("Delete from stud_marks where rollno=
%s",params=(rollno,))
k=c.rowcount
if k>0:
print("student is deleted...")
else:
print("invalid rollno")
cn.commit()
Output:
Enter Rollno of Student to Delete ?5
student is deleted...
Example:
# Finding result of a student
import dbconfig
cn=dbconfig.get_connection()
c=cn.cursor()
rollno=int(input("Rollno :"))
c.execute("select * from stud_marks where rollno=
%s",params=(rollno,))
stud=c.fetchone()
if stud==None:
print("invalid rollno")
else:
rno,name,sub1,sub2,tot,avg=stud
if sub1<40 or sub2<40:
result="fail"
else:
result="pass"
print(f'''Rollno {rno}\t\tStudentName {name}
Subject1 {sub1}\t\t Subject2 {sub2}
Total {tot}\t\t Avg Marks {avg:.2f}
Result {result}''')
cn.close()
Output:
Rollno :1
Rollno 1 StudentName naresh
Subject1 60.0 Subject2 70.0
Total 130.0 Avg Marks 65.00
Result pass
Rollno :4
Rollno 4 StudentName ramesh
Subject1 98.0 Subject2 30.0
Total 128.0 Avg Marks 64.00
Result fail
Rollno :5
invalid rollno
Example:
# Finding result of a student
import dbconfig
cn=dbconfig.get_connection()
c=cn.cursor()
c.execute("select * from stud_marks")
stud=c.fetchall()
for s in stud:
rollno,name,s1,s2,t,a=s
if s1<40 or s2<40:
result="fail"
else:
result="pass"
print(rollno,name,s1,s2,t,a,result)
Output:
1 naresh 60.0 70.0 130.0 65.0 pass
2 suresh 70.0 80.0 150.0 75.0 pass
3 kishore 60.0 50.0 110.0 55.0 pass
4 ramesh 98.0 30.0 128.0 64.0 fail
Full Stack Python (Part-95)
Example:
import threading
t=threading.current_thread()
print(t)
print(t.name)
def fun1():
print("inside fun1")
fun1()
Output:
<_MainThread(MainThread, started 9664)>
MainThread
inside fun1
Example:
# Creating thread using functions or Function based thread creation
import threading
def even():
for num in range(1,21):
if num%2==0:
print(f'Even No :{num}')
def odd():
for num in range(1,21):
if num%2!=0:
print(f'Odd No :{num}')
t1=threading.Thread(target=even)
t2=threading.Thread(target=odd)
t1.start()
t2.start()
Example:
# Creating thread using functions or Function based thread creation
import threading
def even(m,n):
for num in range(m,n):
if num%2==0:
print(f'Even No :{num}')
def odd(m,n):
for num in range(m,n):
if num%2!=0:
print(f'Odd No :{num}')
t1=threading.Thread(target=even,args=(1,21))
t2=threading.Thread(target=odd,args=(1,16))
t1.start()
t2.start()
Output
Syntax:
class <thread-class-name>(threading.Thread):
def run(self):
statement-1
statement-2
User defined class inherit Thread class and override run() method.
This run() method is having operation performed by thread.
Whenever thread is executed, it execute run method of thread class
object.
Example:
import threading
class EvenThread(threading.Thread):
def run(self):
for num in range(1,21):
if num%2==0:
print(f'EvenNo {num}')
class OddThread(threading.Thread):
def run(self):
for num in range(1,21):
if num%2!=0:
print(f'OddNo {num}')
t1=EvenThread()
t2=OddThread()
t1.start()
t2.start()
Output:
class AlphaGeneratorThread(threading.Thread):
def run(self):
for num in range(65,91):
print(f'{super().name}--->{chr(num)}')
# AlphaServer
t1=AlphaGeneratorThread()
t2=AlphaGeneratorThread()
t1.name="Naresh"
t2.name="Ramesh"
t1.start()
t2.start()
Output
Full Stack Python (Part-97)
Garbage Collection
emp1=Employee(101,"naresh")
emp2=Employee(102,"suresh")
emp3=emp2
c1=sys.getrefcount(emp1)
print(c1)
c2=sys.getrefcount(emp2)
print(c2)
Output:
2
3
__del__(self)
It is a magic method of object class. This method is called as
destructor.
__del__() method is executed by PVM before object is garbage
collected.
__init__() method is executed on creation of object.
__init__() method is used for allocating resources for object.
__del__() method is used for de-allocating resources allocated within
__init__() method.
Example:
class Student:
def __init__(self): # Constructor
print("Student object is created...")
def __del__(self): # Destructor
print("Student object is deleted...")
stud1=Student()
stud1=None
Output:
Student object is created...
Student object is deleted...
Example:
class Student:
def __init__(self): # Constructor
print("Student object is created...")
def __del__(self): # Destructor
print("Student object is deleted...")
def fun1():
stud1=Student() # Local variable/local object
fun1()
Output
Student object is created...
Student object is deleted...
Example:
class Student:
def __init__(self): # Constructor
print("Student object is created...")
def __del__(self): # Destructor
print("Student object is deleted...")
def fun1(s):
print(s)
def fun2():
stud1=Student()
fun1(stud1)
fun2()
Output:
Student object is created...
<__main__.Student object at 0x000001C108A445C0>
Student object is deleted...
GUI Programming (Graphical User Interface)
Output
Enter first number 10
Enter second number 20
Enter Operator+
sum of 10 and 20 is 30
Tkinter
Syntax: Tk()
Example:
import tkinter
w=tkinter.Tk()
w.title("Window1")
w.geometry("800x400+200+300") # "widthxheight+xpos+ypos
w['bg']='cyan'
Output
Label
The tkinter label widgets can be used to show text or an image to
the screen. A label can only display text in a single font. The text can
span multiple lines.
Syntax: tkinter.Label(window,text,width,font,fg,bg)
import tkinter
import datetime
w=tkinter.Tk()
w.title("Window1")
w.geometry("1000x400+200+300") # "widthxheight+xpos+ypos
w['bg']='cyan'
label1=tkinter.Label(w,text="UserName",font=("Arial",18),fg="red",bg="
cyan")
label2=tkinter.Label(w,text="Password",font=("Arial",18),fg="red",bg="
cyan")
label3=tkinter.Label(w,text="Date and
Time",font=("Arial",18),fg="red",bg="cyan")
label4=tkinter.Label(w,text=str(datetime.datetime.now()),font=("Arial"
,18),fg="red",bg="cyan")
label1.place(x=100,y=100)
label2.place(x=100,y=150)
label3.place(x=400,y=10)
label4.place(x=580,y=10)
Entry widget
Entry widgets are the basic widgets of Tkinter used to get input, i.e.
text strings, from the user of an application. This widget allows the
user to enter a single line of text.
Syntax: tikiner.Entry(window,width,font,bg,fg,show)
Example:
import tkinter
w=tkinter.Tk()
w.title("Window1")
w.geometry("1000x400+200+300") # "widthxheight+xpos+ypos
w['bg']='cyan'
label1=tkinter.Label(w,text="UserName",font=("Arial",15),bg="cyan",fg
="red")
label2=tkinter.Label(w,text="Password",font=("Arial",15),bg="cyan",fg=
"red")
e1=tkinter.Entry(w,width=20,font=("Arial",15),fg="blue",bg="yellow")
e2=tkinter.Entry(w,width=20,font=("Arial",15),fg="blue",show="$",bg="y
ellow")
label1.place(x=300,y=100)
label2.place(x=300,y=150)
e1.place(x=450,y=100)
e2.place(x=450,y=150)
Button widget
Syntax: tkinter.Button(window,text,width,height,font,bg,fg)
Example:
import tkinter
w=tkinter.Tk()
w.title("Window1")
w.geometry("1000x400+200+300") # "widthxheight+xpos+ypos
w['bg']='cyan'
label1=tkinter.Label(w,text="UserName",font=("Arial",15),bg="cyan",fg
="red")
label2=tkinter.Label(w,text="Password",font=("Arial",15),bg="cyan",fg=
"red")
e1=tkinter.Entry(w,width=20,font=("Arial",15),fg="blue",bg="yellow")
e2=tkinter.Entry(w,width=20,font=("Arial",15),fg="blue",show="$",bg="y
ellow")
b1=tkinter.Button(w,text="Login",font=("Arial",15),fg="blue",width=20)
label1.place(x=300,y=100)
label2.place(x=300,y=150)
e1.place(x=450,y=100)
e2.place(x=450,y=150)
b1.place(x=400,y=200)
Output
Full Stack Python (Part-99)
Min-Project
Example:
import mysql.connector as mysql
import tkinter as gui
import tkinter.messagebox
cn=mysql.connect(database="database1",user="root",password="ro
ot")
w=gui.Tk()
w.geometry("300x200")
w.title("User Register")
l1=gui.Label(w,text="Name",font=("Arial",14))
l2=gui.Label(w,text="UserName",font=("Arial",14))
l3=gui.Label(w,text="Password",font=("Arial",14))
e1=gui.Entry(w,width=20,font=("Arial",14))
e2=gui.Entry(w,width=20,font=("Arial",14))
e3=gui.Entry(w,width=20,font=("Arial",14),show='*')
def register():
c=cn.cursor()
try:
name=e1.get()
user=e2.get()
pwd=e3.get()
c.execute("insert into user_register values(%s,%s,
%s)",params=(name,user,pwd))
tkinter.messagebox.showinfo(title="info",message="User
Registered...")
cn.commit()
e1.delete(0,gui.END)
e2.delete(0,gui.END)
e3.delete(0,gui.END)
except:
tkinter.messagebox.showerror(title="error",message="Error in
registering user")
def close():
w.destroy()
b1=gui.Button(w,text="Register",font=("Arial",14),command=register)
b2=gui.Button(w,text="Exit",width=10,font=("Arial",14),command=clos
e)
l1.grid(row=1,column=1)
e1.grid(row=1,column=2)
l2.grid(row=2,column=1)
e2.grid(row=2,column=2)
l3.grid(row=3,column=1)
e3.grid(row=3,column=2)
b1.grid(row=4,column=1)
b2.grid(row=4,column=2)
Example of login:
cn=mysql.connect(database="database1",user="root",password="ro
ot")
w=gui.Tk()
w.geometry("300x200")
w.title("Login")
l1=gui.Label(w,text="UserName",font=("Arial",14))
l2=gui.Label(w,text="Password",font=("Arial",14))
e1=gui.Entry(w,width=20,font=("Arial",14))
e2=gui.Entry(w,width=20,font=("Arial",14),show='*')
def login():
user=e1.get()
pwd=e2.get()
c=cn.cursor()
c.execute("select * from user_register where uname=%s and pwd=
%s",params=(user,pwd))
row=c.fetchone()
if row==None:
tkinter.messagebox.showinfo(title="info",message="Invalid
username or password")
else:
tkinter.messagebox.showinfo(title="Welcome",message="Welcome
to Application")
def close():
w.destroy()
b1=gui.Button(w,text="Login",font=("Arial",14),command=login)
b2=gui.Button(w,text="Exit",width=10,font=("Arial",14),command=clos
e)
l1.grid(row=1,column=1)
l2.grid(row=2,column=1)
e1.grid(row=1,column=2)
e2.grid(row=2,column=2)
b1.grid(row=3,column=1)
b2.grid(row=3,column=2)
import mysql.connector as mysql
import tkinter as gui
import tkinter.messagebox
cn=mysql.connect(database="database1",user="root",password="ro
ot")
w=gui.Tk()
w.geometry("300x200")
def marks_window():
w1=gui.Tk()
w1.geometry("300x200")
l1=gui.Label(w1,text="Rollno",font=("Arial",14))
l2=gui.Label(w1,text="Name",font=("Arial",14))
l3=gui.Label(w1,text="Subject1",font=("Arial",14))
l4=gui.Label(w1,text="Subject2",font=("Arial",14))
e1=gui.Entry(w1,width=10)
e2=gui.Entry(w1,width=10)
e3=gui.Entry(w1,width=10)
e4=gui.Entry(w1,width=10)
l1.grid(row=1,column=1)
l2.grid(row=2,column=1)
l3.grid(row=3,column=1)
l4.grid(row=4,column=1)
e1.grid(row=1,column=2)
e2.grid(row=2,column=2)
e3.grid(row=3,column=2)
e4.grid(row=4,column=2)
def save():
rno=e1.get()
name=e2.get()
s1=e3.get()
s2=e4.get()
c=cn.cursor()
c.execute("insert into student_marks values(%s,%s,%s,
%s)",params=(rno,name,s1,s2))
cn.commit()
tkinter.messagebox.showinfo(title="info",message="marks
details are saved")
e1.delete(0,gui.END)
e2.delete(0,gui.END)
e3.delete(0,gui.END)
e4.delete(0,gui.END)
b1=gui.Button(w1,text="Save",command=save)
b1.grid(row=5,column=1)
def find_window():
w3=gui.Tk()
w3.geometry("300x200")
w3.title("Find Result")
l1=gui.Label(w3,text="Rollno",font=("Arial",14))
e1=gui.Entry(w3,width=10)
l1.grid(row=1,column=1)
e1.grid(row=1,column=2)
def find():
c=cn.cursor()
c.execute("select rollno,name,sub1,sub2,sub1+sub2 from
student_marks where rollno=%s",params=(e1.get(),))
row=c.fetchone()
if row==None:
tkinter.messagebox.showinfo(title="info",message="Invalid
Rollno")
else:
result="pass" if row[2]>=40 and row[3]>=40 else "fail"
a=map(str,row)
s=" ".join(a)
s=s+" "+result
l2=gui.Label(w3,text=s,font=("Arial",14))
l2.grid(row=2,column=1)
b1=gui.Button(w3,text="Find Result",command=find)
b1.grid(row=3,column=1)
b1=gui.Button(w,text="Marks
Entry",font=("Arial",14),command=marks_window)
b2=gui.Button(w,text="Find
Result",font=("Arial",14),command=find_window)
b1.pack(fill=gui.BOTH,expand=True)
b2.pack(fill=gui.BOTH,expand=True)
Full Stack Python (Part-100)
Min-Project
b1.grid(row=5,column=1)
def find_window():
w3=gui.Tk()
w3.geometry("300x200")
w3.title("Find Result")
l1=gui.Label(w3,text="Rollno",font=("Arial",14))
e1=gui.Entry(w3,width=10)
l1.grid(row=1,column=1)
e1.grid(row=1,column=2)
def find():
c=cn.cursor()
c.execute("select rollno,name,sub1,sub2,sub1+sub2 from
student_marks where rollno=%s",params=(e1.get(),))
row=c.fetchone()
if row==None:
tkinter.messagebox.showinfo(title="info",message="Invalid
Rollno")
else:
result="pass" if row[2]>=40 and row[3]>=40 else "fail"
a=map(str,row)
s=" ".join(a)
s=s+" "+result
l2=gui.Label(w3,text=s,font=("Arial",14))
l2.grid(row=2,column=1)
b1=gui.Button(w3,text="Find Result",command=find)
b1.grid(row=3,column=1)
b1=gui.Button(w,text="Marks
Entry",font=("Arial",14),command=marks_window)
b2=gui.Button(w,text="Find
Result",font=("Arial",14),command=find_window)
b1.pack(fill=gui.BOTH,expand=True)
b2.pack(fill=gui.BOTH,expand=True)