0% found this document useful (0 votes)
33 views635 pages

Pdf24 Merged

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views635 pages

Pdf24 Merged

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 635

Programming Fundamentals

1. Character set of Python


2. Tokens
a. Keywords
b. Identifiers
c. Literals
d. Data Types
e. Operators

Character set of python

Character set defines encoding and decoding standard used by


python programming language.
Character set defines set of characters supported by python
programming language.

There are two encoding standards supported by python language


1. ASCII  American Standard Code for information Interchange
2. UNICODE  Universal code

ASCII support 256 characters 0-255, these 256 characters includes


Characters in English (a-z,A-Z), Digits (0-9), Sepcial characters (+,-,*,/,
%#!,…)

UNICODE super set of ASCII, It support characters of ASCII and also


having more number of characters support from other languages.

UNICODE support more than 1,00,000 characters.

Python and all modern languages support ascii and Unicode


character set.
Uppercase Letters A – 65
B -66

Z – 90
Lowercase Letters a -97
b-98

z-122
Tokens
A token is smallest individual unit within program.
Without tokens a statement cannot created.

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.

How to find keywords of python?

>>> import keyword


>>> keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class',
'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global',
'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return',
'try', 'while', 'with', 'yield']

How many keywords are in python?


>>> len(keyword.kwlist)
35

Python 3.12 version supports 35 keywords.


Python is case-sensitive language; it finds the difference between
uppercase and lowercase.

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

Identifier is a single word, this word is created using alphabets (a-z, A-


Z), digits (0-9) and one special character (_)
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

Integer is allowed only one special character _.


Grouping digits are done using _
_ cannot use as a prefix or suffix

>>> 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

Applications of octal integers


1. Assembly Language/Embedded Applications
2. Representing an integer which does not allows digits 8 and 9

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.

Applications of hexadecimal integer


1. Color Values
2. Unicode Values
3. Memory Addresses

>>> 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

Applications of binary integer


1. Internal data representation
2. Machine language
3. Image Processing
4. Audio or video processing

>>> 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

Identifier is a single word, this word is created using alphabets (a-z, A-


Z), digits (0-9) and one special character (_)

1. Identifier should not be keyword

>>> 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

2. Identifier can be defined in uppercase or lowercase. Python is


a case sensitive language, which finds the difference between
uppercase and lowercase

>>> A=10
>>> a=20
>>> A
10
>>> a
20

3. There should not be any space between identifier

>>> student number=1


SyntaxError: invalid syntax

4. Identifier is allowed only one special character _

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

6. Length of identifier is unlimited

>>> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa=10
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
10
>>>
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
bb=100
>>>
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
bb
100
>>> a=10
>>> b=20
>>> a+b
30

Naming Conventions

Naming Conventions are nothing but naming rules, this naming


convention makes application easy to understand.

1. pascal case
2. snake case
3. camelcase

Pascal case is used to define class names.


Example: Student, Employee, CurrentAccount
Snake case is used to create variables
Example: rollno, employee_no,account_no,otp_no
Camel case is used to define functions
Example:
mean(),mode(),median(),login(),deposit(),createAccount()

Data types and Literals

Data types

Data types are used to reserve memory for data/literals.


Python data types are classified into 2 categories
1. Scalar Data types
2. Collection 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

Python is pure object oriented programming language. Every data


type in python is a class and data is represented as objects.

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.

Statically Typed Programming Dynamically typed programming


Language language

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.

int data type

int data type/class is used to construct integer objects.


Int data type is used by python virtual machine for allocating
memory for integer value/literal.
Integer is a numeric value without fractional part.

Eg: 1, 560, 5789


>>> a=123
>>> type(a)
<class 'int'>
>>> a
123
>>> b=560
>>> type(b)
<class 'int'>
>>> b
560

In python integer values are represented in 4 formats


1. Decimal
2. Octal
3. Hexadecimal
4. Binary

Number system define set of rules and regulations for representing


numbers in computer science.

Size of int data type is dynamic. The memory is allocated based


value size. Int data type size is unlimited.

>>>
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

Applications of binary integer


1. Internal data representation
2. Machine language
3. Image Processing
4. Audio or video processing

>>> 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

All scalar data types are immutable.


After creating object, value cannot modify or after creating object
changes cannot be done.
How to find id or address of object?
Every object in memory is identified with unique number called id or
address. This id or address is generated by PVM.
Address of object is find using id() function.

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

Base conversion functions


Python provides 3 base conversion functions
1. Oct() 🡪 This return octal representation of integer value
2. Hex() 🡪 This return hexadecimal representation of integer value
3. Bin() 🡪 This return binary representation of integer value

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'

float data type


float literal or value is represented in python using float data type or
class.
Float value is a numeric value with fractional part.
This size of float data type is 8bytes.

Finding information about float data type

>>> import sys


>>> sys.float_info
sys.float_info(max=1.7976931348623157e+308, max_exp=1024,
max_10_exp=308, min=2.2250738585072014e-308, min_exp=-1021,
min_10_exp=-307, dig=15, mant_dig=53,
epsilon=2.220446049250313e-16, radix=2, rounds=1)

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

Float value is represented in two formats or notations


1. Fixed notation or fixed format
2. Scientific notation/exponent notation or scientific format

>>> f1=12.456
>>> f1
12.456
>>> f2=12456e-3
>>> f2
12.456
>>> f3=1.234e2
>>> f3
123.4

In scientific notation one special character used in float value called


“e”, the value of “e” is 10.
>>> a=1.7976931348623157e+308
>>> a
1.7976931348623157e+308
>>> b=1.7976931348623157e+309
>>> b
inf
>>> c=0b1010.10
SyntaxError: incomplete input
>>> d=0xab.a
Traceback (most recent call last):
File "<pyshell#67>", line 1, in <module>
d=0xab.a
AttributeError: 'int' object has no attribute 'a'

Complex data type

Complex data type or class is used to represent complex


number/literal.
Complex number is having two values
1. Real
2. Imag

>>> 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

bool data type


This data type is used to represent Boolean values.
In python Boolean values are represented using two keywords
1. True
2. False

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

String is non numeric data type.


String is a collection of characters. These characters can be
alphabets, digits or special characters.
A string which consists of only alphabets is called alphabetic string.
A string which consists of alphabets or digits is called alphanumeric
string.
String is a collection type or sequence type.
String is an immutable sequence data type.

In python string is represented,


1. Within single quotes
2. Within double quotes
3. Within triple single quotes or double quotes

Within single quotes, python programmers represent single line string.


Within single quotes, we can insert double quotes.

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

Within double quotes we can represent single line string

>>> 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

Within double quotes we can insert single quotes

>>> str5="python is 'high level' programming language"


>>> print(str5)
python is 'high level' programming language

Within triple single quotes or double quotes we can represent


multiline string.

>>> 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

In python comments are created using # (pound sign)


It is used to create single line comment.

test1.py
# This is my first program in python

print("Hello") # this statement is used to print a message Hello

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.

Every program required 3 things,


1. Output
2. Input
3. Process

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.

Print function required input to print data or information.


Print function is having 3 inputs
1. data/values
2. sep
3. end
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.

Print function required input to print data or information.


Print function is having 3 inputs
1. data/values
2. sep
3. end
if no input is given to print function, it insert blank line

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

Default end value is \n 🡪 newline

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

n1=input("Enter First Value ")


n2=input("Enter Second Value ")
n3=n1+n2
print(f'sum of {n1} and {n2} is {n3}')

Output:
Enter First Value 10
Enter Second Value 20
sum of 10 and 20 is 1020

How to see content of module/library?


>>> import calendar
>>> dir(calendar)
['APRIL', 'AUGUST', 'Calendar', 'DECEMBER', 'Day', 'EPOCH', 'FEBRUARY',
'FRIDAY', 'HTMLCalendar', 'IllegalMonthError', 'IllegalWeekdayError',
'IntEnum', 'JANUARY', 'JULY', 'JUNE', 'LocaleHTMLCalendar',
'LocaleTextCalendar', 'MARCH', 'MAY', 'MONDAY', 'Month',
'NOVEMBER', 'OCTOBER', 'SATURDAY', 'SEPTEMBER', 'SUNDAY',
'THURSDAY', 'TUESDAY', 'TextCalendar',

Type Conversion Function or Type Casting


Type conversion is a process of converting one type of object to
another type.

1. Int()
2. Float()
3. Complex()
4. Bool()
5. Str()

All these are in-built functions and available in default module


imported by any python program called __builtins__

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)

Syntax-1 is used to convert float,int,bool to integer object


Syntax-2 is used to convert string to integer object
Example:
# Write a program to print sum of integers
# input two integers from keyboard

n1=input("Enter First Value ")


n2=input("Enter Second Value ")
n3=int(n1)+int(n2)
print(f'sum of {n1} and {n2} is {n3}')

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

a=float(input("Enter value of a "))


b=float(input("Enter value of b "))
print(f'before swaping a={a} and b={b}')
c=a
a=b
b=c
print(f'after swaping a={a} and b={b}')
a,b=b,a
print(f'after swaping a={a} and b={b}')
a=a+b
b=a-b
a=a-b
print(f'after swaping a={a} and b={b}')

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

comp1=complex(input("input complex number1 "))


comp2=complex(input("input complex number2 "))
comp3=comp1+comp2
print(f'sum of {comp1} and {comp2} is {comp3}')

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()

ord(char) 🡪 This function return ASCII value of input character


chr(ascii) 🡪 This function return Character value of input ASCII value

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

These operators are used to perform arithmetic operations.


All arithmetic operators are binary operators.

Operator Description
+ Adding or Concatenation
- Subtraction
* Multiplication or Repeat
/ Float Division
// Floor Division
% Modulo
** Exponent or Power

+ operator is used to perform two operations


1. Adding
2. Concatenating
It performs addition, if two operands are numbers
It performs concatenation, if two operands sequences (list, tuple,
string ,…)

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

a=eval(input("Enter first number "))


b=eval(input("Enter second number "))
c=a+b
print(f'sum of {a} and {b} is {c}')

Output
Enter first number 10
Enter second number 20
sum of 10 and 20 is 30

Enter first number 1.5


Enter second number 1.2
sum of 1.5 and 1.2 is 2.7

Enter first number 1+2j


Enter second number 1+1j
sum of (1+2j) and (1+1j) is (2+3j)

- Operator (arithmetic subtract operator)

This operator is used for subtraction of two numbers.

>>> 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

comp1=complex(input("input complex number1 "))


comp2=complex(input("input complex number2 "))
comp3=comp1+comp2
print(f'sum of {comp1} and {comp2} is {comp3}')

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()

ord(char)  This function return ASCII value of input character


chr(ascii)  This function return Character value of input ASCII value

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

These operators are used to perform arithmetic operations.


All arithmetic operators are binary operators.

Operator Description
+ Adding or Concatenation
- Subtraction
* Multiplication or Repeat
/ Float Division
// Floor Division
% Modulo
** Exponent or Power

+ operator is used to perform two operations


1. Adding
2. Concatenating
It performs addition, if two operands are numbers
It performs concatenation, if two operands sequences (list, tuple,
string ,…)

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

a=eval(input("Enter first number "))


b=eval(input("Enter second number "))
c=a+b
print(f'sum of {a} and {b} is {c}')

Output
Enter first number 10
Enter second number 20
sum of 10 and 20 is 30

Enter first number 1.5


Enter second number 1.2
sum of 1.5 and 1.2 is 2.7

Enter first number 1+2j


Enter second number 1+1j
sum of (1+2j) and (1+1j) is (2+3j)

- Operator (arithmetic subtract operator)

This operator is used for subtraction of two numbers.

>>> 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

l=float(input("Enter value of l"))


b=float(input("Enter value of b"))
area=l*b
print(f'area of rectangle with l={l:.2f} and b={b:.2f} is {area:.2f}')

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

/ division operator or float division operator

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)

// floor division operator or integer division

>>> 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

**power of operator or exponent operator

>>> res1=5**2
>>> print(res1)
25
>>> res2=5**0
>>> print(res2)
1
>>> res3=10**-1
>>> print(res3)
0.1

Precedence of operators

The following table summarizes the operator precedence in Python,


from highest precedence (most binding) to lowest precedence
(least binding). Operators in the same box have the same
precedence. Unless the syntax is explicitly given, operators are
binary. Operators in the same box group left to right (except for
exponentiation and conditional expressions, which group from right
to left).

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

These operators are used to compare object values or state.

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

name=input("Enter Name ")


age=int(input("Enter Age "))
result=f'{name} is elg to vote ' if age>=18 else f'{name} is not elg vote'
print(result)

Output:
Enter Name suresh
Enter Age 30
suresh is elg to vote

Enter Name kishore


Enter Age 14
kishore is not elg vote

Example:
# Write a program to find input number is even or odd

num=int(input("Enter any number "))


rem=num%2
a=f'{num} is even' if rem==0 else f'{num} is odd'
print(a)

Output:
Enter any number 4
4 is even

Enter any number 9


9 is odd

Example:
# Write a program to find max of two numbers

num1=int(input("Enter First Number "))


num2=int(input("Enter Second Number "))
res=f'{num1} is max' if num1>num2 else f'{num2} is max'
print(res)

Output:
Enter First Number 10
Enter Second Number 5
10 is max

Enter First Number 5


Enter Second Number 20
20 is max

Enter First Number 10


Enter Second Number 10
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.

1. and 🡪 Binary Operator


2. or 🡪 Binary Operator
3. not 🡪 Unary Operator

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

name=input("Enter Name ")


sub1=int(input("Enter Subject1 Marks "))
sub2=int(input("Enter Subject2 Marks "))
total=sub1+sub2
avg=total/2
result="pass" if sub1>=40 and sub2>=40 else "fail"
print(f'''Name {name}
Subject1 {sub1}
Subject2 {sub2}
Total {total}
Avg {avg:.2f}
Result {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

Enter Name suresh


Enter Subject1 Marks 30
Enter Subject2 Marks 99
Name suresh
Subject1 30
Subject2 99
Total 129
Avg 64.50
Result fail

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

user=input("UserName :") # nit


pwd=input("Password :") # nit123

print("Welcome") if user=="nit" and pwd=="nit123" else print("invalid


username or password")

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

If any operand is True, the complete expression return True.


If opr1 is True, PVM return result of opr1 without evaluating opr2
If opr1 is False, PVM evaluates opr2 and return result of opr2

True or False
True
>>> False or True
True
>>> False or False
False
>>> 100 or 200
100
>>> 100 or 200 or 300
100

Precedence of logical operator


1. not
2. and
3. or

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

ch=input("Enter Single Character ")


print("Vowel") if ch=='a' or ch=='e' or ch=='i' or ch=='o' or ch=='u' else
print("not vowel")

Output:
Enter Single Character i
Vowel

Enter Single Character x


not vowel

Example:
# Write a program to find input number is +ve,-ve or zero

num=int(input("Enter any number "))


print("+ve") if num>0 else print("-ve") if num<0 else print("zero")

Output:
Enter any number 5
+ve

Enter any number -6


-ve

Enter any number 0


Zero

Example:
# Write a program to find input character is alphabet,digit or special
character

ch=input("Enter any character ")


print("alphabet") if ch>='A' and ch<='Z' or ch>='a' and ch<='z' else
print("Digit") if ch>='0' and ch<='9' else print("special character")

Output:
Enter any character a
alphabet

Enter any character A


alphabet

Enter any character 7


Digit

Enter any character *


special character
ord('A')
65
>>> ord('Z')
90
>>> ord('a')
97
>>> ord('z')
122
>>> ord('0')
48
>>> ord('9')
57
>>> 'A'>'B'
False
>>> chr(65)
'A'
>>> chr(97)
'a'

not operator
not is a unary operator, this operator required 1 operand
truth table of not operator
Opr1 Not Opr1
True False
False True

Not operator is used with other operator.


Example: not>,not in, is not

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

Membership operator is used with collection data types for


searching given value in collection values.

Syntax: value/object in collection

In operator returns Boolean value (True/False)

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

ch=input("Enter any character ")


print("vowel") if ch in "aeiouAEIOU" else print("not vowel")

Output
Enter any character a
vowel

Enter any character x


not 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

Every object is having identity, this identity is called address.


What is difference between == and is operator in python?
== Is
It is a relational operator It is identity operator
This operator is used to compare This operator is used to compare
values of object (OR) object identity of objects. If two
equality variables are pointing to same
object in memory this operator
returns True 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

Walrus Operator (Python 3.8)


:= is called walrus operator or assignment expression operator
Walrus Operator (Python 3.8)
:= is called walrus operator or assignment expression operator
It is a binary operator and this operator is used as part of expression.

>>> 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

1. Right shift operator >>


2. Left shift operator <<

>> 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

Formula : value//2 pow n

>>> 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

Opr1 Opr2 Opr1 & Opr2


1 0 0
0 1 0
1 1 1
0 0 0

If any input bit is 0, output is 0

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

Bitwise (|) or operator


This operator is used to apply or gate
Truth table of bitwise| operator

Opr1 Opr2 Opr1 | Opr2


1 0 1
0 1 1
1 1 1
0 0 0

If any input bit is 1, output 1

>>> 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

Bitwise XOR (^) Operator


This operator is used to apply XOR gate
Truth table of XOR operator

Opr1 Opr2 Opr1^opr2


1 0 1
0 1 1
0 0 0
1 1 0

>>> 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

Assignment Operator OR Update operators

Any of the operators can be combined with assignment. The means


that += , -= , *= , /= , //= , %= , **= , >>= , <<= , &= , ^= , and |=

augmented assignment statement is a single operator perform two


operations.
1. Binary operation
2. Assignment

>>> 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.

Command line arguments are used to develop utilities or tools or


commands in python.

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?

Select 🡪 Run 🡪 Run Customized

Control Statements

1. Conditional Control Statements


a. If
b. Match
2. Looping control Statements
a. While
b. For
c. Nested looping
3. Branching Statements
a. Break
b. Continue
c. Pass
d. Return

Control statements are used to control the flow of execution of


program.

Control statements are three types

1. Conditional control statements


2. Looping control statements
3. Branching statements

Conditional Control Statements


Python support two conditional control statements
1. if
2. match (python 3.10)

Conditional control statements are used to execute block of


statements based on condition or selection.

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

if without else is called simple if.

Syntax:

If <condition>:
Statement-1
Statement-2
Statement-3

If condition is True, PVM


executes Statement-
1,Statement-2 and Statement-3
If condition is False, PVM
executes statement-3

In python block must have one statement.s

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

This syntax is having two blocks


1. if block
2. else block

Syntax:

If <condition>:
Statement-1
Statement-2
else:
Statement-3
Statement-4

Statement-5

If condition is True, PVM


executes Statement-
1,Statement-2 and Statement-5
If condition is False, PVM
executes Statement-3,
Statement4 and Statement-5

Example:
# Write a program to verify input number divisible with 7 or not

num=int(input("Enter any number "))


if num%7==0:
print(f'{num} is divisible with 7')
else:
print(f'{num} is not divisible with 7')

Output:
Enter any number 14
14 is divisible with 7

Enter any number 12


12 is not divisible with 7

Example:

# Write a program to display "Hello" if input number is multiples of 5


else display "Bye"

num=int(input("Enter any Number "))


if num%5==0:
print("Hello")
else:
print("Bye")

Output:
Enter any Number 20
Hello
Enter any Number 22
Bye

Home Work

1. Write a program to find input year is leap or not


2. Write a program to find input number last digit is even or odd
3. Write a program to check input number is 3 digit or not
4. Write a program to check a person is senior citizen or not
5. Write a program to find minimum value of input two values
6. Write a program to find input number is +ve or –ve
7. Write a program to find input number is divisible 2 and 3
if..elif..else (if..else ladder)

This syntax allows checking more than one condition.


Syntax:

If condition1:
Statement-1
elif condition2:
Statement-2
elif condition3:
Statement-3

else:
Statement-n

If condition1 is True PVM execute


Statement-1
If condition1 is False and
Condition2 is True, PVM executes
statement-2
If condition1,condition2 is False
and condition3 is True, PVM
executes Statement-3
If all conditions are False, PVM
executes Statement-n
Example:

# Write a program to find input character is alphabet,digit or sepcial


character

ch=input("Enter any character ")


if ch>='A' and ch<='Z' or ch>='a' and ch<='z':
print("alphabet")
elif ch>='0' and ch<='9':
print("digit")
else:
print("special character")

Output:
Enter any character a
alphabet

Enter any character 5


digit

Enter any character $


special character

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'Bike Price {cost}')


print(f'Road Tax {tax:.2f}')

salary=int(input("Enter Salary "))


service=int(input("Enter Service "))
if service>10:
bonus=salary*10/100
elif service>=6 and service<=10:
bonus=salary*8/100
else:
bonus=salary*5/100

print(f'Salary {salary}')
print(f'Bonus {bonus}')

Output:
Enter Salary 50000
Enter Service 12
Salary 50000
Bonus 5000.0

Enter Salary 30000


Enter Service 7
Salary 30000
Bonus 2400.0

Example:
# Write a program to convert input alphabet into uppercase to
lower case,
# lowercase to uppercase

ch=input("Enter any character ")


if ch>='a' and ch<='z':
ch=chr(ord(ch)-32)
print(ch)
elif ch>='A' and ch<='Z':
ch=chr(ord(ch)+32)
print(ch)
else:
print("input character must be alphabet")

Output:
Enter any character $
input character must be alphabet

Enter any character 7


input character must be alphabet

Enter any character a


A

Enter any character A


A

Nested if

If within if is called nested if.


Syntax:

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:

# Write a program to input digit [0-9] and print in word


# input : 4
# output :Four

digit=int(input("Enter any Digit (0-9): "))


match(digit):
case 0:
print("Zero")
case 1:
print("One")
case 2:
print("Two")
case 3:
print("Three")
case 4:
print("Four")
case 5:
print("Five")
case 6:
print("Six")
case 7:
print("Seven")
case 8:
print("Eight")
case 9:
print("Nine")
case _:
print("Invalid Digit")
Output:
Enter any Digit (0-9): 3
Three

Enter any Digit (0-9): 9


Nine

Enter any Digit (0-9): 10


Invalid Digit

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

ch=input("Enter any character ")


match(ch):
case 'a':
print("vowel")
case 'e':
print("vowel")
case 'i':
print("vowel")
case 'o':
print("vowel")
case 'u':
print("vowel")
case _:
print("not vowel")

Output:
Enter any character e
vowel

Enter any character x


not vowel
Example:
>>> list1=[10,20,30,40,50]
>>> match(list1):
... case [10,20,30,40,50]:
... print("Hello")

Looping Control Statements


Looping control statements are used to repeat one or more than
one statement number of times or until given condition.

Python support 2 Looping control statements


1. while
2. for

while loop

“while” keyword represents while loop


While loop execute given block of statements until given condition is
True.
Syntax:

while <condition>:
statement-1
statement-2

PVM repeat statement-


1,statement-2 until given
condition is True.

While loop required 3 statements


1. initialization statement
2. condition
3. update statement

Initialization statement defines initial value of condition.


Condition is a Boolean expression which defines how many times
while loop has to execute.
Update statement, which updates condition.
Example:
# Write a program to input 5 numbers and print sum

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

num=int(input("Enter any number "))


c=0
if num==0:
c=1
else:
while num>0:
num=num//10
c=c+1

print(f'Count of digits {c}')

Output:
Enter any number 0
Count of digits 1

Enter any number 168


Count of digits 3
Example:

# Write a program to find sum of digits of input number

num=int(input("Enter any number "))


s=0

while num>0:
r=num%10
s=s+r
num=num//10

print(f'Sum of digits {s}')

Output:
Enter any number 123
Sum of digits 6

Enter any number 54


Sum of digits 9

Enter any number 0


Sum of digits 0
Example:

# Write a program to count how many even and odd digits exists
within input number

num=int(input("Enter any number ")) # 123


ecount=0
ocount=0

while num>0:
r=num%10
if r%2==0:
ecount=ecount+1
else:
ocount=ocount+1
num=num//10

print(f'Even count digits {ecount}')


print(f'Odd count digits {ocount}')

Output:
Enter any number 4893
Even count digits 2
Odd count digits 2

Enter any number 123


Even count digits 1
Odd count digits 2
Example:
# Write a program to find input number is armstrong or not (3digit
number)

num=int(input("Enter any number "))


num1=num
s=0
while num>0:
r=num%10
s=s+(r**3)
num=num//10

if s==num1:
print(f'{num1} armstrong')
else:
print(f'{num1} is not armstrong')

Output
Enter any number 153
153 armstrong

Enter any number 125


125 is not armstrong

Enter any number 370


370 armstrong
Example:
# Write a program to find an input number is perfect number or not

num=int(input("enter any number "))

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

enter any number 5


5 is not perfect number
Example:
# Write a program to find input number is palindrome or not

num=int(input("Enter any number "))


num1=num
rev=0

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

Write a program to print number in words

123

ONE TWO THREE

489

Four Eight Nine


Write a program to print number in words
123
ONE TWO THREE
489
Four Eight Nine

num=int(input("Enter any number "))


rev=0
while num>0:
r=num%10
rev=(rev*10)+r
num=num//10
while rev>0:
r=rev%10
match(r):
case 1:
print("one",end=' ')
case 2:
print("two",end=' ')
case 3:
print("three",end=' ')
case 4:
print("four",end=' ')
case 5:
print("five",end=' ')
case 6:
print("six",end=' ')
case 7:
print("seven",end=' ')
case 8:
print("eight",end=' ')
case 9:
print("nine",end=' ')
case 0:
print("zero",end=' ')
rev=rev//10

for loop

“for” keyword represents for loop.


For loop is used to repeat one or more than one statement number
of times.
For loop is called iterator, which iterate values from iterables
(collections (OR) for loop is used to read values from collections.

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

str1=input("Enter any string ")


c=0
for ch in str1:
c=c+1

print(f'Length of string {c}')

Output:
Enter any string python
Length of string 6

Enter any string java


Length of string 4
Example:
# Write a program to count
# alphabets, digits and sepcial character exists within input string

str1=input("Enter any string ")

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

print(f'Alphabet Count {ac}')


print(f'Digit Count {dc}')
print(f'Special Character Count {sc}')

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.

Application development range data type is used,


1. To repeat for loop number of times
2. To generate values from other collection types or containers.

The range type represents an immutable sequence of numbers and


is commonly used for looping a specific number of times in for loops

How to create range object?


Syntax-1: range(stop)
Syntax-2: range(start,stop,step)

range object is having 3 attributes.


1. Start
2. Stop
3. Step

Start: starting value of range


Stop: stop value of range
Step: increment or decrement value

Start and Stop values are given based on Step value.

Step is +ve 🡪 start<stop


Step is –ve 🡪 start>stop
Syntax-1: range(stop)
This syntax is used to generate sequence of +ve integer values.
In this syntax default start=0,step=+1

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()

# range required integer input


#for i in range(1.0,6.0):
# print(i)

# the step of value range should not be zero


#for i in range(1,10,0):
# print(i)

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

num=int(input("Enter any number "))

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

Defining a looping statement within looping statement is called


nested looping statement.

1. Nested for
2. Nested while

Nested for loop


for loop inside for loop is called nested for loop.

Syntax:

for variable-name in iterable: # outer loop


for variable-name in iterable: # inner loop
statement-1
statement-2
statement-3

Example:
# Write a program to generate tables from 1 to 5

for num in range(1,6): # 1 2 3 4 5


for i in range(1,11): # 1 2 3 4 5 6 7 8 9 10
print(f'{num}x{i}={num*i}')

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

for num in range(1,6): # 1 2 3 4 5


fact=1
for i in range(1,num+1): # 1 2 3 4 5
fact=fact*i
print(f'Factorial of {num}-->{fact}')

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

for num in range(2,21): # 2 3 4 5 6 7 8 9 10 11 12 13 ... 20


c=0
for i in range(1,num+1):
if num%i==0:
c=c+1
if c==2:
print(f'{num} is prime')

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

n=int(input("enter value of n"))


for num in range(1,n+1): # start=1,stop=5,step=1 --> 1 2 3 4 5
print(f'{num}-->{num**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

m=int(input("enter value of m")) # 5


n=int(input("enter value of n")) # 20
for num in range(m,n+1): # start=5,stop=21,step=1 --> 5 6 7 8 9 10 ...
20
if num%2==0:
print(num)

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

for num in range(65,91):


print(f'{chr(num)}-->{num}')

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

num=int(input("Enter any number "))


c=0
for i in range(1,num+1):
if num%i==0:
c=c+1

if c==2:
print(f'{num} is prime')
else:
print(f'{num} is not prime')

Output:
Enter any number 4
4 is not prime

Enter any number 7


7 is prime
Example:
# Write a program to print first 10 even numbers in reverse order

for num in range(20,0,-2): # start=20,stop=0,step=-2


print(num)

Output:
20
18
16
14
12
10
8
6
4
2

# Write a program to find factorial of input number

num=int(input("Enter any number ")) # 3


fact=1
for i in range(1,num+1): # start=1,stop=4,step=1 --> 1 2 3
fact=fact*i

print(f'{num} factorial is {fact}')


# Accept 10 numbers from user and display their avg

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

print(f'Minimum Value {min_value}')


print(f'Maximum Value {max_value}')

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

# Write a program to display sum of odd numbers and even number


that fall between 12 and 37

even_sum=0
odd_sum=0
for num in range(12,38):
if num%2==0:
even_sum+=num
else:
odd_sum+=num

print(f'Even Numbers Sum {even_sum}')


print(f'Odd Numbers Sum {odd_sum}')

Output:

Even Numbers Sum 312


Odd Numbers Sum 325
Example:
# Write a program to display all the numbers which are divisible by
11 but not by 2 between
# 100 and 500

for num in range(100,501):


if num%11==0 and num%2!=0:
print(num)

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

while loop is executed until given condition is True.

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

What is difference between while and for loop?


while for
While loop repeat block of For loop repeat block of
statements until given condition statements number of times
Branching statements
Branching statements are used to control looping statements.
Python support the following branching statements
1. break
2. continue
3. return (functions)

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

num=int(input("Enter any number "))


c=0
for i in range(1,num+1):
print("Hello")
if num%i==0:
c=c+1
if c>2:
break

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

continue is a keyword or branching statement or passes control


statement.
Continue statement is included with in looping statements (for, while)
This statement continue the execution of while or for.
Example:
for num in range(1,11): # 1 2 3 4 5 6 7 8 9 10
if num%2==0:
continue
print(num)

Output:
1
3
5
7
9
Full Stack Python (Part-33)

while…else and for ..else

while and for loops are defined with else block.


Syntax of while..else Syntax of for..else

while <condition>: for variable in iterable:


statement-1 statement-1
statement-2 statement-2
else: else:
statement-3 statement-3

else block is executed after execution of while and for loop.


else block is not executed when for,while loop are terminated using
break statement.

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")

for num in range(1,6):


print(num)
break
else:
print("inside else block")

Output:
1
2
3
4
5
inside else block
1

Collections or data structures


Python data types are classified into two categories
1. Scalar data types
2. Collection types
Scalar data types are used to represent one value.
1. Int
2. Float
3. Complex
4. Bool
5. NoneType

Collection data types are used to represent more than value


1. Sequences
a. List
b. Tuple
c. Range
d. String
e. Bytes
f. Bytearray
2. Sets
a. Set
b. Frozenset
3. Mapping
a. Dictionary

Collection types are called containers.


Collection types allow to group individual objects and represent as
one object.
Collection types are called iterable.
Iterable objects implements iteration protocol.
Collections are used store more than one value or object.
Every collection uses a data structure for organizing data.

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

Python support the following sequence data types


1. List (Mutable)
2. Tuple (Immutable)
3. Range (Immutable)
4. String (Immutable)
5. Bytes (Immutable)
6. Bytesarray (mutable)

list datatype or collection


list is a mutable sequence data type.
Lists are mutable sequences, typically used to store collection of
homogeneous items.
List is a linear data structure, which is mutable and ordered
sequence of element/items.
Each value/object in list is called element or item.

In application development list is used to represent group of


individual objects where duplicates are allowed and reading/writing
is done sequential and random.

“list” is name of class or data type represents list object.

How to create list?


1. Using a pair of square brackets to denote the empty list: []
2. Using square brackets, separating items with
commas: [a], [a, b, c]
3. Using a list comprehension: [x for x in iterable]
4. Using the type constructor or function: list() or list(iterable)

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]

Creating list using list() function


It type is a type conversion function, which convert other iterables or
collections into list type.

1. list() 🡪 Create empty list


2. list(iterable) 🡪 Create list by using existing iterable or collection.

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]

Reading content of list/sequences

Python allows reading content of sequence in different ways


1. index
2. slicing
3. for loop
4. iterator
5. enumerate

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)

This index is used as a subscript to read value from list.

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)

len() : This function returns count elements or length of iterable

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

print(f'Even number count {ecount}')


print(f'Odd number count {ocount}')

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)

for i in range(a): # start=0,stop=6,step=1 --> 0 1 2 3 4 5


if i==0:
min_score=scores[i]
elif scores[i]<min_score:
min_score=scores[i]

print(scores)
print(f'Minimum Score {min_score}')

# Finding maximum score

for i in range(a): # start=0,stop=6,step=1 --> 0 1 2 3 4 5


if i==0:
max_score=scores[i]
elif scores[i]>max_score:
max_score=scores[i]

print(f'Maximum Score {max_score}')


print(f'Minimum Score {min(scores)}')
print(f'Maximum Score {max(scores)}')
print(f'Total Score {sum(scores)}')
Output:
[50, 30, 20, 10, 50, 60]
Minimum Score 10
Maximum Score 60
Minimum Score 10
Maximum Score 60
Total Score 220

max(iterable) Return maximum value of iterable


min(iterable) Return minimum value of iterable
sum(iterable) Add all the values of iterable and return
len(iterable) Return count of values or elements or items

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.

Slicing is done using two approaches


1. Using slice operator
2. Using slice object

What is difference between indexing and slicing?


Index Slicing
Index allows to read one value Slicing allows reading more than
one value by generating
multiple indices.

Slice operator
Syntax: sequence-name[start:stop:step]

Slice operator internally uses range for generating multiple indices.

Syntax1: sequence-name[::] or seqnece-name[:]


This syntax create copy of sequence by using default start,stop and
step.
Default start=0,stop=len(sequence),step=+1

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]

Syntax3: sequence-name[start::] or sequence-name[start:]


This syntax read values from left to right.
In this syntax default step value is +1
Default stop is till end of list.

>>> 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]

Using for loop


For loop is used to iterate or read values from any iterable.

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)

Reading data from list using for loop


list1=[10,20,30,40,50,60,70,80,90,100]

# Add all the values of list


s=0
for x in list1:
s=s+x

print(f'Sum of {list1} is {s}')

# Find maximum value of list


max_value=list1[0]
for x in list1:
if x>max_value:
max_value=x

print(f'Maximum value of {list1} is {max_value}')

# 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 length of list without using len function


list1=[1,2,3,4,5,6,7,8]
c=0
for x in list1:
c=c+1

print(f'Length of {list1} is {c}')

# 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']

Q: what is difference between iterator and iterable in python?


An Iterable is basically an object that any user can iterate over. An
Iterator is also an object that helps a user in iterating over another
object (that is iterable). We can generate an iterator when we pass
the object to the iter() method. We use the __next__() method for
iterating.

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')

Mutable Operations of list


List is a mutable collection/iterable. It means after creating list object
changes can be done.
Full Stack Python (Part-37)
Mutable Operations of list
List is a mutable collection/iterable. It means after creating list object
changes can be done.

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

list1=[] # empty list

for i in range(5): # start=0,stop=5,step=1 --> 0 1 2 3 4


value=int(input("Input integer value "))
list1.append(value)

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=[]

n=int(input("How many players?"))

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=[]

for value in num_list:


if value%2==0:
even_list.append(value)
else:
odd_list.append(value)

print(f'Number List {num_list}')


print(f'Even numbers List {even_list}')
print(f'Odd numbers 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)

append() method is used to add one object or value.


In order to append more than one value or object python uses
slicing operator.

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]

Replacing value/Updating value


Replacing values of list are done using,
1. index
2. slicing

using index one value is replaced


using slicing more than one value is replaced

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]

list1=[12, 35, 9, 56, 24]

# 1st approch
x=list1[0]
list1[0]=list1[-1]
list1[-1]=x

print(f'After Swaping {list1}')

# 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)

print(f'Before Swaping {list1}')


pos1=int(input("Enter Pos1 "))
pos2=int(input("Enter Pos2 "))
temp=list1[pos1-1]
list1[pos1-1]=list1[pos2-1]
list1[pos2-1]=temp

print(f'After Swaping {list1}')

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

n=int(input("Enter how many values ?"))


list1=[]
for i in range(n):
value=int(input("Enter value "))
list1.append(value)

print(f'before sorting values {list1}')

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

print(f'After sorting {list1}')

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.

1. Using del keyword


2. Using remove method
3. Using pop method
4. Using clear method

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)

print(f'Before deleting value {list1}')


value=int(input("Enter value to delete "))
if value in list1:
i=list1.index(value)
del list1[i]
print(f"{value} is deleted from list")
print(f'After deleting list is {list1}')
else:
print(f'{value} not exists within list')
Output:
Enter how many values?5
Enter value10
Enter value20
Enter value20
Enter value30
Enter value20
Before deleting value [10, 20, 20, 30, 20]
Enter value to delete 20
20 is deleted from list
After deleting list is [10, 20, 30, 20]

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)

print(f'Before deleting values {list1}')


value=int(input("Enter value to delete "))
found=False
while True:
if value in list1:
i=list1.index(value)
del list1[i]
found=True
else:
break

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]

Syntax-2: del list-name[start-index:stop-index:step]


This syntax is used to delete more than one value/element from list.
This syntax uses multiple indexes from list.

>>> 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]

s.remove(x) remove the first item from s where s[i] is equal to x

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]

Remove multiple elements from a list in Python

# Remove elements which even numbers

list1=[4,9,2,3,5,1,11,13,17,23,8,12,16,18,20,22]

print(f'Before Deleting values {list1}')


i=0
l=len(list1)
while i<l:
if list1[i]%2==0:
del list1[i]
l=l-1
continue
i=i+1

print(f'After Deleting values {list1}')

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]

Implementing Queue Data structure using list


Queue data structure follows FIFO (First In First Out), the element
added first is removed first. Queue allows two operations
1. Adding  append()
2. Removing  del
Example:
Q=[]
while True:
print("1. Adding")
print("2. Removing")
print("3. Display")
print("4. Exit")
opt=int(input("Enter your option "))
if opt==1:
value=int(input("Enter any value"))
Q.append(value)
print(f'{value} added inside Q')
elif opt==2:
if len(Q)==0:
print("Queue is empty")
else:
value=Q[0]
del Q[0]
print(f'{value} deleted from Queue')
elif opt==3:
print(f'{Q}')
elif opt==4:
break
else:
print("invalid option")

Output:
1. Adding
2. Removing
3. Display
4. Exit
Enter your option 1
Enter any value10
10 added inside Q

s.extend(t) or s += extends s with the contents of t (for the most


t part the same as s[len(s):len(s)] = t)

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']

inserts x into s at the index given by i (same


s.insert(i, x)
as s[i:i] = [x])

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

Example of inserting more than one value

>>> 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]

s.reverse() reverses the items of s in place

>>> 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]

Creating copy of the collection or list or iterable

Creating copy is done using different methods


1. Shallow Copy
2. Deep Copy
Shallow Copy
creates a shallow copy of s (same
s.copy()
as s[:])
Shallow copy is called reference copy. In shallow copy a new list
created by copying address/references of objects found in original
list.
Example:
>>> list1=[[10,20],30]
>>> list2=list1.copy()
>>> print(list1)
[[10, 20], 30]
>>> print(list2)
[[10, 20], 30]
>>> list1[0].append(40)
>>> print(list1)
[[10, 20, 40], 30]
>>> print(list2)
[[10, 20, 40], 30]
list2[0][0]=99
>>> print(list2)
[[99, 20, 40], 30]
>>> print(list1)
[[99, 20, 40], 30]
>>> list1[1]=88
>>> print(list1)
[[99, 20, 40], 88]
>>> print(list2)
[[99, 20, 40], 30]

copy module

copy module provides a function to perform deep copy.

copy.deepcopy(iterable)

This function returns copy of iterable.


copy is a default module which comes with python software.
>>> list1=[[10,20],30]
>>> print(list1)
[[10, 20], 30]
>>> import copy
>>> list2=copy.deepcopy(list1)
>>> print(list2)
[[10, 20], 30]
>>> list1[0].append(90)
>>> print(list1)
[[10, 20, 90], 30]
>>> print(list2)
[[10, 20], 30]
>>> list2[0][0]=99
>>> print(list2)
[[99, 20], 30]
>>> print(list1)
[[10, 20, 90], 30]
Full Stack Python (Part-40)

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])

for i in range(3): # start=0,stop=3,step=1 --> 0 1 2


for j in range(3): # start=0,stop=3,step=1 --> 0 1 2
print(list1[i][j],end=' ')
print()

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=[]

print("Enter elements of 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)

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=[]

print("Enter Elements of matrix1")


for i in range(2):
row=[]
for j in range(2):
value=int(input("Enter Value "))
row.append(value)
matrix1.append(row)

print("Enter Elements of matrix2")


for i in range(2):
row=[]
for j in range(2):
value=int(input("Enter Value "))
row.append(value)
matrix2.append(row)

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

Comprehensions in Python provide us with a short and concise way


to construct new sequences (such as lists, sets, dictionaries, etc.)
using previously defined sequences. Python supports the following 4
types of 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

Syntax1: [expression/value for variable in iterable]


Syntax2: [expression/value for variable in iterable if test]

Example:
# Create List with 0 filled 100 values

list1=[0 for i in range(100)]


print(list1)

# Create List with Alphabets from A-Z

list2=[chr(value) for value in range(65,91)]


print(list2)

# Create List with Alphabets from a-z


list3=[chr(value) for value in range(97,123)]
print(list3)

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

n=int(input("Enter the value of n"))

#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]]

Syntax-2: [expression/value for variable in iterable if test/condition]


This syntax evaluate expression if test is True

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)

gradeA=[stud for stud in gradeList if stud[1]=='A']


gradeB=[stud for stud in gradeList if stud[1]=='B']
gradeC=[stud for stud in gradeList if stud[1]=='C']
print(gradeA)
print(gradeB)
print(gradeC)

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]

Operators used with list


1. + operator is used for concatenation of list

>>> 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]

2. * Operator is used to repeat list n times

>>> 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]

3. == operator is used to compare elements of list

>>> 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. …

Where tuple is used in application development?


1. To represent immutable list
2. Tuple is used to represent data in other collections like set and
dictionary
3. It is used by enumerate to generate two values tuple.

Tuples are immutable sequences, typically used to store collections


of heterogeneous data (such as the 2-tuples produced by
the enumerate() built-in). Tuples are also used for cases where an
immutable sequence of homogeneous data is needed.

How to create tuple?

Tuples may be constructed in a number of ways:


1. Using a pair of parentheses to denote the empty tuple: ()
2. Using a trailing comma for a singleton tuple: a, or (a,)
3. Separating items with commas: a, b, c or (a, b, c)
4. Using the tuple() built-in: tuple() or tuple(iterable)

Using a pair of parentheses to denote the empty tuple: ()

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]

Using a trailing comma for a singleton tuple: a, or (a,)

>>> 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,)

Separating items with commas: a, b, c or (a, b, c)

>>> 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'>

Find the size of a Tuple in Python


The size of a Tuple means the amount of memory (in bytes) taken by
a Tuple object.

>>> import sys


>>> t1=(10,20)
>>> sys.getsizeof(t1)
56
>>> t2=(10,20,30,40,50)
>>> sys.getsizeof(t2)
80
Packing and Unpacking in Python

Python has a cool feature that permits us to pack and unpack


values from iterables in a single assignment.

Unpacking arguments in Python refers to the process of taking a


packed tuple or dictionary and “unpacking” its elements into
separate variables.

Packing is a process of grouping individual objects into one object


(iterable/collection).

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]

Initially this packing and unpacking is implemented on tuples, later it


is used with other collection types (list, dictionary,…)

>>> 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)

How to read multiple values in single line?

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

Input : test_tup = (3, 7, 1, 18, 9), k = 2


Output : (3, 1, 9, 18)
Input : test_tup = (3, 7, 1), k=1
Output : (1, 7)

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)

Python program to create a list of tuples from given list having


number and its cube in each tuple

Input: list = [1, 2, 3]


Output: [(1, 1), (2, 8), (3, 27)]

Input: list = [9, 5, 6]


Output: [(9, 729), (5, 125), (6, 216)]

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”

A string can be created in different ways


1. Within single quotes
2. Within double quotes
3. Within triple single quotes or double quotes
4. String is created using str() (OR) str(object)
Within single quotes we can represent single line string. Within single
quotes we cannot embedded single quotes, we can embed only
double quotes.

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

within double quotes we can represent single line string. Within


double we can insert/embed single quotes.

>>> 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)

triple single quotes or double quotes are used to represent multiline


string.

>>> 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

type casting or type conversion using str() function


this function is used to convert other objects into string type.

1. str()  Create empty string


2. str(object)  convert any type of object into string type

>>> 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)

Example of reading using index and slicing:


str1="PROGRAMMING"
str2=str1[0]
str3=str1[-1]
str4=str1[4]
print(str1,str2,str3,str4,sep="\n")
str5=str1[:5]
print(str5)
str6=str1[5:]
print(str6)
str7=str1[::-1]
print(str7)
str8=str1[3:-3]
print(str8)
str9=str1[::2]
print(str9)
str10=str1[::-2]
print(str10)

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)

str1=input("Enter any string ")


c=0
for ch in str1:
c=c+1

print(f'Length of string is {c}')


print(f'Length of string is {len(str1)}')
Output:
Enter any string abc
Length of string is 3
Length of string is 3

Example:
# Write a program to count alphabets,digits and special characters
exists within string

str1=input("Enter any string ")


ac,dc,sc=0,0,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

print(f'Alphabet count {ac}')


print(f'Digit count {dc}')
print(f'Special Character count {sc}')

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

str1=input("Enter any string ")


str2=str1[::-1]
if str1==str2:
print(f'{str1} is pal')
else:
print(f'{str1} is not pal')

Output:
Enter any string ama
ama is pal

Enter any string java


java is not pal

Python program to check whether the string is Symmetrical or


Palindrome
Given a string. the task is to check if the string is symmetrical and
palindrome or not. A string is said to be symmetrical if both the
halves of the string are the same and a string is said to be a
palindrome string if one half of the string is the reverse of the other
half or if a string appears same when read forward or backward.
Example:
Input: khokho
Output:
The entered string is symmetrical
The entered string is not palindrome

Input:amaama
Output:
The entered string is symmetrical
The entered string is palindrome

str1=input("enter any string ")


l=len(str1)
m=l//2
s1=str1[:m]
s2=str1[m:]
if s1==s2:
print("The entered string is symmetrical")
else:
print("The entered string is not symmetrical")

if str1==str1[::-1]:
print("The entered string is palindrome")
else:
print("The entered string is not palindrome")

Reverse Words in a Given String in Python


Input : str =" geeks quiz practice code"
Output : str = code practice quiz geeks
Input : str = "my name is laxmi"
output : str= laxmi is name my

str1="geeks quiz practice code"


list1=str1.split()
list1=list1[::-1]
str2=' '.join(list1)
print(str1)
print(str2)
Full Stack Python (Part-44)
Methods or functions of string

Case conversion methods

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

str1=input("Enter any string ") # java --> 4


str2=""
for i in range(len(str1)): # range(4) --> start=0,stop=4,step=1 --> 0 1 2 3
if i==0:
if str1[i]>='a' and str1[i]<='z':
str2=str2+chr(ord(str1[i])-32)
else:
str2=str2+str1[i]
elif str1[i]>='A' and str1[i]<='Z':
str2=str2+chr(ord(str1[i])+32)
else:
str2=str2+str1[i]

print(str1)
print(str2)

Output:
Enter any string python
python
Python

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

str1=input("Enter any string ") # AbC


str2=""

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

str1=input("Enter any String ")


str2=""
for ch in str1:
if ch>='a' and ch<='z':
str2=str2+chr(ord(ch)-32)
elif ch>='A' and ch<='Z':
str2=str2+chr(ord(ch)+32)
else:
str2=str2+ch

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:

>>> s1="python programming language"


>>> s2=s1.title()
>>> print(s1)
python programming language
>>> print(s2)
Python Programming Language

Example:
# write a program for title case

str1="python programming language"


list1=str1.split() # --> ["python","programming","language"]
list1=[s.capitalize() for s in list1]
print(list1)
str2=' '.join(list1)
print(str1)
print(str2)
Output:
['Python', 'Programming', 'Language']
python programming language
Python Programming Language

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

Case conversion methods


1. capitalize()
2. lower()
3. swapcase()
4. title()
5. upper()

String examines methods or string validation methods

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

str1=input("Enter any string ")


ans=True
for ch in str1:
if ch>='a' and ch<='z' or ch>='A' and ch<='Z':
pass
else:
ans=False
break

print(ans)

Output:
Enter any string python
True

Enter any string py13


False

Enter any string py$


False

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

str1=input("Enter any string ")


ans=True
for ch in str1:
if ch>='a' and ch<='z' or ch>='A' and ch<='Z' or ch>='0' and ch<='9':
pass
else:
ans=False
break

print(ans)

Output:
Enter any string 123
True

Enter any string abc


True

Enter any string abc123


True

Enter any string abc123$


False

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.

>>> s1=" "


>>> s1.isspace()
True
>>> s2="abc"
>>> s2.isspace()
False
>>> s3="a b c d"
>>> s3.isspace()
False

str.istitle()
Return True if the string is a titlecased string and there is at least one
character return False.

>>> s1="Python Programming"


>>> s1.istitle()
True
>>> s2="Python programming"
>>> s2.istitle()
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

String alignment methods


String alignment methods are used for formatting output.

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)

String alignment methods


String alignment methods are used for formatting output.

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))

for name in names_list:


print(name.ljust(20,"*"),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))

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

def mutate_string(string, position, character):


list1=list(string)
list1[position]=character
s="".join(list1)
return s

if __name__ == '__main__':
s = input()
i, c = input().split()
s_new = mutate_string(s, int(i), c)

Searching methods

str.startswith(prefix[, start[, end]])


Return True if string starts with the prefix, otherwise
return False. prefix can also be a tuple of prefixes to look for. With
optional start, test string beginning at that position. With
optional end, stop comparing string at that position.

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

str.endswith(suffix[, start[, end]])


Return True if the string ends with the specified suffix, otherwise
return False. suffix can also be a tuple of suffixes to look for. With
optional start, test beginning at that position. With optional end, stop
comparing at that position.

Example:
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

str.find(sub[, start[, end]])


Return the lowest index in the string where substring sub is found
within the slice s[start:end]. Optional arguments start and end are
interpreted as in slice notation. Return -1 if sub is not found.

str.rfind(sub[, start[, end]])


Return the highest index in the string where substring sub is found,
such that sub is contained within s[start:end]. Optional
arguments start and end are interpreted as in slice notation. Return -
1 on failure.

>>> str1="python java python java oracle java"


>>> str1.find("java")
7
>>> str1.find("java",10)
19
>>> str1.find("sql")
-1
>>> str1.rfind("java")
31
>>> str1.rfind("java",10,25)
19
Full Stack Python (Part-46)

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'

>>> 'Arthur: three!'.removeprefix('Arthur: ')


'three!
>>> name="Mr.Mohan"
>>> name1=name.removeprefix("Mr.")
>>> print(name)
Mr.Mohan
>>> print(name1)
Mohan
>>> name2=name.lstrip("Mr.")
>>> print(name2)
ohan

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:

>>> s1="nit "


>>> len(s1)
13
>>> s2=s1.rstrip()
>>> len(s2)
3
>>> s1==s2
False
>>> s1.rstrip()==s2
True
>>> s3="nit****"
>>> s4=s3.rstrip("*")
>>> print(s3)
nit****
>>> print(s4)
nit
>>> s5="nit**$$%%@@@%%"
>>> s6=s5.rstrip("%$@*")
>>> print(s5)
nit**$$%%@@@%%
>>> print(s6)
Nit

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:

>>> str1=" nit "


>>> len(str1)
23
>>> str2=str1.strip()
>>> len(str2)
3
>>> str1==str2
False
>>> str1.strip()==str2
True
>>> str3="***$$$nit***###"
>>> str4=str3.strip("*$#")
>>> print(str3)
***$$$nit***###
>>> print(str4)
nit
>>> website="www.helloworld.com"
>>> website1=website.strip("w.com")
>>> print(website)
www.helloworld.com
>>> print(website1)
helloorld

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.maketrans(x[, y[, z]])


Returns a translation table usable for str.translate().

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

str.replace(old, new[, count])


Return a copy of the string with all occurrences of
substring old replaced by new. If the optional argument count is
given, only the first count occurrences are replaced.

>>> str1="python java python java java oracle java mysql"


>>> str2=str1.replace("java","jython")
>>> print(str1)
python java python java java oracle java mysql
>>> print(str2)
python jython python jython jython oracle jython mysql
>>> str3=str1.replace("java","jython",1)
>>> print(str3)
python jython python java java oracle java mysql
>>> str4=str1.replace("p","P")
>>> print(str4)
Python java Python java java oracle java mysql
bytes

Bytes objects are immutable sequences of single bytes. Since many


major binary protocols are based on the ASCII text encoding, bytes
objects offer several methods that are only valid when working with
ASCII compatible data and are closely related to string objects in a
variety of other ways.

bytes class or data type represents bytes object.

How to create bytes object?

 Single quotes: b'still allows embedded "double" quotes'


 Double quotes: b"still allows embedded 'single' quotes"
 Triple quoted: b'''3 single quotes''', b"""3 double quotes"""

>>> 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'

Only ASCII characters are permitted in bytes literals (regardless of the


declared source code encoding). Any binary values over 127 must
be entered into bytes literals using the appropriate escape
sequence.

Applications of bytes object


1. Binary files
a. Images
b. Audio
c. Video
2. Networking applications
3. Persisting objects/Saving objects into binary file

In addition to the literal forms, bytes objects can be created in a


number of other ways:

 A zero-filled bytes object of a specified length: bytes(10)


 From an iterable of integers: bytes(range(20))
 Copying existing binary data via the buffer protocol: bytes(obj)

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

bytes object is immutable sequence, after creating bytes object


changes cannot be done.

>>> 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

bytearray objects are a mutable counterpart to bytes objects.


It support all mutable methods,
1. append()
2. insert()
3. remove()
4. pop()
5. sort()
6. extends()
7. ….

“bytearray” class or data type represents bytearray object.

bytearay object is created in different ways.

1. Creating an empty instance: bytearray()


2. Creating a zero-filled instance with a given
length: bytearray(10)
3. From an iterable of integers: bytearray(range(20))
4. Copying existing binary data via the buffer
protocol: bytearray(b'Hi!')

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')

Characteristics of sequence data types


1. Ordered collection where insertion order preserved
2. Index based collection
3. Allows duplicates
4. Sequences can be homogeneous or heterogeneous data

In application development sequences are used to represent group


of individual objects where reading and writing is done sequentially
and random.
Sets

Sets are unordered collection, where insertion order is not preserved.


Sets are non index based collections. It does not support indexing
and slicing.
Sets does not allows duplicate values.

Python support two set types

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

A set object is an unordered collection of distinct hashable objects.


Common uses include membership testing, removing duplicates
from a sequence, and computing mathematical operations such as
intersection, union, difference, and symmetric difference.

set data type class

set is a mutable data type or object.


After creating set changes can be done.
The set type is mutable — the contents can be changed using
methods like add() and remove().

Sets can be created by several means:


 Use a comma-separated list of elements within
braces: {'jack', 'sjoerd'}
 Use
a set comprehension: {c for c in 'abracadabra' if c not in 'abc'}
 Use the type constructor: set(), set('foobar'), set(['a', 'b', 'foo'])

In set data is organized using hashing data structure.

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.

Syntax-1: set()  Empty set


Syntax-2: set(iterable)  Creating set using existing iterables or
collections.

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

Set uses hashing data structure for organizing data.


According hashing data structure there is a hash table, in which
each location is identified with key.

What is hashable object?


An object which generates hash value is called hashable object. This
hash value is used in hash based data structures for finding key.

Object Law
If two objects are equal according == operator, it should generate
same hash value.

Hash value is an integer value. All immutable objects are hashable


objects.

How to find hash value of object?


hash() function returns hash value of object.

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

How to read content of set?


The content of set can be read in different ways
1. for loop
2. iterator
3. enumerate

Example:
A={10,20,30,40,50}

# Using for loop


for value in A:
print(value)
print("***************************")
# Using iterator
x=iter(A)
value1=next(x)
print(value1)
value2=next(x)
print(value2)

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))

Removing element from set


remove(elem)
Remove element elem from the set. Raises KeyError if elem is not
contained in the set.

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}

Set examine methods

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 = {}

for rno in rooms:


if rno in room_count:
room_count[rno] += 1
else:
room_count[rno] = 1

for rno, count in room_count.items():


if count == 1:
print(rno)
https://www.hackerrank.com/challenges/py-check-subset/
problem?isFullScreen=true

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))

What is difference between list and set?


List Set
List is ordered collection Set is unordered collection
List insertion order is preserved. Set insertion order is not
preserved.
List is sequence Set is non sequence
List allows duplicates Set does not allows duplicates
List support indexing and slicing Set does not support indexing
and slicing
List organize data in sequential Set data is organized using
order hashing data structure
List allows any type of object Set allows only hashable object
(immutable object)
List is created using [] Set is created using {}
“list” class or data type represents “set” class or data type
list object represents set object.
In application development list is In application development set is
used to represent group of used to represent group of
individual objects where individual objects where
duplicates are allowed and duplicates are not allowed and
reading and writing is done perform mathematical set
sequential and randomly. operations.
frozenset

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. ….

What is use of frozenset?


1. To represent immutable set
2. To present nested set.

How to create frozenset?


Syntax1: frozenset() : Creating empty frozenset
Syntax2: frozenset(iterable) : Creating frozenset using existing iterable

>>> 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

Everyone please practice MCQs from here…


https://www.sanfoundry.com/python-questions-answers-sets-1/

<< All the best in Python Full Stack Journey >>


Full Stack Python (Part-51)
dictionary (Mapping)

dictionary is a collection type.


dictionary is mapping collection type.
A dictionary is a kind of data structure that stores items in key-value
pairs. A key is a unique identifier for an item, and a value is the data
associated with that key.
A Python dictionary is a collection of key:value pairs.
In dictionary each key is mapped with one or more than one value.
Dictionary keys must be hashables and values can be any type.
Dictionary is mutable collection or object, after creating dictionary
changes can be done.
Dictionary keys must be unique (duplicate keys are not allowed).
Dictionary values can be anything.
Dictionary is key based collection, where reading and writing is done
using key.
In application development dictionary is used to represent group of
individual objects where each object is bind with key.

Example: Contacts, AddressBook, Shoping Cart, Cookies, request,


repose
How to create dictionary?

“dict” class or data type which represents dictionary object.


Dictionary is created in different ways.

1. Empty dictionary is created using {}


2. Dictionary is created with items, where key and value are
separated with :
{key:value,key:value,key:value,key:value,…}
3. Using dictionary comprehension
4. Using dict() function
a. dict() : This create empty dictionary
b. dict(iterable): This create dictionary by converting existing
iterable/collection.

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}

Example of creating dictionary using dictionary function

>>> 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'}
>>>

Reading content of dictionary


The content of dictionary can be read in different ways.
1. Using key
2. Using for loop
3. Using iterator
4. Using dictionary methods
a. Keys()
b. Values()
c. Items()
5. Getter methods of dictionary

Using key
Dictionary is key based collection, to read value from dictionary we
can use key.

Syntax: dictionary-name[key]

If key exists, it return value


It key not exists, it generate KeyError

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

Using for loop


For loop iterate/read key from dictionary.

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

Iterator object is created using iter() function. This objet is used to


read keys from dictionary.

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

Using dictionary methods

Dictionary view objects


The objects returned
by dict.keys(), dict.values() and dict.items() are view objects. They
provide a dynamic view on the dictionary’s entries, which means
that when the dictionary changes, the view reflects these changes.
Example:
>>>
stud_dict={'naresh':'python','suresh':'java','ramesh':'python','kishore':'c
++'}
>>> print(stud_dict)
{'naresh': 'python', 'suresh': 'java', 'ramesh': 'python', 'kishore': 'c++'}
names=stud_dict.keys()
>>> print(names)
dict_keys(['naresh', 'suresh', 'ramesh', 'kishore'])
>>> stud_dict['rajesh']='oracle'
>>> print(names)
dict_keys(['naresh', 'suresh', 'ramesh', 'kishore', 'rajesh'])
>>> del names[0]
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
del names[0]
TypeError: 'dict_keys' object doesn't support item deletion
>>> courses=stud_dict.values()
>>> print(courses)
dict_values(['python', 'java', 'python', 'c++', 'oracle'])
>>> students=stud_dict.items()
print(student)
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
print(student)
NameError: name 'student' is not defined. Did you mean: 'students'?
>>> print(students)
dict_items([('naresh', 'python'), ('suresh', 'java'), ('ramesh', 'python'),
('kishore', 'c++'), ('rajesh', 'oracle')])
>>> students[0]
Traceback (most recent call last):
File "<pyshell#14>", line 1, in <module>
students[0]
TypeError: 'dict_items' object is not subscriptable

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}

Mutable Operation of dictionary


Dictionary is a mutable collection, after creating dictionary changes
can be done.
Adding item inside dictionary

Syntax: dictionary-name[key]=value

If key not exists, PVM add key with value


If key exists, PVM modify/update value of given key
>>> student={101:'naresh'}
>>> print(student)
{101: 'naresh'}
>>> student[102]="suresh"
>>> print(student)
{101: 'naresh', 102: 'suresh'}
>>> student[103]="kishore"
>>> print(student)
{101: 'naresh', 102: 'suresh', 103: 'kishore'}
>>> student[101]="ramesh"
>>> print(student)
{101: 'ramesh', 102: 'suresh', 103: 'kishore'}

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("Before updating ")


print(email_dict)
name=input("Enter name of person to update email-id")
if name in email_dict:
new_emailid=input("Enter New Email-id ")
email_dict[name]=new_emailid
print("After updating ")
print(email_dict)
else:
print(f'{name} not found')
prod={}
n=int(input("enter how many products ?"))
for i in range(n):
pid=int(input("Enter ProductId "))
pinfo=[input("Enter ProductName"),float(input("Enter Price "))]
prod[pid]=pinfo

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)

str1=input("enter any string ")


list1=str1.split()
d1={}
for value in set(list1):
c=list1.count(value)
d1[value]=c

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:]))

How to remove data/items from dictionary?


Removing items from dictionary is done in different ways
1. Using del keyword
2. Using remove method
3. Using pop method
4. Using popitem method
5. Using clear method

Using del keyword


This keyword required key for deleting item from dictionary
If key exists it delete item
If key not exists it raises KeyError

Syntax: del dictionary-name[key]


Example:
>>> d1={1:10,2:20,3:30,4:40,5:50}
>>> print(d1)
{1: 10, 2: 20, 3: 30, 4: 40, 5: 50}
>>> del d1[1]
>>> print(d1)
{2: 20, 3: 30, 4: 40, 5: 50}
>>> del d1[4]
>>> print(d1)
{2: 20, 3: 30, 5: 50}
>>> del d1[1]
Traceback (most recent call last):
File "<pyshell#25>", line 1, in <module>
del d1[1]
KeyError: 1
pop(key[, default])
If key is in the dictionary, remove it and return its value, else
return default. If default is not given and key is not in the dictionary,
a KeyError is raised.

>>> 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)

Ways to sort list of dictionaries by values in Python – Using itemgetter

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'}]

from operator import itemgetter


list1=[{"name": "Nandini", "age": 20},
{"name": "Manjeet", "age": 20},
{"name": "Nikhil", "age": 19}]

print(list1)

list2=sorted(list1,key=itemgetter("age"))
print(list2)
list3=sorted(list1,key=itemgetter("name","age"))
print(list3)

Python – Convert key-values list to flat dictionary


Sometimes, while working with Python dictionaries, we can have a
problem in which we need to flatten dictionary of key-value pair
pairing the equal index elements together. This can have utilities in
web development and Data Science domain.

Input:
The original dictionary is : {‘name’: [‘Jan’, ‘Feb’, ‘March’], ‘month’:
[1, 2, 3]}

Output:
Flattened dictionary : {1: ‘Jan’, 2: ‘Feb’, 3: ‘March’}

dict1={'name': ['Jan', 'Feb', 'March'], 'month': [1, 2, 3]}


dict2=dict(zip(dict1['month'],dict1['name']))
print(dict1)
print(dict2)
Example:
# Creating contacts application

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.

Syntax1: {key:value for variable in iterable}


Syntax2: {key:value for variable in iterable if test}

Example:
# Creating dictionary using dictionary comprehension

ascii_dict1={n:chr(n) for n in range(65,91)}


print(ascii_dict1)
print(ascii_dict1[65])
ascii_dict2={n:chr(n) for n in range(97,123)}
print(ascii_dict2)
table_dict={n:[n*i for i in range(1,11)] for n in range(1,6)}
print(table_dict)

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.

Syntax1: {key:value for variable in iterable}


Syntax2: {key:value for variable in iterable if test}

Example:
# Creating dictionary using dictionary comprehension

ascii_dict1={n:chr(n) for n in range(65,91)}


print(ascii_dict1)
print(ascii_dict1[65])
ascii_dict2={n:chr(n) for n in range(97,123)}
print(ascii_dict2)
table_dict={n:[n*i for i in range(1,11)] for n in range(1,6)}
print(table_dict)

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

n=int(input("Enter how many players ?"))


players={input("Enter Name "):int(input("Score ")) for i in range(n)}
for name,score in players.items():
print(f'{name}--->{score}')

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?

List Set Dictionary


List is a ordered Set is unordered Dictionary is
collection collection mapping collection
List contains only Set contains only Dictionary contains
values values key and value(item)
List allows duplicate Set does not allows Dictionary allows
values duplicate values duplication values
not allows duplicate
keys
Reading and Writing It is non-index based Reading and Writing
is done using index collection is done using key.
In application In application In application
development to development to development to
group individual group individual group individual
objects where objects where object where each
duplicates are duplicates are not object is identified
allowed and reading allowed and to with key.
and writing is done perform
sequential and mathematical set
random. operations.
List is create using [] Set is created using Dictionary is created
{value,} using {key:value,…}
“list” class or data “set” class or data “dict” class
type represents list type represents set represents dictionary
object object object.
Functions

Python is a multi paradigm programming language, programming


paradigm define set of rules and regulations for writing programs or
organizing instructions.

1. POP (Procedural Oriented Programming)


2. MOP (Modular Oriented Programming)
3. OOP (Object Oriented Programming)

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.

Functions are two types


1. Predefined functions
2. User defined functions

The existing functions or functions provided by python are called


predefined functions. These predefined functions are also called
library functions.
Example: print(),min(),max(),input(),len(),….

Application specific functions are called user defined functions (OR)


the functions build by programmer are called user defined functions.
Example: withdraw(), deposit(), checkBal(), printMiniStatement(),..

Syntax of writing function


Function is defined using “def” keyword.

def <function-name>([parameters]):
‘’’doc string’’’
statement-1
statement-2

In python functions are objects.

A function can be defined with parameters (input).


A function can be defined without parameters (without input)
Parameters receive values at the time invoking or calling function.
Full Stack Python (Part-56)
Syntax of writing function
Function is defined using “def” keyword.

def <function-name>([parameters]):
‘’’doc string’’’
statement-1
statement-2

In python functions are objects.

A function can be defined with parameters (input).


A function can be defined without parameters (without input)
Parameters receive values at the time invoking or calling function.

By defining function, it is not executed.

Function is having two parts


1. Function definition
2. Function invocation or calling or executing

Example:
print("Welcome")
def sayHello():
print("Hello, This is my first function")

sayHello() # executing function/calling function/executable statement


print("Hello")
a=100
b=200
c=a+b
print(c)
Output:
Welcome
Hello, This is my first function
Hello
300

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

If function does not required any input to perform operations, it is


defined 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

The memory for local variables is allocated, when function is called


and de-allocation is done after execution of function.

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.

Syntax: global <variable-list>

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,…)

x=100 # Global Variable


def fun1():
x=200 # Local Variable
y=300 # Local Variable
print(x)
print(y)
a=globals()
print(a['x'])
a['x']=900

fun1()
print(x)
Output:
200
300
100
900
Full Stack Python (Part-57)

Local variable Global Variables


A variable created inside A variable created outside
function is called local variable function is called global variable
The scope of this variable within The scope this variable within
function. function and outside the
function.

Function with parameters

Parameters are local variables, which receive values at the time of


calling function or invoking function.
A function required input to perform operation, that function is
defined with parameters.

A function defined with 4 types of parameters/arguments

1. Required positional arguments


2. Default arguments/Operational arguments
3. Variable length arguments
4. Keyword arguments

Required Positional arguments or parameters


Function with required positional arguments required values at the
time of invoking function or calling function.

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

Function with type hint


In Python, type hinting is an optional yet useful feature to make your
code easier to read, reason about, and debug. With type hints, you
let other developers know the expected data types for variables,
function arguments, and return values
Type hints are introduced python 3.5 version.

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

Example of sending values with argument name:


def fun1(a,b,c,d):
print(a,b,c,d)

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.

Syntax: return [<value>/<object>]

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

number=int(input("Enter any number "))


result=factorial(number)
print(f'factorial of {number} is {result}')

Output:
Enter any number 4
factorial of 4 is 24

# Write a function to convert string to uppercase


def upper(s:str)->str:
us=''
for ch in s:
if ch>='a' and ch<='z':
us=us+chr(ord(ch)-32)
else:
us=us+ch
return us

str1=input("Enter any string ")


str2=upper(str1)
print(str1)
print(str2)

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

Default parameters or arguments (OR) optional arguments

Default parameters are given values at the time of defining function.


If values are not given at the time invoking function, PVM assign
default values.

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

Default parameters are given values at the time of defining function.


If values are not given at the time invoking function, PVM assign
default values.

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]

Python does not support pass by value, it support only pass


reference. Whenever function is called by sending object, PVM does
not send object, it send reference (address)
Example:
def fun1(a):
a[0]=99
a.append(100)

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

When function is defined with required and default parameters, first


parameter must be required and followed by default.

Function with variable length arguments or parameters

Function with variable length argument receives 0 or more values.


Variable length argument is prefix with *
Variable length argument is of type tuple.
If function required more than one value to perform operation, it is
defined with variable length argument/parameter.

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)

Keyword arguments or parameters


If function defined with keyword arguments, it receives key and
value. Keyword argument variable length argument because it
receives any number of key and values.

Keyword argument is prefix with **


Keyword argument is of type dictionary.

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}

A function is defined with one keyword argument.

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

When to write a function with keyword arguments?


1. A function required to receive key and value
2. A function required to manipulate data of dictionary

Example:
def add(*varg,**kwargs):
s=0
for value in varg:
s=s+value

for value in kwargs.values():


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

A function defined inside function is called nested function.

What is use of nested functions?


1. Dividing functionality of a function into number of sub functions
2. We can develop special functions
a. Decorator
b. Closures
3. Data hiding
Nested Function

A function defined inside function is called nested function.

What is use of nested functions?


1. Dividing functionality of a function into number of sub functions
2. We can develop special functions
a. Decorator
b. Closures
3. Data hiding

Syntax:
def <outer-function-name>([parameters]):
statements
def <inner-function>/<nested function>([parameters]):
statements

Inner function is used within outer function but cannot access


outside outer function.

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.

Inner function can access local variables of outer function directly


but cannot update or modify values directly.

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

without nonlocal keyword, inner function can access local variables


of outer function but cannot modify or update.

In order to modify or update nonlocal variable or enclosed block


variable we have to use “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.

x=100 # Global variable


def fun1():
y=200 # Local variable of fun1
def fun2():
z=300 # Local variable of fun2
print(z)
print(y)
print(x)
print(__name__)
fun2()

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

n1=int(input("Enter First Number "))


n2=int(input("Enter Second Number "))
o=input("Enter Operator ")
n3=calculator(n1,n2,o)
print(f'Result is {n3}')

Output:
Enter First Number 5
Enter Second Number 2
Enter Operator -
Result is 3

Decorator function

By definition, a decorator is a function that takes another function


and extends the behavior of the latter function without explicitly
modifying it.

In Python, a decorator is a design pattern that allows you to modify


the functionality of a function by wrapping it in another function.

A decorator is a design pattern in Python that allows a user to add


new functionality to an existing object without modifying its structure.

You'll use a decorator when you need to change the behavior of a


function without modifying the function itself.

Decorators in Python are functions that takes another function as an


argument and extends its behavior without explicitly modifying it.

Decorators are used to transform one function to another function.

Decorator function receives input as function and modifies or


extends the function by writing another function and return modified
function.

Working with decorators required two steps


1. Developing decorator
2. Applying decorator

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

a=int(input("enter first number "))


b=int(input("enter second number "))
c=div(a,b)
print(f'{a}/{b}={c:.2f}')

Output:
enter first number 6
enter second number 0
6/0=0.00

Chaining Decorators in Python

Multiple decorators can be chained in Python.


To chain decorators in Python, we can apply multiple decorators to
a single function by placing them one after the other, with the most
inner decorator being applied first.

Chaining decorators means applying more than


one decorator inside a function.
Syntax:

@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

A Closure in Python is a function object that remembers values in


enclosing scopes even if they are not present in memory.

Python closure is a nested function that allows us to access variables


of the outer function even after the outer function is closed .

ADVANTAGE: Closures can avoid use of global variables and


provides some form of data hiding.

Closure in Python can be defined when a nested function


references a value in its enclosing scope. Closures provide some
form of data hiding

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

Generator is a special function which returns generator iterator


object.
In Python, a generator is a function that returns an iterator that
produces a sequence of values when iterated over.
Generators are useful when we want to produce a large sequence
of values, but we don't want to store all of them in memory at once.

A Python generator function allows you to declare a function that


behaves like an iterator, providing a faster and easier way to create
iterators. They can be used on an abstract container of data to turn
it into an iterable object like lists, dictionaries and strings.

A function which contain “yield” keyword is called generator


function. A generator function returns value using “yield” keyword.
Yield keyword after returning value, it pause execution of function.

What is difference between return and yield?


Generator

Generator is a special function which returns generator iterator


object.
In Python, a generator is a function that returns an iterator that
produces a sequence of values when iterated over.
Generators are useful when we want to produce a large sequence
of values, but we don't want to store all of them in memory at once.

A Python generator function allows you to declare a function that


behaves like an iterator, providing a faster and easier way to create
iterators. They can be used on an abstract container of data to turn
it into an iterable object like lists, dictionaries and strings.

A function which contain “yield” keyword is called generator


function. A generator function returns value using “yield” keyword.
Yield keyword after returning value, it pause execution of function.

What is difference between return and yield?


return yield
A normal function returns value Generator function returns value
using return keyword using yield keyword
return keyword terminates Yield keyword after returning
execution of function after value it pause execution of
returning value function.

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 )

b=fun1() #Creating Generator iterator object


list1=list(b)
print(list1)

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()

b=reviter(list1) # iterator object


for y in b:
print(y,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

a=primeGenerator(5,20) # Creating primeGenerator iterator object


value1=next(a)
print(value1)
value2=next(a)
print(value2)
for value in a:
print(value,end=' ')

Output:
5
7
11 13 17 19

Python Generator Expression

In Python, generator expression is another way of writing the


generator function. It uses the Python list comprehension technique
but instead of storing the elements in a list in memory, it creates
generator objects.

Generator Expression Syntax

The generator expression in Python has the following Syntax:

(expression for item in iterable)

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

Lambda functions are anonymous functions.


A function which does not have any name is called anonymous
function.
Lambda functions are used with higher order functions. A function
which receives input as another function is called higher order
function.
A lambda function can be defined as function argument.

Lambda function is defined with “lambda” keyword.

Syntax:

Variable=lambda [parameters]:expression/statement

Lambda function can be defined,


1. With parameters
2. Without parameters

Lambda functions are frequently used with higher-order functions,


which take one or more functions as arguments or return one or
more functions.

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']

functools.reduce(function, iterable[, initializer])


Apply function of two arguments cumulatively to the items
of iterable, from left to right, so as to reduce the iterable to a single
value. For
example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+
3)+4)+5). The left argument, x, is the accumulated value and the
right argument, y, is the update value from the iterable. If the
optional initializer is present, it is placed before the items of the
iterable in the calculation, and serves as a default when the iterable
is empty. If initializer is not given and iterable contains only one item,
the first item is returned.

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

What is difference between normal function and lambda function?


Normal function Lambda function
Normal function is defined with Lambda function is defined with
“def” keyword “lambda” keyword.
Normal function is defined with Lambda function is anonymous
name function, this function does not
have name
This function contains one or Lambda expression or function
more than one statement contains one statement or single
line function
To return value, it must use Because it is a lambda expression
“return” keyword not required to use return
keyword
This cannot be defined as This can be defined as a function
function argument argument
In application development In application development
normal functions are used for lambda are used to represent
achieving modularity and simple expressions.
reusability

Function Recursion or Recursive functions

Python also accepts function recursion, which means a defined


function can call itself.

Recursion is a common mathematical and programming concept. It


means that a function calls itself. This has the benefit of meaning that
you can loop through data to reach a result.

The developer should be very careful with recursion as it can be


quite easy to slip into writing a function which never terminates, or
one that uses excess amounts of memory or processor power.
However, when written correctly recursion can be a very efficient
and mathematically-elegant approach to programming.
Function recursion required 3 statements
1. Initialization statement
2. Condition
3. Update statement

Initialization statement define initial value of recursion or condition


Condition which define how many times recursive call has to done
Update statement, which updates condition.

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)

n=int(input("Enter any number ")) #3


fact=factorial(n)
print(f'Factorial of {n} is {fact}')

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

n=int(input("Enter any number ")) # 45


countDigits(n)
print(res)

Output:
Enter any number 3456
4

Enter any number 69345


5

Python does not support function overloading


Defining more than one function with same with by changing
arguments. This concept is supported by C++,Java,C#.Net

In python if we write more than one function with same, python


replace old function with new function.

Example
def fun1():
print("fun1 without parameters")

def fun1(a):
print("fun1 with one parameter")
fun1(100)

Output:
fun1 with one parameter

Modules and Packages

What is module in python?

A module is a file containing Python definitions and statements. The


file name is the module name with the suffix .py appended. Within a
module, the module's name (as a string) is available as the value of
the global variable __name__ .

A module can define functions, classes, and variables. A module


can also include runnable code.

Every python program is called one module which is saved with


extension .py
Advantage of modular programming easy to maintain code and
multiple people can work simultaneously on the same project.
Modules and Packages

What is module in python?

A module is a file containing Python definitions and statements. The


file name is the module name with the suffix .py appended. Within a
module, the module's name (as a string) is available as the value of
the global variable __name__ .

A module can define functions, classes, and variables. A module


can also include runnable code.

Every python program is called one module which is saved with


extension .py

Advantage of modular programming easy to maintain code and


multiple people can work simultaneously on the same project.

How to create module?


Creating module is nothing but creating new file or program.
Writing a python program is creating one module only.
Modules are two types
1. Predefined modules
2. User defined modules

Existing modules or modules provided by third party vendors are


called predefined modules. These modules are also called libraries.
Example: datetime, calendar, os, sys, random,….

The modules developed by programmer are called user defined


modules or application specific modules are called user defined
modules.

Example: accounts.py, transaction.py, reports.py, students.py

How to use the content of one module inside another module?

Content of one module can be used inside another module using


“import” keyword.

Syntax1: import module-name,module-name


Syntax2: import module-name as <alias-name>
Syntax3: from <module-name> import *
Syntax4: from <module-name> import <identifier>,<identifier>
Syntax5: from <module-name> import <identifier> as <alias-name>

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

A module which does not contain executable statements is called


reusable module.
A module which contains executable statements is called
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)

Syntax2: import module-name as <alias-name>

Importing module with alias name or alternative name.

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")

Syntax3: from <module-name> import *


This syntax import module content or identifiers (function name,
variable name, class name)
This syntax allows to use content without using module name.

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()

Syntax4: from <module-name> import identifier


This syntax allows importing specific identifiers from module

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>

This syntax allows to import content with alias name or alternative


name.

Module8.py Module10.py
x=100 from module8 import x as p,y as
y=200 q,fun1 as f1
z=300

def fun1(): def fun1():


print("inside fun1") print("fun1 of current module")
def fun2(): x=100
print("inside fun2") y=300
print(x)
print(y)
print(p)
print(q)
fun1()
f1()

How to use executable module as a reusable module

Within a module, the module's name (as a string) is available as the


value of the global variable __name__ .
The value of __name__ is module name, if module imported inside
another module.
The value of __name__ is __main__, if module is executed.
To import executable module as reusable module, one condition is
defined inside module.

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 advantage of packages?


1. Grouping set of modules which perform similar operations
2. Providing security for modules

How to create package?


Creating package is nothing but creating one folder.

Creating package in pycharm


1. Select project
2. Select New
3. Select Python Package

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

What is monkey patching?


Monkey patching in python refers to modifying or updating a piece
of code or class or any module at the runtime. In simple words, we
can change the behavior or working of a class/ module at the
runtime without changing the whole python code

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

Object Oriented Programming (OOP)


Package Manager

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 tool is used for installing and uninstall packages.

All python packages are available in one repository www.pypi.org


Pypi stands for python package index.

pip provides various commands


1. pip install
2. pip uninstall
3. pip download
4. pip list
5. pip show
6. pip freeze

pip install <package-name>


pip uninstall package-name

this command uninstall package which is installed.

pip list

This command is used to list packages installed in system


pip show <package-name>
This command display the complete information about package

pip download package-name


Object Oriented Programming (OOP)

Python is a multi paradigm programming language. It allows writing


programs using various programming paradigms.
A programming paradigm defines set of rules and regulations for
writing programs.

1. Procedural Oriented Programming (POP)


2. Modular Oriented Programming (MOP)
3. Object Oriented Programming (OOP)

Any programming language which support the following principals is


called object oriented programming languages

1. Encapsulation
2. Polymorphism
3. Inheritance
4. Class
5. Object
6. Abstraction

Main objective of learning object oriented programming is


developing user defined data types or classes.

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

Properties define the state of object


Behavior define the functionality of object
Object is an instance of class
Class
Class is a blue print of object
Every data type in python is class and instances are objects.
Class is encapsulated with properties and behavior of object.
Class is used to create object.
Class defines the structure of object.
Class is a collection of variables and methods.
These variables and methods are called members of class.
Class is building block of an object oriented program.
Encapsulation

Encapsulation is process of grouping data and operations which


operate on data into single entity.
Binding data with related operations is called encapsulation.

Advantages of encapsulation
1. Data Hiding
2. Binding

What is data hiding?


Preventing data access from unrelated operations is called data
hiding. This allows for the development of secured applications.

What is binding?
Linking data with related operations is called binding.

Encapsulation is implemented using class.

Writing a class is nothing but building one data type.


Class is a collection of variables/objects and methods
Class is collection of attributes and methods/member functions.
Syntax:
class <class-name>/<datatype-name>:
variables/fields/attributes
methods

Variables defined inside the class are of two types.


1. Instance variables or object level variables
2. Class level variables

Methods defined inside class are three types


1. Instance method or object level method
2. Class level method
3. Static method

Variables define properties of object


Methods defines functionality of object

Instance method or object level method


A method defined inside class with first argument being “self” is
called instance method or object level method.
This method is bind with object name and cannot invoke without
creating object.
This method used to perform object level operation.

What is “self”?

“self” is a name of parameter or argument.


“self” refer to object.
Instance method hold reference of current object on which it is
invoked using “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....")

audi=Car() # Creating object of Car


audi.start()
bmw=Car() # Creating object of Car
bmw.start()
audi.stop()
bmw.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)

Instance Variables or Object Level Variables


Instance variables define the properties of object.
Inside the class instance variables are bind with “self” (OR) any
variable inside class bind with “self” is called instance variable or
object level variable.
Instance variables are created and accessed only inside instance
methods.
Instance variables are object level variables and these are created
inside object (OR) variables belongs to object are instance variables.

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

stud1=Student() # Creating object of Student class


stud1.rollno=101
stud1.name="nk"
print(stud1.rollno,stud1.name)
stud2=Student() # Creating object of Student class
stud2.rollno=102
stud2.name="suresh"
print(stud2.rollno,stud2.name)

Output:
101 nk
102 suresh
Constructor Method or Constructor

Constructor is a special method or magic method or instance


method, which is executed automatically when ever object of class
is created.
Constructor is used for initialization of object (OR) define properties
of object (OR) create instance variable.
Block of code which has to execute automatically on creation of
object is written inside constructor.

Constructor is defined,
1. Without parameters
2. With parameters

__init__ is name of constructor method.

Syntax:
def __init__(self,[para1,para2,…]):
statement-1
statement-2

Example:
class Student:
def __init__(self):
print("student object is created...")

stud1=Student() # creating object of Student class


stud2=Student() # creating object of Student class

Output:
student object is created...
student object is created...

Constructor without parameters does not receive values at the time


creating object.
# Constructor without parameters
class Student:
def __init__(self):
self.rollno=0
self.name=None
self.course=None

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

Constructor with parameters receives values at the time creating


object.

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

Constructor is executed one time at the time of creating object.

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

What is difference between constructor method and normal instance


method?

Constructor Instance method Normal instance method


Name of constructor method is Name of normal instance
__init__ method is any name.
Constructor get executed This method has to be called
automatically at the of time explicitly.
creating object
The purpose of constructor Purpose of this method setter and
method is object initialization getter operations.
Class contains one constructor Class contains any number of
instance methods.

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)

Constructor is for creating instance variables or defining initial


properties of object.
Method is used for setter and getter operations.
An operation which changes the values of object is called setter
operation.
An operation which does not change the values of object is called
getter operation.

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

Advantage of encapsulation is data hiding.


Preventing data access by unrelated operations or outside functions
is called data hiding.

Access Speicifiers or Modifiers


Members of the class are restricted using access modifiers or
specifieres.

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

When data is private, it is accessed with the help of public methods.

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

n=int(input("Enter how players"))


list1=[]
for i in range(n):
name=input("Enter Name ")
score=int(input("Enter Score "))
p=Player(name,score)
list1.append(p)

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

Class variables or class level variables


The variables declared inside class and not bind with self is called
class level variable. Class level variables are global variables, which
are global to more than one object.
Full Stack Python (Part-71)

Class variables or class level variables


The variables declared inside class and not bind with self is called
class level variable. Class level variables are global variables, which
are global to more than one object.
Class level variables bind with class name (OR) class level variables
inside class bind with class name and outside the class bind with
class name.

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 or class method


A method defined inside class with first argument as “cls” is called
class level method. @classmethod decorator is used to transform
method to class level method.

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

What is difference between instance method and class method?


Instance method Class method
A method defined inside class A method defined inside class
with first argument as “self” is with first argument as “cls” and
called instance method declared @classmethod
decorator is called class method
This method is invoked with This method is invoked with class
object name and cannot name without creating object
invoked without creating object
It represents object level It represent class level operation
operation
This method can access instance This method access only class
variables and class variables variables but cannot access
instance variables

Class Reusability

Object oriented application is a collection of classes; the content of


one class can be used inside another class in different ways.

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.

In composition there are two classes


1. Composite class or container class
2. Component class or contained class
Example:
class Engine:
def start(self):
print("Engine Start....")
def stop(self):
print("Engine Stop....")

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

In composition if container object destroyed, it also destroy


contained object.

Aggregation is a special type of composition. In aggregation


component object is not created inside composite class. It is
created outside composite class and inject to composite class using
constructor or methods.
In Aggregation component class object is exists independent of
composite class object.

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.

Inheritance allows to build new data type based on existing data


type.

Inheritance is process of grouping all the classes which share


common properties and behavior.

Advantage of inheritance

Advantage of inheritance is reusability; it allows using variables and


methods of one class inside another class.

inheritance is an is-a relationship.


In Hierarchy of inheritance existing class is called generalized class,
this class is having common properties and behavior.
This class which is derived from existing class is called specialized
class.

Generalized class  Parent class, Super class, Base class


Specialized class  Child class, Sub class, Derived Class
Based on the reusability of classes, inheritance is classified different
types.

1. Single Level Inheritance


2. Multilevel Inheritance
3. Multiple Inheritance
4. Hierarchical Inheritance
5. Hybrid Inheritance

Syntax:
class <derived-class-name>(<base-class-name>,<base-class-
name>,..):
variables
methods

Methods of base class or super class are automatically inherited


inside derived class.

# Single Level Inheritance


class A: # base class/parent class/super class
def m1(self):
print("m1 of A")
def m2(self):
print("m2 of A")
class B(A): # derived class/child class/sub class
def m3(self):
print("m3 of B")
def m4(self):
print("m4 of B")

objb=B()
objb.m1()
objb.m2()
objb.m3()
objb.m4()

Output:
m1 of A
m2 of A
m3 of B
m4 of B

Properties or variables of base class are not inherited automatically


inside derived class.

In order to inherit the properties/variables of base class within


derived class, derived class constructor must call constructor of base
class.

super().method-name
super().variable-name

super() function returns, the reference of super class, using this


reference sub class can invoke members of super class.

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.

Method is override to modify or extend method of base class inside


derived class.

Method is override to provide different implementation of base class


method within derived class.

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)

This method returns string representation of object.


This method is executed automatically whenever object is printed
using print function or when str() function.

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)

What’s the difference between __str__() and __repr__()?


The __str__() method returns a human-readable, or informal, string
representation of an object. This method is called by the built-
in print(), str(), and format() functions. If you don’t define
a __str__() method for a class, then the built-in object
implementation calls the __repr__() method instead.
The __repr__() method returns a more information-rich, or official,
string representation of an object. This method is called by the built-
in repr() function.

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)

The __eq__ method in Python is used to define how objects of a class


are compared for equality. The __eq__ method takes two
arguments: self(object on the left-hand side of == operator ) and
other(object on the right-hand side of == operator). __eq__ method
always returns a boolean value(True or False).

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

What is Polymorphism in oop?

“poly” means “many” and “morphism” is forms. Defining one thing in


many forms is called polymorphism.

In Python, polymorphisms refer to the occurrence of something in


multiple forms. As part of polymorphism, a Python child class has
methods with the same name as a parent class method.

In python polymorphism is achieved using method overriding.

Abstract classes and abstract methods (abc module)

“abc” stands abstract base class module it is default module which


comes with python software. This module is used for developing
abstract classes and abstract methods.
abstract class
abstract class represents abstract data type (ADT). A data type
which allows to build similar data types is called abstract data type.

Abstract class defines set of rules and regulations for building classes.
Abstract class is collection of abstract methods, non abstract
methods and properties.

Syntax of creating abstract class

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

A method without implementation is called abstract method.


Empty method is called abstract method.
Abstract methods should be written inside abstract class.
Abstract method define protocol which must followed by inherited
class (OR) abstract method must be override inside inherited class or
derived class.

Syntax of creating abstract method


@abc.abstractmethod
def <method-name>(self,parameters,..):
pass
Example:
import abc

class A(abc.ABC): # abstract class


@abc.abstractmethod
def m1(self):
pass

class B(A): # concrete class


def m1(self): # overriding method
print("overriding method")

# 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 Or Runtime Polymorphism


An ability of reference variable change its behavior based on the
type of object assigned.
Runtime polymorphism allows to develop loosely coupled code. The
code which works with any type is called loosely coupled code.

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

Nested Classes or Inner classes

Defining class inside class is called nested classes or inner classes.

What is need of nested classes or inner classes?


1. Hiding class inside class
2. Modularity

Inner classes are two types


1. Member class
2. Local class

Member class

If class defined as member of class it is called member class. This


class can access by any member of class.
Syntax:
class Outer-class-name:
variables
methods
class member-class-name:
variables
methods

Example:

Inner class can access members of outer class directly.


Outer class cannot access members of inner class directly.

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

A class defined inside method or block is called local class.


This class is used inside declared block.

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

Compile time errors


The errors which occur during compiling of program are called
compile time errors. All syntax errors are called compile time errors.

These syntax errors must be rectified by programmer in order to


execute program.

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

These logical errors must be rectified by programmer in order to get


accurate result.

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.

When runtime errors occurs program execution is terminated.

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

================== RESTART: E:/student drive/FSP7PM/etest2.py


==================
Enter First Number 7
Enter Second Number 0
Traceback (most recent call last):
File "E:/student drive/FSP7PM/etest2.py", line 3, in <module>
n3=n1/n2
ZeroDivisionError: division by zero

Enter First Number abc


Traceback (most recent call last):
File "E:/student drive/FSP7PM/etest2.py", line 1, in <module>
n1=int(input("Enter First Number "))
ValueError: invalid literal for int() with base 10: 'abc'

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.

Adv of exception handling


1. To avoid abnormal termination program
2. To convert predefined error messages into user defined error
messages
3. Separating business logic and error logic

Every exception or error is one data type or class.


Raising an exception or error is nothing but creating object of
exception class and giving to PVM.

Exception is a root class or parent class for all exception classes.


Exceptions are two types
1. Predefined exceptions
2. User defined exceptions

Predefined exception
The existing exception types are predefined exception.
These exceptions are used by python and python libraries.

User defined exceptions


The programmer defined exception types are called user defined
exceptions.
The keywords used in exception handling
1. try
2. except
3. finally
4. raise

try keyword or try block

The statements which has to be monitored for exception handling or


error handling are written inside try block (OR) the statements which
raise an error during runtime are written inside try block.

Syntax:
try:
statement-1
statement-2

except block

except block is called error handling block.


If there is error inside try block, it is handled by except block.
A try block followed by one or more than one 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

Enter First Number 7


Enter Second Number 0
cannot divide number with zero
Full Stack Python (Part-78)
# Write a program to input n elements into set and remove specific
element

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

Example of printing predefined error message by print exception


object

# Write a program to input n elements into set and remove specific


element
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 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 block with multiple except blocks


If try block generates multiple exceptions or errors, it is handled by
defining multiple except blocks.

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

Enter first number 5


Enter second number 0
cannot divide number with zero

Enter first number 5


Enter second number abc
input value must be integer type

except block without type


except block without error type is called generic except block, this is
able to handle any type of error.
How to get information about exception handled by PVM?

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

Enter first number 5


Enter second number abc
invalid literal for int() with base 10: 'abc'

finally

finally is not an exception handler.


In application development finally block is used for de-allocate the
resources allocated within try block.

Finally block is executed,


1. After execution of try block (NO ERROR)
2. After execution of except block (Handled Error)
3. Error is raised by try block but not handled by except block

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...

inside try block


enter first number 5
enter second number 0
inside except block
inside finally block
continue...
>>>

inside try block


enter first number 5
enter second number abc
inside finally block
Traceback (most recent call last):
File "E:/student drive/FSP7PM/etest4.py", line 4, in <module>
n2=int(input("enter second number "))
ValueError: invalid literal for int() with base 10: 'abc'
raise keyword

A function generates an error using raise keyword.


Generating error is nothing but creating error object and giving to
python virtual machine.

Example:
def multiply(n1,n2):
if n1==0 or n2==0:
raise ValueError()
else:
return n1*n2

num1=int(input("Enter First Number "))


num2=int(input("Enter Second Number "))
try:
num3=multiply(num1,num2)
print(num1,num2,num3,sep="\n")
except ValueError:
print("numbers cannot multiply with zero")

Output:
Enter First Number 5
Enter Second Number 0
numbers cannot multiply with zero

User defined exception class or error class OR Custom Exceptions

User defined exception class is developed by inheriting the


properties and behavior of Exception class.
Exception is a parent class for all predefined and user defined
exception classes.
Syntax:
class <exception-class-name>(Exception):
variables
methods

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

Enter First Number 5


Enter Second Number abc
input value must be integer

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

A file is collection of data or information.


Files are used to save or persists data permanently.
A file is named memory location on secondary storage device (Disk).

Files are two types


1. Text files
2. Binary 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

A file is collection of data or information.


Files are used to save or persists data permanently.
A file is named memory location on secondary storage device (Disk).

Files are two types


1. Text files
2. Binary 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.

Basic steps to work with files


1. Open file
2. Write/Read
3. Close file

How to open file?

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.

How to write text into text file?


1. write(s)
2. print()

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

Reading data from text file

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']

class csv.DictWriter(f, fieldnames)


Create an object which operates like a regular writer but maps
dictionaries onto output rows. The fieldnames parameter is
a sequence of keys that identify the order in which values in the
dictionary passed to the writerow() method are written to file f.

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

class csv.DictReader(f, fieldnames=None)


Create an object that operates like a regular reader but maps the
information in each row to a dict whose keys are given by the
optional fieldnames parameter.

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 stands for Java script object notation.


JSON (JavaScript Object Notation) is a lightweight data-interchange
format. It is easy for humans to read and write. It is easy for machines
to parse and generate.
It is based on a subset of the JavaScript Programming Language
Standard ECMA-262 3rd Edition - December 1999.

JSON is a text format that is completely language independent but


uses conventions that are familiar to programmers of the C-family of
languages, including C, C++, C#, Java, JavaScript, Perl, Python, and
many others. These properties make JSON an ideal data-
interchange language.

JSON is built on two structures:

 A collection of name/value pairs. In various languages, this is realized as


an object, record, struct, dictionary, hash table, keyed list, or associative
array.
 An ordered list of values. In most languages, this is realized as an array,
vector, list, or sequence.
json module

Python provides json module to work with json files.


json module is a default module which comes with python software.
json module provides encoders and decoders for converting python
data types to json and json data types to python.

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.

Create students.xml file

<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>

“xml” module is used to manipulate xml files.


It is a default module which comes with python software.

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)

for name in root.iter("name"):


print(name.text)

for age in root.iter("age"):


print(age.text)

for subject in root.iter("subject"):


print(subject.text)

Output:
students
{}
student
student
student
Rick Grimes
Daryl Dixon
Maggie
35
33
36
Maths
Science
Arts

Binary files

In binary files data is stored in bytes format (OR) binary file is


collection of bytes (OR) binary file allows only bytes data type.

Example:
# Creating binary file
with open("file1.dat","wb") as f:
b=bytes([65,66,67,68,69,70])
f.write(b)

print("data is written inside file")

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”.

There are two methods provided by pickle module,


1. dump
2. load

dump() : write pickled representation of object inside file (OR)


convert object into bytes.
load() : which read bytes and convert into object

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)

print("data is written inside file")

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']}

Pickling and un-pickling user defined objects


emp.py
class Employee:
def __init__(self):
self.__empno=None
self.__ename=None
self.__salary=None
def setData(self,eno,en,s):
self.__empno=eno
self.__ename=en
self.__salary=s
def __str__(self):
return f'{self.__empno},{self.__ename},{self.__salary}'
filetest20.py
# program for pickling

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)

print("employee details are saved within file")


filetest21.py
# unpickling employee objects

import pickle
import emp

with open("employee.ser","rb") as f:
emp1=pickle.load(f)
emp2=pickle.load(f)
print(emp1)
print(emp2)

Regular Expression or re module

“re” is a default module which comes with python software.

What is regular expression?


A regular expression is special string which define search pattern or
match pattern.
Regular expression define pattern of representation of string.

Applications of regular expressions


1. input validations
a. password validation
b. username validation
c. date and time validation
d. mobile number validation
e. email validation
f. url validation
2. Parsers
3. Search engines
4. Machine Learning
a. ChatBot

The following functions provided by re module


re.compile(pattern, flags=0)
Compile a regular expression pattern into a regular expression
object, which can be used for matching using
its match(), search() and other method

re.search(pattern, string, flags=0)


Scan through string looking for the first location where the regular
expression pattern produces a match, and return a
corresponding Match. Return None if no position in the string
matches the pattern
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

re.fullmatch(pattern, string, flags=0)


If the whole string matches the regular expression pattern, return a
corresponding Match. Return None if the string does not match the
pattern

re.split(pattern, string, maxsplit=0, flags=0)


Split string by the occurrences of pattern. If capturing parentheses
are used in pattern, then the text of all groups in the pattern are also
returned as part of the resulting list. If maxsplit is nonzero, at
most maxsplit splits occurs

re.findall(pattern, string, flags=0)


Return all non-overlapping matches of pattern in string, as a list of
strings or tuples. The string is scanned left-to-right, and matches are
returned in the order found. Empty matches are included in the
result.

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

How to create regular expression pattern?

Regular expression pattern or regular expression is created in two


ways.
1. Create string prefix with r
2. Using compile function of re module
>>> 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))
Full Stack Python (part-85)

Regular Expression or re module

“re” is a default module which comes with python software.

What is regular expression?


A regular expression is special string which define search pattern or
match pattern.
Regular expression define pattern of representation of string.

The following functions provided by re module


re.compile(pattern, flags=0)
Compile a regular expression pattern into a regular expression
object, which can be used for matching using
its match(), search() and other method

re.search(pattern, string, flags=0)


Scan through string looking for the first location where the regular
expression pattern produces a match, and return a
corresponding Match. Return None if no position in the string
matches the pattern

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

re.fullmatch(pattern, string, flags=0)


If the whole string matches the regular expression pattern, return a
corresponding Match. Return None if the string does not match the
pattern
re.split(pattern, string, maxsplit=0, flags=0)
Split string by the occurrences of pattern. If capturing parentheses
are used in pattern, then the text of all groups in the pattern are also
returned as part of the resulting list. If maxsplit is nonzero, at
most maxsplit splits occurs

re.findall(pattern, string, flags=0)


Return all non-overlapping matches of pattern in string, as a list of
strings or tuples. The string is scanned left-to-right, and matches are
returned in the order found. Empty matches are included in the
result.

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

How to create regular expression pattern?

Regular expression pattern or regular expression is created in two


ways.
1. Create string prefix with r
2. Using compile function of re module

>>> 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'>

re.search(pattern, string, flags=0)


Scan through string looking for the first location where the regular
expression pattern produces a match, and return a
corresponding Match. Return None if no position in the string
matches the pattern

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

re.findall(pattern, string, flags=0)


Return all non-overlapping matches of pattern in string, as a list of
strings or tuples. The string is scanned left-to-right, and matches are
returned in the order found. Empty matches are included in the
result.

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)
[]

re.fullmatch(pattern, string, flags=0)


If the whole string matches the regular expression pattern, return a
corresponding Match. Return None if the string does not match the
pattern

>>> 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

The special characters used to create regular expression pattern

.
(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’.

>>> str1="ab a abb abbb"


>>> import re
>>> m=re.findall(r'ab+',str1)
>>> print(m)
['ab', 'abb', 'abbb']
>>> list1=re.findall(r'ab*',str1)
>>> print(list1)
['ab', 'a', 'abb', 'abbb']

?
Causes the resulting RE to match 0 or 1 repetitions of the preceding
RE. ab? will match either ‘a’ or ‘ab’.

>>> str1="ab a abb abbb"


>>> list1=re.findall(r'ab?',str1)
>>> print(list1)
['ab', 'a', 'ab', '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.

>>> str1="ab a abb abbb"


>>> list1=re.findall(r'ab{3}',str1)
>>> print(list1)
['abbb']

{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.

>>> str1="ab a abb abbb"


>>> list1=re.findall(r'ab{2,3}',str1)
>>> print(list1)
['abb', 'abbb']
>>> list1=re.findall(r'ab{1,}',str1)
>>> print(list1)
['ab', 'abb', 'abbb']

[]
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

Ranges of characters can be indicated by giving two characters


and separating them by a '-', for example [a-z] will match any
lowercase ASCII letter, [0-5][0-9] will match all the two-digits numbers
from 00 to 59, and [0-9A-Fa-f] will match any hexadecimal digit.

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

Enter Your Email-ID [email protected]


invalid email

Example
# Extracting date from string
import re

str1="date of joining is 12-05-2020"


m=re.search(r'([0-9]{2})-([0-9]{2})-([0-9]{4})',str1)
print(m)
print(m.group(0))
print(m.group(1))
print(m.group(2))
print(m.group(3))

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 ()

If the regular expression uses the (?P<name>...) syntax,


the groupN arguments may also be strings identifying groups by their
group name.

Example:
# Extracting date from string
import re

str1="date of joining is 12-05-2020"


m=re.search(r'(?P<day>[0-9]{2})-(?P<month>[0-9]{2})-(?P<year>[0-9]
{4})',str1)
print(m)
print(m.group('day'))
print(m.group('month'))
print(m.group('year'))
print(m.group(0))
print(m.group(1))
print(m.group(1,2,3))

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

input IFSC code SBI00000123


invalid 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.

>>> str1="python java oracle python python java python"


>>> import re
>>> str2=re.sub(r'java','jython',str1)
>>> print(str2)
python jython oracle python python jython python
>>> str3=re.sub(r'java','jython',str1,1)
>>> print(str3)
python jython oracle python python java python

Python Networking – socket module

Python is a general purpose programming language.


This language is used to develop different types of applications or
software’s.
Python language allows developing networking applications or
networking enabled applications.

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.

Socket module provides socket object/class for developing client


and server program.

Networking programs can be,


1. Connection oriented (TCP)
2. Connection less (UDP)
What is socket?
Socket is an implementation of client and server programs.
Socket is an endpoint communication between two programs.

Socket module provides socket object/class for developing client


and server program.

Networking programs can be,


1. Connection oriented (TCP)
2. Connection less (UDP)

In connection oriented communication, client program connects to


server program and server program should accept the connection
of client. In connection oriented implementation there are two
programs

1. Client
2. Server
Connection oriented implementation is done using TCP sockets.

In connection less communication, sender program send message


to receiver by writing information (packets) with network.
Connection less implementation is done using UDP sockets

For developing networking applications python provides a built in


module called socket.
class socket.socket(family=AF_INET, type=SOCK_STREAM)

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.

SOCK_STREAM  TCP (Connection Oriented)


SOCK_DGRAM  UDP (Connection Less)

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

import socket import socket

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

import socket import socket

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:

Connection less implementation using UDP (User Datagram Protocol)

Default implementation of socket is TCP, to change the socket type


socket constructor provide one parameter type.

Syntax:
socket.socket(type= SOCK_DGRAM)
Connection less implementation using UDP (User Datagram Protocol)

Default implementation of socket is TCP, to change the socket type


socket constructor provide one parameter type.

Syntax:
socket.socket(type= SOCK_DGRAM)

This create socket object with UDP implementation.

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

import socket import socket

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

Limitations of file System


1. Files cannot hold large amount data
2. Files are not secured because files are managed by operating
system
3. It does not provides query language

To overcome above limitations, applications/projects use database


systems or database software.

Database software/Database Applications


1. Oracle
2. MySQL
3. SQLServer
4. SQLLite3
5. PostgreSQL
6. MongoDB
7. MS-Excel

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.

SQL provides set of commands to perform operations on the


database.
Based on the operations, these commands are classified into
different categories

1. DDL 🡪 Data Definition Language


a. CREATE
b. ALTER (like adding/removing column)
c. DROP
2. DML 🡪 Data Manipulation Language
a. INSERT
b. UPDATE (like changing the existing data)
c. DELEE

3. DQL 🡪 Data Query Language


a. SELECT
b. FROM
c. WHERE
d. GROUP BY
e. HAVING
f. ORDER BY

4. TCL 🡪 Transaction Control Language


a. COMMIT
b. ROLLBACK
5. DCL 🡪 Data Control Language
a. GRANT
b. REVOKE

Oracle Database
Install Oracle Software
Oracle 11g Expression Edition

To work with Oracle database


1. Open SQL command line
2. Search SQL command line

Default username : system


Default password : manager
Inside database, data is organized in the form of tables. A table is
collection of rows and columns.
A table is database object.

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.
Syntax-1: Inserting values into all columns

Insert into <table-name> values(value1,value2,value3,…)

Syntax-2: inserting values into selected columns

Insert into <table-name> (col-name,col-name,col-name,..)


values(value1,value2,value3,..)
Full Stack Python (Part-90)

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

Limitations of file System


1. Files cannot hold large amount data
2. Files are not secured because files are managed by operating
system
3. It is does not provides query language

To overcome above limitations, application/projects use database


system or database software.

Database software/Database Applications


1. Oracle
2. MySQL
3. SQLServer
4. SQLLite3
5. PostgreSQL
6. MongoDB
7. MS-Excel

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

1. DDL  Data Definition Language


a. CREATE
b. ALTER
c. DROP
2. DML  Data Manipulation Language
a. INSERT
b. UPDATE
c. DELEE
3. DQL  Data Query Language
a. SELECT
4. TCL  Transaction Control Language
a. COMMIT
b. ROLLBACK
5. DCL  Data Control Language
a. GRANT
b. REVOKE

Oracle Database
Install Oracle Software
Oracle 11g Expression Edition
https://www.oracle.com/database/technologies/xe-
downloads.html

To work with Oracle database


1. Open SQL command line
2. Search SQL command line
Default username : system
Default password : manager

Inside database, data is organized in the form of tables. A table is


collection of rows and columns.
A table is database object.

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.

Syntax-1: Inserting values into all columns

Insert into <table-name> values(value1,value2,value3,…)

Syntax-2: inserting values into selected columns

Insert into <table-name> (col-name,col-name,col-name,..)


values(value1,value2,value3,..)
Full Stack Python (Part-91)

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.

Syntax: select * from <table-name>


Syntax: select <column-name>,<column-name> from <table-name>
Syntax: select * from table-name where <condition>
Commit
Save changes into database

Rollback
Undo changes of database table.

Python  Database Communication

Python program communicate with database software or


application using libraries provided by database vendors.
These libraries are developed by following the abstract given by
python. These abstracts are given in the form a library DB-API.

Libraries used to communicate with various databases


1. Cx_Oracle  Oracle Database
2. Mysql-connector-python  Mysql Database
3. Pyodbc  SQL Server
4. psycopg2  PostgreSQL
5. PyMongo  MongoDB

Python  Oracle Communication


In order to have communication between python and oracle
database, oracle is provided a library called cx_oracle (driver).
cx_Oracle library does not comes with python software.
Basic steps to communicate with database
1. Establish connection to database
2. Create cursor object for sending SQL statements
3. Read result from cursor object
4. Commit/rollback changes
5. Close connection

Establishing connection to database

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)

Creating cursor object

Cursor object is used to send SQL statements to database.


Database server executes SQL statements and return result inside
cursor object.

How to create cursor object?


Connection object is having a method called cursor(), which returns
cursor object.

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...

cursor object provides the following methods for sending SQL


statements.

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

An SQL statement with values is called static SQL statement


An SQL statement with replacement fields is called dynamic SQL
statement, where these fields are replaced with values during
runtime.

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")

ans=input("Add another employee?")


if ans=="no":
break
except:
print("error in establishing connection")

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')

ans=input("Update another employee salary")


if ans=="no":
break
except:
t=sys.exc_info()
print(t[0])

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

# Write a program to delete employee from emp table

import cx_Oracle

with cx_Oracle.connect("system/manager@XE") as cn:


c=cn.cursor()
while True:
eno=int(input("EmployeeNo "))
c.execute("delete from emp where empno=:1",(eno,))
k=c.rowcount
if k>0:
print("employee deleted from database table")
cn.commit()
else:
print(f'{eno} not found')
ans=input("Delete another employee? ")
if ans=="no":
break

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

with cx_Oracle.connect("system/manager@XE") as cn:


c=cn.cursor()
cmd='''create table student_marks1(rollno number(4),
sub1 number(5,2),
sub2 number(5,2),
sub3 number(5,2))'''
try:
c.execute(cmd)
print("Table Created")
except cx_Oracle.DatabaseError:
print("Table exists...")

Output:
Table Created
How to read data from database table?

Reading data from database table is done by sending “SELECT”


query or command to database.

SELECT command is used to read data from database table. This


command read and store data inside cursor object.

To fetch data from cursor object, cursor provides the following


methods.

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}')

print(f'Total Salaries {tot}')


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)]
101 naresh 6000.0
102 suresh 6000.0
103 kishore 7000.0
104 ramesh 8400.0
105 kishore 5000.0
106 rajesh 6000.0
Total Salaries 38400.0

executemany()

cursor.executemany(operation, seq_of_params)

This method prepares a database operation (query or command)


and executes it against all parameter sequences or mappings found
in the sequence 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.

Sql_script is a collection of SQL commands

S1.sql
create table temp(col1 varchar2(20),
col2 varchar2(20));

insert into temp values('1','abc');


insert into temp values('2','xyz');

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

For communicating with mysql database,


1. install MYSQL database software
2. Install mysql-connector-python library

MySQL database software

Download mysql database from the following website

https://dev.mysql.com/downloads/installer/
Installing mysql-connector-python library

User name of mysql : root


Password of mysql is password given at the time installing mysql
software (root)
Basic steps to work database
1. Establish connection to database
2. Create cursor object
3. Send SQL statements
4. Read result from cursor object
5. Commit changes
6. Close connection

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)

# Program to establish connection to Mysql Database

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

import mysql.connector as mysql

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")

ans=input("Add another student ?")


if ans=="no":
cn.commit()
break

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

# program to delete student from stud_marks table

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)

Multithreading (threading module)

Applications are two types


1. Single tasking applications
2. Multitasking applications
A task is an operation performed by application.

An application which allows performing one task at a time is called


single tasking applications.

An application which allows performing more than one task


simultaneously or concurrently is called multitasking application.

Advantage of multitasking applications is utilization CPU idle time


and increasing efficiency of program.

Multitasking applications are two types

1. Process based multitasking


2. Thread based multitasking

Process based multitasking


A process is nothing instance of program (OR) A program under
execution is called process.

Simultaneous execution of more than one process is called process


based multitasking. This type of multitasking is suitable at operating
system.
Thread based multitasking
Thread is an instance of process (OR) A process under execution is
called thread.
Thread performs an operation independent of other operations.
Simultaneous execution of more than one thread is called thread
based multitasking (OR) multithreading.
A thread is an independent part/path of execution within program
or process.

For developing multithreading applications python provides a


predefined module called “threading”. It is default module which
comes with python software.

How to create thread?


Threading module provides “Thread” class for creating thread.
A thread is created in 2 ways

1. Callable object/Function based


2. Inheriting Thread class/Class based

Function based or Callable object

Basic steps for creating thread using function


1. Define a function, which has to be called thread
2. Create thread object by sending function as a target.
3. Invoke start() method of thread class to execute thread.
Every python program is executed within PVM (Process)as one
thread. The default thread created by PVM to run program is called
MainThread.

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

current_thread() is a name of function, which return thread object


which is currently in execution.

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

Life Cycle of Thread


Full Stack Python (Part-96)
Creating thread by inheriting Thread class

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:

Life Cycle of Thread

Thread life cycle is divided into 5 states


1. New born state
2. Runnable state/Ready State
3. Running state
4. Idle state
5. Dead state
Example:
import threading

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

In python memory management is automatic.


Memory management consists of two things.
1. Allocation of memory (Creating object)
2. De-Allocation of memory (Deleting object)

Always python developer allocates memory by creating objects. The


objects created by developer deleted by PVM’s garbage collector.

Garbage collector removes only unused objects or unreferenced


objects.

Q: What is unused object or unreferenced object?


An object bind with reference variable is called referenced object or
used object.
An object not bind with reference variable is called unreferenced
object or unused object.
Every object is having an attribute or property called refcount. The
value of refcount incremented when object is bind with variable and
refcount decremented when object unbind with variable.

Garbage collection always removes objects whose reference count


is 0.
Example:
import sys
class Employee:
def __init__(self,eno,en):
self.__empno=eno
self.__ename=en

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)

An end user communicates with application using two interfaces.


1. CUI (Character User Interface)
2. GUI (Graphical User Interface)

In CUI applications, end user interacts with application by typing


commands.
In GUI applications, end user interacts with application by using
graphical component or graphics or by clicking buttons.

Example of CUI application


# CUI

num1=int(input("Enter first number "))


num2=int(input("Enter second number "))
opr=input("Enter Operator")
match(opr):
case '+':
print(f'sum of {num1} and {num2} is {num1+num2}')
case '-':
print(f'diff of {num1} and {num2} is {num1-num2}')
case '*':
print(f'product of {num1} and {num2} is {num1*num2}')
case '/':
print(f'division {num1} and {num2} is {num1/num2}')

Output
Enter first number 10
Enter second number 20
Enter Operator+
sum of 10 and 20 is 30

Enter first number 10


Enter second number 5
Enter Operator/
division 10 and 5 is 2.0
Example of GUI

How to develop GUI applications?


To develop GUI applications, python provides number of libraries.
1. Tkinter
2. wxPython
3. Kivy
4. PyQT

Tkinter

Tkinter is default library or package which comes with python


software. This library is used for developing GUI applications (OR)
windows based applications.
This library provides functions and classes for developing GUI
applications.
GUI components are called widgets.
Tk class
This class represents window object. It is root object for GUI
application.

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

Button widget is used to perform some operations or execute


commands.
A Python function or method can be associated with a button. This
function or method is named the callback function. If you click the
button, the callback function is called.

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:

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("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

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)

You might also like