Python Notes
Python Notes
1. Features of python
2. Tokens
3. Data types
4. Operators
5. Type conversion (Type casting)
6. Conditional statements
7. Looping statements
8. Jumping statements
9. List
10. Strings
11. Sets
12. Tuples
13. Dictionaries
14. Functions
OOPS PYTHON
“object oriented programming structure”
1. Class
2. Object
3. Constructors
4. Inheritance
5. Polymorphism
6. Data Encapsulation
7. Abstract class &Abstract Method
8. [Link] Handling
1. Features of python
1. Its is a object oriented programming language because in python we are having class,
object ,inheritance.
2. It is a high level language ,because now a days what the programming language we
have to done all the are consider ae a high level language.
3. In python there is “NO COMPAILATION PROCESS” because an interpreter will execute
the program line by line [in C language the compiler can compiler the entire program
at a time
4. Coding is very simple(compare to C )
5. In python there is no data type declaration ,because at the time a of execution an
interpreter will decide based on the value; that which data type
Ex: a=0 [python]
Int a=10 [C]
6. it is a case-sensitive
Ex: Breakwrong
break correct
7. python is a “plat form independent” because in any operating system in python will
work like, windows, …etc.
8. it is a “GUI” (graphical user interface).
1. How to write and execute the program in python.
2. Tokens
Def: it is a smallest unit of any programming language.
NAME = SRIDHAR
STD = [Link]
AGE = 20
1. Identifiers (variables)
A python identifiers is a “name” used to identify a variable, function, class, module or other object.
Rules :
Ex:
Ex:
Types of literals:
a) Numerical literals
b) String literals
c) Boolean literals
d) Special literals
3. Punctuators
Punctuator are symbols that are used in programming languages to organize sentence and
programming structure.
4. Key words
2. True
5. Or 23. Global
7. Is 25. Try
8. In 26. As
9. If 27. Assert
16. Pass
17. Def
18. Return
19. Lambda
3.D ATA TYPES
Python Supports the Dynamic data type. that is at the time of execution of program
Data type of threat of a variable will be decided based on the data which is assigned to that
variable.
*** It is used to Specified what type of data has to be Stored into the variable. There
1. None (null)
I. int ( integer )
II. Float
III. Complex
I. List
II. String
1. Int
Integer, is a whole number, positive or negative, without decimals, of unlimited
length.
It is Immutable (un- changeable)
Example:
i=45
type(i)
<class 'int'>
print(i)
45
2. Float
“Floating point number" is a number, positive or negative, containing one or more
decimals.
It is Immutable.
Example:
f=(45.5)
type(f)
<class 'float'>
print(f)
45.5
3. complex
Complex numbers Form: x+yj
x: real part
y: imaginary part
it is Immutable
Example:
cl=(45+77.7j)
type(cl)
<class 'complex'>
print(cl)
(45+77.7j)
[Link]
Boolean: True or False
It is Immutable
Example:
b=True
type(b)
<class 'bool'>
print(b)
True
[Link]
List is a sequence of ordered homogeneous elements. Symbol: [ ]
Supports indexing (positive, negative).
It is Mutable
Example:
list=[10,20,30,40]
type(list)
<class 'list'>
print(list)
[10, 20, 30, 40]
6 . str
Strings: combination of characters.
Each character in string can be accessed by index.
Positive index starts from ‘0’(left to right).
Negative index starts from’-1’(right to left).
It is Immutable
Example:
str="sridhar"
type(str)
<class 'str'>
print(str)
sridhar
[Link]
tuple is a sequence of ordered heterogeneous objects
Symbol: ( ) Supports indexing (positive, negative).
It isimmutable
Example:
type(t)
<class 'tuple'>
print(t)
(45, 77, 10, 46)
[Link]
Set is a collection of un- ordered elements.
Symbol: { }
Discards the duplicates
It is mutable
Example:
s={11,23,35,65}
type(s)
<class 'set'>
print(s)
{65, 35, 11, 23}
[Link]
Dictionaries are used for mapping (key,value) pairs.
It is mutable.
Example:
d={1:'s',2:'r',3:'i'}
type(d)
<class 'dict'>
print(d)
{1: 's', 2: 'r', 3: 'i'}
4. Operators in python
Following are the basic operators in python
1. Arithmetic operators
2. Bitwise operators
3. Logical operators
4. Relational Operators
5. Assignment operators:
6. Special operators: Identity operators and Membership operators
Arithmetic operators:
Arithmetic operators are used to perform mathematical operations like addition,
subtraction, multiplication and division.
OPERATOR NAME SYNTAX
+ Addition x+y
Subtraction x-y
-
Multiplication x*y
*
Division (float) x/y
/
Division (floor) x // y
//
Modulus x%y
%
Example program:
a=5
b=2
print('a+b=',a+b)
print('a-b=',a-b)
print('a*b=',a*b)
print('a/b=',a/b)
print('a//b=',a//b)
print('a**b=',a**b)
OPU
OUTPUT
a+b= 7
a-b= 3
a*b= 10
a/b= 2.0
a//b= 2
a**b= 25
Bitwise Operators:
Bitwise operators acts on bits and performs bit by bit operation.
OPERATOR NAME SYNTAX
OUTPUT:
a&b= 8
a|b= 15
~a 11
a^b= 7
a<<b= 45056
a>>b= 0
Logical Operators:
Logical operators perform Logical AND, Logical OR and Logical NOT operations.
OPERATOR NAME SYNTAX
Or Logical OR x or y
Example program:
a=10
b=5
print((a<b)and(a<b))
print((a>b)or(a>b))
print(not(a<b))
output:
False
True
True
Relational Operators:
Relational operators compares the values. It either returns True or False
according to the condition
OPERATOR NAME SYNTAX
== Equal to x == y
!= Not equal to x != y
Example Program:
a=10
b=5
print('a<b=',a<b)
print('a>b=',a>b)
print('a<=b=',a<=b)
print('a>=b is',a>=b)
print('a==b=',a==b)
print('a!=b=',a!=b)
output:
a<b= False
a>b= True
a<=b= False
a>=b is True
a==b= False
a!=b= True
Assignment operators:
Assignment operators are used to assign values to the variables.
OPERATOR DESCRIPTION SYNTAX
= Assignment x=y+z
Add AND: Add right side operand with left side operand and
Subtract AND: Subtract right operand from left operand and then
Divide AND: Divide left operand with right operand and then
//= and then assign the value(floor) to left operand a//=b a=a//b
Special Operators:
Identity Operators:
is and is not are the identity operators both are used to check if two values are located
on the same part of the memory. Two variables that are equal does not imply that
they are identical.
Example program
a=10
b=5
print(a is b)
print(a is not b)
output
True
False
Membership Operators:.
in and not in are the membership operators; used to test whether a value or
variable is in a sequence.
Example program
a=' triveni '
b='indu'
print('a' in b)
print('i' not in b)
output
True
false
5. Type Conversion functions:
Python defines type conversion functions to directly convert one data type to
another which is useful in day to day and competitive programming.
Following are some conversion functions.
int(a, base) : This function converts any data type to integer. ‘Base’ specifies the base in
which string is if data type is string.
float() : This function is used to convert any data type to a floating point number
Program 1 :
(before type casting)
a=input("enter a number1")
b=input("enter a number2")
c=a+b
print(c)
output
enter a number1199
enter a number2111
199111
Program 2 :
(after type casting)
a=int(input("enter a number 1"))
b=int(input("enter a number 2"))
c=a+b
print(c)
output
enter a number 1100
enter a number 2200
300
Example program
output
enter a number 156
0x38
num=int(input("enter a number 1"))
print(oct(num))
output
enter a number 118
0o22
num=input("enter a number")
print(ord(num))
output
enter a numbera
97
Hacker rank
Print the output with a new line
Write a program to print the below-give output.
Case 1
Input (stdin)
Hello!
Welcome to Python Programming
Output (stdout)
Hello!
Welcome to Python Programming
Write a program to get a float value from the user and display it in the below-
mentioned format.
INPUT & OUTPUT FORMAT:
Input consists of 1 float value.
Output must display the given input and also display the input with one, two and three
decimal points.
SAMPLE INPUT:
23.115
SAMPLE OUTPUT:
23.115000
23.115
23.11
23.1
Test case 1
Input
23.115
Output
23.115000
23.115
23.11
23.1
Test case 2
Input
345.67
Output
345.670000
345.670
345.67
345.7
Round Off
Write a program to get a float value from the user and display it in the below-mentioned format.
HINT: Use ceil() and floor() functions from header file.
INPUT & OUTPUT FORMAT:
Input consists of one float value.
Output consists of one integer, its highest round off value and its lowest round off value.
Case 1
Input (stdin)
54.5
Output (stdout)
54
55.0
54.0
Case 1
Input (stdin)
A
Output (stdout)
65
Case 2
Input (stdin)
a
Output (stdout)
97
Arithmetic operator
Write a program to perform arithmetic operations such as addition, subtraction, multiplication,
modulo division and division.
INPUT & OUTPUT FORMAT:
Input consists of two integers
Output consist of integers
Case 1
Input (stdin)
5
2
Output (stdout)
7
3
10
1
2
25
Case 2
Input (stdin)
9
3
Output (stdout)
12
6
27
0
3
343
Cricket Stadium
There was a large ground in center of the city which is rectangular in shape. The Corporation decides
to build a Cricket stadium in the area for school and college students, But the area was used as a car
parking zone. In order to protect the land from using as an unauthorized parking zone , the corporation
wanted to protect the stadium by building a fence. In order to help the workers to build a fence, they
planned to place a thick rope around the ground. They wanted to buy only the exact length of the rope
that is needed. They also wanted to cover the entire ground with a carpet during rainy season. They
wanted to buy only the exact quantity of carpet that is needed. They requested your help. Can you
please help them by writing a program to find the exact length of the rope and the exact quantity of
carpet that is required?
Input format:
Input consists of 2 integers. The first integer corresponds to the length of the ground and the second
integer corresponds to the breadth of the ground. Output Format:
Output Consists of two integers. The first integer corresponds to the perimeter. The second integer
corresponds to the quantity of carpet required.
Case 1
Input (stdin)
50
20
Output (stdout)
140
1000
Case 2
Input (stdin)
70
40
Output (stdout)
220
2800
Dept Repay
Alice wanted to start a business and she was looking for a venture capitalist. Through her friend Bob,
she met the owner of a construction company who is interested to invest in an emerging business.
Looking at the business proposal, the owner was very much impressed with Alice's work. So he
decided to invest in Alice's business and hence gave a green signal to go ahead with the project. Alice
bought Rs.X for a period of Y years from the owner at R% interest per annum. Find the rate of
interest and the total amount to be given by Alice to the owner. The owner impressed by proper
repayment of the financed amount decides to give a special offer of 2% discount on the total interest
at the end of the settlement. Find the amount given back by Alice and also find the total amount.
(Note: All rupee values should be in two decimal points).
INPUT FORMAT:
Input consists of 3 integers. The first integer corresponds to the principal amount borrowed by Alice.
The second integer corresponds to the rate of interest The third integer corresponds to the number of
years.
OUTPUT FORMAT:
The output consists of 4 floating point values. The first value corresponds to the interest. The second
corresponds to the amount. The third value corresponds to the discount. The last value corresponds to
the final settlement. All floating point values are to be rounded off to two decimal places
Case 1
Input (stdin)
100
1
10
Output (stdout)
10.00
110.00
0.20
109.80
Case 2
Input (stdin)
10000
10
5
Output (stdout)
5000.00
15000.00
100.00
14900.00
Case 1
Input (stdin)
1000
2
1
Output (stdout)
900
Case 2
Input (stdin)
900
5
3
Output (stdout)
1700
Four musketeers
'Artagnan joined the group of 3 Musketeers and now their group is called four Musketeers.
Meanwhile, d'Artagnan also moved to a new house in the same locality nearby to the other three.
Currently, the houses of Athos, Porthos and Aramis are located in the shape of a triangle. When the
three musketeers asked d'Artagnan about the location of his house, he said that his house is
equidistant from the houses of the other 3. Can you please help them find out the location of the
house? Given the 3 locations {(x1,y1), (x2,y2) and (x3,y3)} of a triangle, write a program to
determine the point which is equidistant from all the 3 points.
INPUT FORMAT:
Input consists of 6 integers. The first integer corresponds to x1. The second integer corresponds to y1.
The third and fourth integers correspond to x2 and y2 respectively. The fifth and sixth integers
correspond to x3 and y3 respectively.
OUTPUT FORMAT:
The output consists of two floating point numbers (with one decimal place) which correspond to the
location of the house.
Case 1
Input (stdin)
2
4
10
15
5
8
Output (stdout)
5.7
9.0
Case 2
Input (stdin)
1
1
1
1
1
1
1
Output (stdout)
1.0
1.0
Treasure Hunter
Though there have been more successful pirates, Blackbeard is one of the best-known and widely-
feared of his time. He commanded four ships and had a pirate army of 300 at the height of his career
and defeated the famous warship, HMS “Scarborough” in sea-battle. He was known for barreling into
battle clutching two swords with several knives and pistols at the ready. He captured over forty
merchant ships in the Caribbean and without flinching killed many prisoners. Now, Blackbeard and
his three pirates found a treasure of gold coins. Long Ben too joined them. They decided to share the
treasure. Blackbeard agreed to give x% share for Long Ben. He then decided to take y% share from
the remaining treasure. His other pirates will share the remaining gold coins equally. Write a program
to compute their share's. INPUT FORMAT:
Input consists of 3 integers. The first input corresponds to the number of gold coins in the treasure.
The second input corresponds to Ben's share percentage and the last input is Blackbeard's share
percentage.
OUTPUT FORMAT:
The output consists of three integers. The first output integer corresponds to Long Ben's share. The
second integer corresponds to Blackbeard's share. The last integer corresponds to other pirates share.
Case 1
Input (stdin)
729
65
87
Output (stdout)
473
222
11
Booka the alien
Booka is an alien. He couldn't understand how to measure days, weeks, months and years. Make
Booka understand what is meant by days, weeks, months and years. Teach him about the conversion
of days into years, months and weeks using a program.
INPUT FORMAT:
Input consists of an integer which corresponds to the number of days.
OUTPUT FORMAT:
The output consists of three integers. The first integer corresponds to the total years. The second
integer corresponds to the total months. The third integer corresponds to the total days.
Case 1
Input (stdin)
373
Output (stdout)
1
0
8
Case 2
Input (stdin)
365
Output (stdout)
1
0
0
Unit-2
[Link] Statements (or)Decision Making
Statements:
Conditional statements in programming languages decides the direction of flow of
program execution.
Conditional statements are also called as Decision making statements.
if statement
if-else statements
nested if statements
if-elif ladder
o
if statement:
if statement is the simple decision-making statement.
It is used to decide whether a certain statement or block of statements will be executed
or not i.e if a certain condition is true then a block of statement is executed otherwise
not.
Syntax:
if condition:
#statements (Or)
if(condition)
#statements
if statement accepts boolean values – if the value is true then it will execute the block of
statements below it otherwise not.
python uses indentation to identify a block. So the block under an if statement will be
identified as shown in the below example:
if (condition):
#statement1
#statement2
Example program
a=45
if a>30:
print('the given number is less')
print('number is found')
output
the given number is less
number is found
: if-else
The if statement alone tells us that if a condition is true it will execute a block
of statements and if the condition is false it won’t.
But what if we want to do something else if the condition is false. Here comes the else
statement. We can use the else statement with if statement to execute a block of code
when the condition is false.
Syntax:
if (condition):
#statements
else:
#statements
Example programs :
write a python program whether the given number is even or odd.
num=int(input("enter a number"))
if num%2==0:
print("the given number even")
else:
print("the given number odd")
print("program is over")
output
enter a number45
the given number odd
program is over
OUTPUT:
year=int(input("enter a year"))
if year%4==0:
print("its is leap year")
else:
print("its is not leap year")
print("program is over")
output:
enter a year2025
its is not leap year
program is over
num1=int(input("enter a number"))
num2=int(input("enter a number"))
if num1>num2:
print("num1 given number is less")
else:
print("num2 given number is high")
print(" program is over")
output
enter a number15
enter a number3
num1 given number is less
program is over
Nested if-else:
A nested if is an if statement that is the target of another if statement.
Nested if statements means an if statement inside another if statement.
Yes, Python allows us to nest if statements within if statements. i.e, we can
place an if statement inside another if statement.
Syntax:
if (condition1):
if (condition2):
#statements
else:
#statements
Example program:
i=20
if i>0:
if i>15:
print("i is greater than 15")
else:
print("i is smaller than 15")
else:
print("i is negative number")
OUTPUT:
i is greater than 15
if-elif-else ladder:
The if statements are executed from the top down. As soon as one of the
conditions controlling the if is true, the statement associated with that if is executed, and the
rest of the ladder is bypassed. If none of the conditions is true, then the final else
statement will be executed.
Syntax:
if (condition1):
#statements
elif
(condition2):
#statements
else:
#statements
Example program
Example:
i = 20
if (i == 10):
print ("i is 10")
elif (i == 15):
print ("i is 15")
elif (i == 20):
print ("i is 20")
else:
print ("i is not present")
Output:
i is 20
Example program:
write a python program based on age.
output
enter the age20
you are young
program is over
output:
enter the marks77
you are in A grade
program is over
[Link] Statements:
Python programming language provides following types of loops to handle looping
requirements.
while
for
while loop:
A while loop implements the repeated execution of code based on a given
Boolean condition.
The code that is in a while block will execute as long as the while statement evaluates to True.
As opposed to for loops that execute a certain number of times, while loops are
conditionally based, so we don’t need to know how many times to repeat the code going in.
Syntax:
while (expression):
#statements
Example:
count = 0
while (count < 3):
print("Hello Python")
count = count+1
Output:
Hello Python
Hello Python
Hello Python
EXAMPLE PROGRAMS
Write a python program to print the odd numbers upto 20.
i=1
while(i<=20):
print(i)
i=i+2
print("loop is closed")
output:
1
3
5
7
9
11
13
15
17
19
loop is closed
output:
2
4
6
8
10
12
14
16
18
20
loop is closed
1)WHILE:
Example 1: : write a python program whether the given number is armstrong or not.
num=int(input("enter a number"))
sum=0
temp=num
while (temp>0):
rem=temp%10
sum=sum+rem**3
temp=temp//10
if (sum==num):
print("it is a armstrong number")
else:
print("it is not a armstrong number")
Output:
enter a number153
it is a armstrong number
enter a number407
it is a armstrong number
Example 2: write a python program whether the given number is palindrome or not.
Output:
enter the number1221
it is a palindrome number
enter the number143
it is not a palindrome number
Example 3: write a python program whether the given number is spy or not.
num=int(input('enter a number:'))
sum=0
prod=1
temp=num
while(temp>0):
rem=temp%10
sum=sum+rem
prod=prod*rem
temp=temp//10
if sum==prod:
print('it is a spy number')
else:
print('it is not a spy number')
Output:
enter a number:132
it is a spy number
enter a number:1432
it is not a spy number
Example 5: write a python program whether the given number is neon or not.
num=int(input('enter a number:'))
sum=0
sqr=num**2
while(sqr>0):
rem=sqr%10
sum=sum+rem
sqr=sqr//10
if sum==num:
print('it is a neon number')
else:
print('it is not a neon number')
Output:
enter a number:9
it is a neon number
enter a number:23
it is not a neon number
Example 6: write a python program whether the given number is harshad or not.
num=int(input('enter a number:'))
sum=0
temp=num
while(temp>0):
rem=temp%10
sum=sum+rem
temp=temp//10
if num%sum==0:
print('it is a harshad number')
else:
print('it is not a harshad number')
Output:
enter a number:18
it is a harshad number
enter a number:81
it is a harshad number
Example7: write a python program whether the given number is perfect or not.
num=int(input('enter a number:'))
sum=0
i=1
while(i<=num//2):
if(num%i==0):
sum=sum+i
i=i+1
if sum==num:
print('it is perfect number')
else:
print('it is not a perfect number')
Output:
enter a number:6
it is perfect number
enter a number:32
it is not a perfect number
Example 7:
a=0
b=1
i=1
value=int(input("enter a given range"))
list=[0,1]
while(i<=value-2):
result=a+b
[Link](result)
a=b
b=result
i=i+1
print(list)
output:
enter a given range6
[0, 1, 1, 2, 3, 5]
Nested while
write a python program whether the given number is strong or not.
num=int(input("enter a number"))
sum=0
temp=num
while(temp>0):
i=1
fact=1
rem=temp%10
while(i<=rem):
fact=fact*i
i=i+1
sum=sum+fact
temp=temp//10
if(sum==num):
print("strong number")
else:
print("it is not strong number")
output
enter a number145
strong number
for loop:
A for loop implements the repeated execution of code based on a loop counter or loop
variable.
For loops are used most often when the number of iterations is known before entering the
loop, unlike while loops which are conditionally based.
In Python, for loops are constructed like so:
Syntax:
for iterating_var in sequence:
statements
Example:
for i in range(0,5):
print(i)
Output
0
1
2
3
4
This for loop sets up i as its iterating variable, and the sequence exists in the range of 0
to 5.
Then within the loop we print out one integer per loop iteration. Keep in mind that in
programming we tend to begin at index 0, so that is why although 5 numbers are printed
out, they range from 0-4.
For Loops using range()
One of Python’s built-in immutable sequence types is range().
In loops, range() is used to control how many times the loop will be repeated.
When working with range(), you can pass between 1 and 3 integer arguments to it:
1. start states the integer value at which the sequence begins, if this is not
included then start begins at 0
2. stop is always required and is the integer that is counted up to but not included
3. step sets how much to increase (or decrease in the case of negative numbers) the
next iteration, if this is omitted then step defaults to 1
Example-1: range(stop)
for i in range(6):
print(i)
Output
0
1
2
3
4
5
Example programs
FOR:
EX:1 : print even number upto 20
for i in range(2,20,2):
print(i)
O/P:
2
4
6
8
10
12
14
16
18
for i in range(1,15):
print(i)
O/P:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
EX:3
for i in range(10):
print(i)
O/P:
0
1
2
3
4
5
6
7
8
9
write a python program whether the given number is fascinating number or not.
num=int(input("enter a number"))
if num<100:
print("fasinating is not defined")
else:
result=str(num)+str(num*2)+str(num*3)
expected_list=['1','2','3','4','5','6','7','8','9']
if sorted(result)==expected_list:
print("it is fasinating number")
else:
print("it is not fasinating number")
output:
enter a number192
it is fasinating number
num=int(input('enter a number:'))
fact=1
if num<0:
print('factorials are not defined by negative values')
elif num==0:
print('factorial of 0 is 1')
else:
for i in range(1,num+1):
fact=fact*i
print('factorial of',num,'is',fact)
output:
enter a number:5
factorial of 5 is 120
a=0
b=1
value=int(input("enter a given range"))
list=[0,1]
for i in range(value-2):
result=a+b
[Link](result)
a=b
b=result
print(list)
output:
enter a given range5
[0, 1, 1, 2, 3]
output:
enter the number5
it is automorphic
O/P:
enter the number5
triomorphic
enter the number6
triomorphic
enter the number9
triomorphic
O/P:
enter the value10
enter the value40
11,13,17,19,23,29,31,37
num=int(input('enter a number:'))
flag=0
for i in range(2,num):
if(num%i==0):
flag=1
break
if flag==1:
print('it is not a prime number')
else:
print('it is prime number')
O/P:
enter a number:5
it is prime number
enter a number:23
it is prime number
range function
a=0
b=1
value=int(input("enter the range:"))
x=[0,1]
for i in range(1,value-1):
result=a+b
[Link](result)
a=b
b=result
print(x)
O/P:
enter the range:4
[0, 1, 1, 2]
enter the range:7
[0, 1, 1, 2, 3, 5, 8]
Output
Hyderabad Vizag
Bangalore
Chennai
Nested Loops:
Loops can be nested in Python, as they can with other programming languages.
A nested loop is a loop that occurs within another loop, structurally similar to nested
if statements.
Syntax:
The program first encounters the outer loop, executing its first iteration. This first iteration
triggers the inner, nested loop, which then runs to completion. Then the program returns
back to the top of the outer loop, completing the second iteration and again triggering the
nested loop.
Again, the nested loop runs to completion, and the program returns back to the top of the
outer loop until the sequence is complete or a break or other statement disrupts the
process.
Example-1:
num_list = [1, 2, 3]
alpha_list = ['a', 'b'] for
number in num_list:
print(number)
for letter in alpha_list:
print(letter)
Output:
1
a b 2
a b 3
a b
Example-2:
list_of_lists = [['a', 'i', 'm'],[0, 1, 2],[9.9, 8.8, 7.7]]
for list in list_of_lists:
for item in list:
print(item)
Output:
a i m 0
1
2
9.9
8.8
7.7
Example: write a python program whether the given number is strong or not.
num=int(input("enter a number"))
sum=0
temp=num
while(temp>0):
i=1
fact=1
rem=temp%10
while(i<=rem):
fact=fact*i
i=i+1
sum=sum+fact
temp=temp//10
if(sum==num):
print("strong number")
else:
print("it is not strong number")
output:
enter a number145
strong number
[Link] Statements:(JUMPING
STATEMENT)
Using for loops and while loops in Python allow you to automate and repeat tasks in an
efficient manner.
But sometimes, an external factor may influence the way our program runs. When this occurs,
we may want our program to exit a loop completely, skip part of a loop before continuing, or
ignore that external factor. we can perform these actions with break, continue, and
pass statements.
break:
In Python, the break statement provides with the opportunity to exit out of a loop when an external
condition is triggered. We will put the break statement within the block of code under loop statement,
usually after a conditional if statement.
It is used to terminate the loop.
*JUMPING STATEMENTS:
Example program:
1)BREAK:
for i in range(10):
if i==6:
break
print(i)
print('program over')
output:
0
1
2
3
4
5
program over
EX:2
num=int(input('enter a number:'))
flag=0
for i in range(2,num):
if(num%i==0):
flag=1
break
if flag==1:
print('it is not a prime number')
else:
print('it is prime number')
O/P:
enter a number:5
it is prime number
enter a number:23
it is prime number
continue:
The continue statement gives the option to skip over the part of a loop where an external
condition is triggered, but to go on to complete the rest of the loop.
That is, the current iteration of the loop will be disrupted, but the program will return to the
top of the loop.
The continue statement will be within the block of code under the loop statement, usually
after a conditional if statement.
We can use the continue statement to avoid deeply nested conditional code, or to
optimize a loop by eliminating frequently occurring cases that you would like to reject.
The continue statement causes a program to skip certain factors that come up within a loop,
but then continue through the rest of the loop.
CONTINUE:
for i in range(10):
if(i==3):
continue
print(i)
print('sridhar')
O/P:
0
1
2
4
5
6
7
8
9
Sridhar
pass:
When an external condition is triggered, the pass statement allows to handle the condition
without the loop being impacted in any way; all of the code will continue to be read unless a
break or other statement occurs.
As with the other statements, the pass statement will be within the block of code under the
loop statement, typically after a conditional if statement.
PASS:
for i in range(1,10):
if i==5:
print('sridhar')
pass
print(i)
print('program over')
O/P:
1
2
3
4
sridhar
5
6
7
8
9
program over
Program:
num=int(input('Enter any value:'))
print('multiplication table of',num,'is:') for i
in range(1,11):
print(num,'*',i,'=',num*i)
Output:
Enter any value:5 multiplication
table of 5 is:
5 *1 = 5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50
Program:
num=int(input('Enter any positive number:'))
even_list=[]
odd_list=[]
for i in range(0,num): if(i
%2==0):
even_list.append(i) else:
odd_list.append(i) print('Even
numbers are:',even_list) print('Odd
numbers are:',odd_list)
Output:
Enter any positive number:20
9. LIST
Python lists are ordered sequences of items. For instance, a sequence of n numbers might be
called S:
S = s0, s1, s2, s3, …, sn-1
A list or array is a sequence of items where the entire sequence is referred to by a single
name (i.e. s) and individual items can be selected by indexing (i.e. s[i]).
Python lists are dynamic. They can grow and shrink on demand.
Python lists are also heterogeneous, a single list can hold arbitrary data types.
Python lists are mutable sequences of arbitrary objects.
CREATING A LIST:
In Python programming, a list is created by placing all the items (elements) inside a
square bracket [ ], separated by commas.
It can have any number of items and they may be of different types (integer, float,
string etc.).
Ex:
l=[]
type(l)
<class 'list'>
print(l)
[]
Ex
l=[10,20,30,40,50]
type(l)
<class 'list'>
print(l)
[10, 20, 30, 40, 50]
Ex
l=[10,"sridhar",4.5]
type(l)
<class 'list'>
print(l)
[10, 'sridhar', 4.5]
Also, a list can even have another list as an item. This is called nested
Ex
l=[10,20,[1,2,3,4],30]
type(l)
<class 'list'>
print(l)
[10, 20, [1, 2, 3, 4], 30]
l[2]
[1, 2, 3, 4]
List() Method To Create A List
Python includes a built-in list() method.
It accepts either a sequence or tuple as the argument and converts into a
Python list.
Ex:
List = list() empty list len(List)
0
ACCESSING ELEMENTS OF A LIST:
There are various ways in which we can access the elements of a list.
1. List Index
We can use the index operator [] to access an item in a list. Index starts from 0. So, a list
having 5 elements will have index from 0 to 4.
Ex:
list = ['s','r','i','d','h'’a’,’r’]
print(list[0])
Output: s
print(list[2])
Output: i
print(ist[4])
Output: h
Trying to access an element other that this will raise an Index Error. The index must be an
integer. We can't use float or other types, this will result into Type Error.
Ex:
list[4.0]Error! Only integer can be used for indexing
Nested list are accessed using nested indexing.
Ex:
list = ["sridhar", [2,0,1,5]]
print(list[0][1])
Output: s
print(list[1][3])
Output: 5
Python allows negative indexing (Reverse Indexing) for its sequences. The index of
-1 refers to the last item, -2 to the second last item and so on.
Ex:
List=['s','r','i','d','h',’a’,r’]
Print(list[-1])
Output: r
print(list[-5])
Output: i
Extend operator can be used to concatenate one list into another. It is not possible to store
the value into the third list. One of the existing list has to store the concatenated result.
Example:
list_c =list_a.extend(list_b) print
list_c
Output: NoneType
print list_a
Output: [1, 2, 3, 4, 5, 6, 7, 8]
print list_b
Output: [5, 6, 7, 8]
Slicing:
Given a string s, the syntax for a slice is:
s[ startIndex : pastIndex ]
The startIndex is the start index of the string. pastIndex is one past the end of the slice.
Ex:
List = [1, 2, 3, 4, 5, 6, 7, 8]
List[2:5]
Output
[3,4,5]
Since Python list follows the zero-based index rule, so the first index starts at 0.
In slicing, if you leave the start, then it means to begin slicing from the 0th index.
Ex:
List[:2] [1, 2]
While slicing a list, if the stop value is missing, then it indicates to perform slicing to the end
of the list. It saves us from passing the length of the list as the ending index.
Ex:
List[2:]
[3, 4, 5, 6, 7, 8]
Reverse A Python List Using The Slice Operator
o It is effortless to achieve this by using a special slice syntax (::-1). But please remember that
reversing a list this way consumes more memory than an in-place reversal.
o Here, it creates a shallow copy of the Python list which requires long enough space for holding
the whole list.
Ex:
List[::-1]
[8, 7, 6, 5, 4, 3, 2, 1]
Iteration:
Python provides a traditional for-in loop for iterating the list. The for statement makes it super
easy to process the elements of a list one by one.
for element in List:
print(element)
If you wish to use both the index and the element, then call the enumerate () function.
for index, element in enumerate(List): print(index,
element)
If you only want the index, then call the range() and len() methods.
for index in range(len(List)):
print(index)
Ex:
List = ['Python', 'C', 'C++', 'Java', 'CSharp']
Output –
I like Python I like C
I like C++ I like Java
I like CSharp
List methods:
[Link](elem) -- adds a single element to the end of the list. Common error:
does not return the new list, just modifies the original.
[Link](index, elem) -- inserts the element at the given index, shifting elements to
the right.
[Link](list2) -- adds the elements in list2 to the end of the list. Using + or += on
a list is similar to using extend().
[Link](elem) -- searches for the given element from the start of the list and
returns its index. Throws a ValueError if the element does not appear (use "in"
to check without a ValueError).
[Link](elem) -- searches for the first instance of the given element and
removes it (throws ValueError if not present)
[Link]() -- sorts the list in place (does not return it). (The sorted() function shown
later is preferred.)
[Link]() -- reverses the list in place (does not return it)
[Link](index) -- removes and returns the element at the given index. Returns the
rightmost element if index is omitted (roughly the opposite of append()).
Examples:
AIR PIC SRCC
A APPEND
I INSERT
R REMOVE
P POP
I INDEX
C COPY
S SORT
R REVERS
C COUNT
C CLEAR
1)APPEND ( ): adds a single element to the end of the list.
Ex :
l=[10,20,30,40,50]
[Link](60)
print(l)
output:
[10, 20, 30, 40, 50, 60]
EX:l=[1,2,3,4,5,6,7]
[Link](5)
l
output:
[1, 2, 3, 4, 6, 7]
4)POP ( ): remove and return an element at the specicfied position.
Ex:
l=[12,13,14,1516]
[Link](3)
1516
l
Output:
[12, 13, 14]
Ex:
l=[21,22,23,34,45,67]
[Link](23)
2
[Link](67)
5
Ex:
l=[11,22,33]
l=l*10
print(l)
[11, 22, 33, 11, 22, 33, 11, 22, 33, 11, 22, 33, 11, 22, 33, 11, 22, 33, 11, 22, 33, 11, 22, 33, 11, 22, 33, 11, 22,
33]
[Link](11)
output:
10
Ex:
l=['s','r','i','d','h','a','r']
[Link]()
print(l)
output:
['a', 'd', 'h', 'i', 'r', 'r', 's']
8)REVERSE ( ): reverse the order of element in a list.
Ex:
l=['a', 'd', 'h', 'i', 'r', 'r', 's']
[Link]()
l
output:
['s', 'r', 'r', 'i', 'h', 'd', 'a']
Ex:
l=[123456789]
[Link]()
l
output
[]
functions of List
Function Description
Return True if all elements of the list are true (or if the list is empty).
list1=[1,2,3,4]
all()
list2=[10,11,0,14]
print(all(list1)) # True
print(all(list2)) #False
Return True if any element of the list is true. If the list is empty, return False.
any() list=[1,2,0,4]
print(any(list)
True
Return the length (the number of items) in the
len()
list. Print(len(list)) 4
Convert an iterable (tuple, string, set, dictionary) to a
print(list(t))
[1,2,3,4]
Return the largest item in the list.
max()
print(max(list)) 4
print(sorted(list))
[1,3,4,6,8]
Return the sum of all elements in the list.
sum()
print(sum(list))
22
List comprehension:
Syntax:
l =[expression,[Link]]
to find the squares up to 10
sqr=[i**2 for i in range(10)]
print(sqr)
output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
O/P:
[0, 1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
10. String
A string is a sequence of characters.
In Python, string is a sequence of Unicode character.
Python strings are "immutable" which means they cannot be changed after they are
created.
CREATING STRINGS:
Creating Strings is easy, and it is done simply by enclosing the characters in single or
double quotes.
The strings in Python consider both single and double quotes as the same.
Ex:
String_var = 'sridhar' String_var =
"sridhar" String_var = """sridhar"""
ACCESSING CHARACTERS:
Python allows to index from the zeroth position in Strings.
But it also supports negative indexes. Index of ‘-1’ represents the last character of the String.
Similarly using ‘-2’ we can access the penultimate element of the string and so on. Example:
P Y T H O N – S T R I N G
0 1 2 3 4 5 6 7 8 9 10 11 12
To retrieve a range of characters in a String we use ‘slicing operator’, the colon ‘:’. With the
slicing operator, we define the range as [a:b].
sample_str = 'Python String'
print (sample_str[3:5])
#return a range of character # ho
print (sample_str[7:])
# return all characters from index 7 # String
print (sample_str[:6])
# return all characters before index 6
# Python
print (sample_str[7:-4]) # St
1. If we try to retrieve characters at out of range index then ‘IndexError’ exception will be
raised.
Ex:
sample_str= "Python Supports Machine Learning."
print (sample_str[1024])
#index must be in range #
IndexError: string index out of range
2. String index must be of integer data type. You should not use a float or any other data type for
this purpose. Otherwise, the Python subsystem will flag a TypeError exception as it detects a
data type violation for the string index.
Ex:
sample_str = "Welcome post"
print (sample_str[1.25])
#index must be an integer
# TypeError: string indices must be integers
#t
#h
#o
#n
for Iterating Using for we can iterate var1 = 'Python'
through all the characters of for var in var1:
the String. print (var)
#P
#y
STRING METHODS
1)CAPITALZE():First letter capitalized in first word.
print([Link]())
2)SWAPAGE():converts the lower cases into upper cases and vice versa.
print([Link]())
print([Link]('a','m'))
print([Link]("chi"))
True
print([Link]("nch"))
True
6)FIND():returns the index of the first occurrence of an element.
print([Link]("h"))
print([Link]("i"))
20
print([Link]("a"))
str="sridhar 22mt1ao102"
print([Link]())
FALSE
str="sridhar4577"
print([Link]())
TRUE
str="12345"
print([Link]())
TRUE
str="6302974137"
print([Link]())
TRUE
str="sridhar"
print([Link]())
TRUE
print([Link]())
FALSE
13)UPPER():
print([Link]())
print([Link]())
False
15)LOWER()
print([Link]())
16)ISLOWER():checks the string is lower or not if it is returns true other wise false.
str="CHITHADA SRIDHAR CIVIL BRANCH"
print([Link]())
FALSE
17)JUSTIFY():
str="sridhar"
print([Link](16,"*"))
SRIDHAR*********
str="sridhar"
print([Link](16,"*"))
*********SRIDHAR
18)CENTER()
str="sridhar"
print([Link](16,"*"))
****SRIDHAR*****
print([Link]())
SRIDHAR
print([Link]())
SRIDHAR
print(".".join(str))
[[Link],[Link]]
str="sridhar"
print([Link](10))
000SRIDHAR
print([Link]("a"))
print([Link]("z"))
print([Link]("z"))
str="45.7"
print([Link]())
FALSE
24)LENGTH MAX():
25)LENGTH MIN():
str="1235"
print(min(str))
1
11. Set
Sets:
A set is an unordered collection of items. Every element is unique (no
duplicates) and must be immutable (which cannot be changed).
However, the set itself is mutable. We can add or remove items from it.
Sets can be used to perform mathematical set operations like union, intersection, symmetric
difference etc.
Creating a set:
A set is created by placing all the items (elements) inside curly braces {}, separated by comma or
by using the built-in function set().
It can have any number of items and they may be of different types (integer, float, tuple, string
etc.). But a set cannot have a mutable element, like list, set or dictionary, as its element.
set of integers
set = {1, 2, 3}
set of mixed datatypes
set = {1.0, "Hello", (1, 2, 3)}
set do not have duplicates
set = {1,2,3,4,3,2}
print(set)
o/p:{1, 2, 3, 4
# initialize a with {}
a = {}
# check data type of a
# Output: <class 'dict'>
print(type(a))
Changing a set:
Sets are mutable. But since they are unordered, indexing have no meaning.
We cannot access or change an element of set using indexing or slicing. Set does not support it.
We can add single element using the add() method and multiple elements using the update()
method. The update() method can take tuples, lists, strings or other sets as its argument. In all
cases, duplicates are avoided.
# initialize set
set = {1,3}
print(set)
add an element
Output: {1, 2, 3}
[Link](2)
print(set)
set = {1, 3, 4, 5, 6}
print(set)
discard an elemen
Output: {1, 3, 5, 6}
[Link](4)
print(set)
remove an element
Output: {1, 3, 5}
[Link](6)
print(set)
discard an element
not present in set
Output: {1, 3, 5}
[Link](2)
print(set)
Similarly, we can remove and return an item using the pop() method.
Set being unordered, there is no way of determining which item will be popped. It is
completely arbitrary.
We can also remove all items from a set using clear().
initialize my_set
Output: set of unique elements
set = set("HelloWorld")
print(set)
pop an element
Output: random element
print([Link]())
clear set
Output:set()
[Link]()
print(set)
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
Union:
print(A|B) # {1, 2, 3, 4, 5, 6, 7, 8}
print(B|A) # {1, 2, 3, 4, 5, 6, 7, 8}
[Link](B) # {1, 2, 3, 4, 5, 6, 7, 8}
[Link](A) # {1, 2, 3, 4, 5, 6, 7, 8}
Intersection:
print(A&B) #{4, 5}
print(B&) #{4, 5}
A. intersection(B) #{4, 5}
B. intersection(A) #{4, 5}
Difference:
print(A-B) # {1, 2, 3}
print(B-A) # {8, 6, 7}
A. difference(B) # {1, 2, 3}
B. difference(A) # {8, 6, 7}
Symmetric Difference:
print(A^B) # {1, 2, 3, 6, 7, 8}
print(B^A) # {1, 2, 3, 6, 7, 8}
A. symmetric_difference(B) # {1, 2, 3, 6, 7, 8}
Methods of set:
[Link] IPS ADD ICU ICU ICU
DDIFFERENCE
SSYMMETRIC DIFFERENCE
IINTERSECTION
R REMOVE
IINTERSECTION UPDATE
I IS DISJOINT
PPOP
SSYMMETRIC UPDATE
AADD
DDIFFERENCE UPDATE
DDISCARD
IIS SUBSET
CCOPY
UUNION
IIS SUPER SET
CCLEAR
UUPDATE
SET METHODS
DEFINATION:
A) A SET IS A COLLECTION OF UNORDERED ELEMENTS.
B) IT IS A MUTABLE(WE CAN ADD & REMOVE THE ELEMENTS.
C) WE REPRESENT THE SET IN CURLY BRACES { }.
D) IN SET EVERY ELEMENT IS UNIQUE(NO DUPILCATES).
E) THE SET ARE USING FOR MATHEMATICAL OPERATIONS LIKE ,
1)UNION
s1={1,2,3,4}
s2={5,6,7,8}
print(s1|s2)
{1, 2, 3, 4, 5, 6, 7, 8}
2)INTERSECTION
s1={'a','b','c','d'}
s2={'c','d','f','e'}
print(s1&s2)
{'d', 'c'}
3) DIFFERENCE
s1={1,2,3,4}
s2={4,5,6,7,8}
print(s1-s2)
{1,2,3}
4)SYMMTRICAL DIFFERANCE
s1={10,20,30,40}
s2={40,50,60,70}
print(s1^s2)
5)ADD
s1={11,13,15,16}
[Link](20)
print(s1)
[Link]()
[Link]()
print(s)
{3, 4, 5, 6, 7, 8}
7)REMOVE
s={'a','b','c','d'}
[Link]('d')
print(s)
PRINT(W)
8)DISCARD
s={70, 10, 50, 20, 60, 30}
[Link](50)
print(s)
[Link](90)
print(s)
9)COPY
s={11, 13, 15, 16, 20}
[Link]()
{16, 20, 11, 13, 15}
10)UPDATE
s={1, 2, 3, 4, 5, 6, 7, 8}
s1={'a','b','c'}
[Link](s1)
print(s)
11)IS DISJOINT
s1={1,2,3,4}
s2={4,5,6,7,8}
[Link](s2)
False
12)IS SUBSET
s1={1,2,3,4}
s2={4,5,6,7,8}
[Link](s2)
False
13)IS SUPERSET
s1={4,5,6,7,8}
s2={1,2,3,4}
[Link](s2) False
14)CLEAR
s={1, 2, 3, 4, 5, 6, 7, 8}
s1={'a','b','c','d'}
[Link]()
set()
12. Tuples
Tuple is a sequence of elements. A tuple is immutable, unlike a list in Python. By immutable,
we mean that it is not possible to update a tuple after declaring one. The elements inside a
tuple can be any Python object such a string, integer etc. Tuples are surrounded by
parenthesis.
Examples:
t1 = (1, "sridhar", 3.0)
t1
(1, 'srishar', 3.0)
type(t1)
<type 'tuple'>
Declaring a Tuple:
Empty Tuple is declared by empty parenthesis.
t2 = ()
t2 ()
type(t2)
<type 'tuple'>
It is important to note that declaring a tuple consisting a single element requires a comma after
the first element.
t3 = (1,)
t3
(1,)
type(t3)
<type 'tuple'>
If we miss out on that comma, t3 would become an integer because 1 itself is an integer.
t3 = (1)
type(t3)
<type 'int'>
t3 = ('abc')
type(t3)
<type 'str'>
If you try accessing some index that doesn’t exist, Python raises appropriate error. We can
also access elements using negative indexing.
>>> t1[-1]
3.0
>>> t1[-2]
'abc'
+ ve Index 0 1 2
Tuple=
- ve -3 -2 -1
(1, "abc", 3.0)
Index
If we try to update the element by using index, it raises an error saying that ‘tuple’ object does
not support item assignment.
However, if you add mutable elements such as a list inside a tuple, we can mutate them. For
example:
a = [1, 2]
b = [4, 5]
t = (a, b)
t
([1, 2], [4, 5])
[Link](3)
t
However, now that tuples are not mutable, we cannot update the tuple inside a tuple either.
If we really want to update a tuple, we can use that tuple to create another tuple.
t2 = (t[0], (3), t[1])
t2
((1, 2), 3, (4, 5))
Deleting a Tuple:
Since tuples are immutable, it is not possible to delete individual elements of a tuple,
however, we can delete the whole tuple itself.
del t
t #If we try to access the tuple after deleting it, python will raise an error
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 't' is not defined
Slicing a Tuple:
Tuple slicing is similar to string slicing. Using slicing we can extract out elements of any tuple. We
have to provide the starting index and the ending index i.e. tuple[start:end]
It starts from start and ends right before end. It won’t print the element at the index
end. As in the example above, we have n at the 4th index of tuple t, however, it printed
only tilla.
If the start is out of the range of the tuple, then it prints empty tuple.
t[5:7] ()
If you don’t provide start, then it will print from start till end-1 element.
t[:3]
('s', 'u', 's')
Similarly, if end is not provided, it prints till the last element of the tuple.
t[2:]
('s', 'a', 'n')
t[:]
('s', 'u', 's', 'a', 'n')
Operations on tuple:
Addition:
Using the addition operator, with two or more tuples, adds up all the elements into a new tuple. For
example,
t = (2, 5, 0) + (1, 3) + (4,)
print t
(2, 5, 0, 1, 3, 4)
Multiplication
Multiplying a tuple by any integer, x will simply create another tuple with all the elements from the
first tuple being repeated x number of times. For example, t*3 means, elements of tuple t will be
repeated 3 times.
t = (2, 5)
print t*3
(2, 5, 2, 5, 2, 5)
for name in
('sridhar','civil'):
print("Hello",name)
Output:
Hello Sridhar
Hello civil
Functions of Tuple:
len() function
As you might have already guessed, this function is used to get the number of elements inside any
tuple.
t = 1, 2, 3
print len(t) 3
cmp() function
This is used to compare two tuples. It will return either 1, 0 or -1, depending upon whether the
two tuples being compared are similar or not.
The cmp() function takes two tuples as arguments, where both of them are compared.
If T1 is the first tuple and T2 is the second tuple, then:
if T1 > T2, then cmp(T1, T2) returns 1
if T1 = T2, then cmp(T1, T2) returns 0
if T1 > T2, then cmp(T1, T2) returns -1
Methods of tuple:
Methods that add items or remove items are not available with tuple. Only the
following two methods are available.
Method Description
Count
print([Link]('p'))
Output: 2
Index
print([Link]('l'))
Output: 3
Advantages of Tuple over List
Since, tuples are quite similar to lists, both of them are used in similar situations as well.
However, there are certain advantages of implementing a tuple over a list. Below listed are some
of the main advantages:
We generally use tuple for heterogeneous (different) datatypes and list for
homogeneous (similar) datatypes.
Since tuple are immutable, iterating through tuple is faster than with list. So there is a
slight performance boost.
Tuples that contain immutable elements can be used as key for a dictionary. With list,
this is not possible.
If you have data that doesn't change, implementing it as tuple will guarantee that it
remains write-protected.
Tuple vs List:
The key difference is that tuples are immutable . This means that you cannot change the
values in a tuple once you have created it. As a list is mutable , it can't be used as a key
in a dictionary, whereas a tuple can be used.
The literal syntax of tuples is shown by parentheses ( ) whereas the literal syntax of lists
is shown by square brackets [ ] .
Tuples are heterogeneous data structures (i.e., their entries have different meanings),
while lists are homogeneous sequences.
Lists are for variable length , tuples are for fixed length .
Tuples show structure whereas lists show order
[Link]
Python dictionary is an unordered collection of items. While other compound data
types have only value as an element, a dictionary has a key: value pair.
Dictionaries are optimized to retrieve values when the key is known.
Creating Dictionary:
Creating a dictionary is as simple as placing items inside curly braces {} separated by
comma.
An item has a key and the corresponding value expressed as a pair, key: value.
While values can be of any data type and can repeat, keys must be of immutable type
(string, number or tuple with immutable elements) and must be unique.
empty dictionary
dict = {}
#dictionary with integer keys
dict = {1: 'sridhar', 2: 'civil'}
dictionary with mixed keys
dict = {'name': 'sridhar', 1: [2, 4, 3]}
using dict()
dict = dict({1:'sridhar', 2:'civil'})
from sequence having each item as a pair
dict = dict([(1,'sridhar'), (2,'civil')])
output:
sridhar2
0
update value
dict['age'] = 27
print(dict)
add item
dict['address'] ='Downtown'
print(dict)
We can remove a particular item in a dictionary by using the method pop(). This method
removes as item with the provided key and returns the value.
The method, popitem() can be used to remove and return an arbitrary item (key, value) form
the dictionary. All the items can be removed at once using the clear() method.
We can also use the del keyword to remove individual items or the entire dictionary itself.
create a dictionary
squares = {1:1, 2:4, 3:9, 4:16, 5:25}
remove a particular item
print([Link](4))
Output: 16
print(squares)
Output: {2: 4, 3: 9}
remove all items
[Link]()
print(squares)
Output: {}
PICK UP GF SVC.
P POP()
I ITEMS()
C COPY()
KKEYS()
U UPDATE()
PPOPITEM()
G GET()
FFROM KEYS()
S SET DEFAULT()
VVALUES()
CCLEAR()
1)POP
d={"name":"sridhar","rno":102,"branch":"civil"}
[Link]("rno",102)
102
2)ITEMS
d={"name":"sridhar","rno":102,"branch":"civil"}
[Link]()
dict_items([('name', 'sridhar'), ('rno', 102), ('branch', 'civil')])
3)COPY
d={"name":"sridhar","rno":102,"branch":"civil"}
[Link]()
{'name': 'sridhar', 'rno': 102, 'branch': 'civil'}
4)KEYS
d={"name":"sridhar","rno":102,"branch":"civil"}
[Link]()
dict_keys(['name', 'rno', 'branch'])
5)UPDATE
d={"name":"sridhar","rno":102,"branch":"civil"}
[Link]({"per":100})
print(d)
{'name': 'sridhar', 'rno': 102, 'branch': 'civil', 'per': 100}
6)POPITEM
d={"name":"sridhar","rno":102,"branch":"civil"}
[Link]()
('branch', 'civil')
print(d)
{'name': 'sridhar', 'rno': 102}
7)GET
d={"name":"sridhar","rno":102,"branch":"civil"}
[Link]("rno")
102
8)FROMKEYS
d={"name":"sridhar","rno":102,"branch":"civil"}
a=("x","y","z")
[Link](a,"sri")
{'x': 'sri', 'y': 'sri', 'z': 'sri'}
9)SET DEFAULT
d={"name":"sridhar","rno":102,"branch":"civil"}
[Link]("rno",100)
102
[Link]("rno")
102
print(d)
{'name': 'sridhar', 'branch': 'civil'}
[Link]("rno",100)
100
print(d)
{'name': 'sridhar', 'branch': 'civil', 'rno': 100
10)VALUES
d={"name":"sridhar","rno":102,"branch":"civil"}
[Link]()
dict_values(['sridhar', 102, 'civil'])
11)COPY
d={"name":"sridhar","rno":102,"branch":"civil"}
[Link]()
print(d)
{}
Functions of Dictionary:
9
81
25
Dictionary Comprehension:
Dictionary comprehension is an elegant and concise way to create new dictionary from
an iterable in Python.
Dictionary comprehension consists of an expression pair (key: value) followed by for
statement inside curly braces {}.
Here is an example to make a dictionary with each item being a pair of a number and
its square.
Example:
squares = {x: x*x for x in range(6)}
print(squares)
Output:
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
1)Built-in functions:
The functions which comes along with python software are known as Built-in functions or
Predefined functions.
Definition:
A function is nothing but collection of instructions for solving a particular task is
known as a function.
Advantages:
1)By using functions, we can understand the program very easily.
2)Reduce the time.
3)Solve the complex problems easily.
4)Reduce the lines of code.
def add():
a=100
b=200
return a+b
print(add())
4)+ - (with argument , without return value)
def add(a,b):
sum=a+b
print(sum)
add(100,200)
X=100
def robo(): x
print(x) 1
robo() 0
def chitti(): 0 output:100
print(x)
chitti()
Print(“Hai”)
robo()
robo()
Output:
Hai
Hai
Program:
if n == 0 or n==1:
return 1
else:
return n * factorial (n-1)
print(factorial(5))
If they are not equal, then the function return a type error.
EX: def add (x,y):
Sum=x + y
Print (sum)
Add (100,200) => 300 (values are stored in orderwise)
Add (200,400,600) => type error (does not match)
2. Default arguments:
These are the arguments for which default values are assigned during function
declaration.
These values are used, only when the values of such arguments are not provided
in the function call.
Ex: def add (x=100, y=200):
Sum=x + y (Order)
Print(sum)
add (10,20) => 30
add (10) =>10
add ( ) => 300
3. KEYWORD ARGUMENTS:
These are the arguments which can be identified by the caller of the
function using their parameter names.
It allows the caller of the function to specify only few arguments and In any
order.
EX:
Ex:
def robo (* no): (* : n number of values accept)
Print(no)
robo (10,20,30,40) => 10,20,30,40.
robo (“work”, ”dream” , ”achieve”) => work , dream , achieve.
EX:
Ex:
Ex:-
def add(a,b):
return a+b
print(add(10,20))
Example-1:
def grade(marks):
If(marks>90):
return “excellent”
elif(marks>70):
return “good”
elif(marks>60):
return “average”
else:
return “fail”
Print(grade(75))
Example-2:
print((lambda marks:"excellent" if marks>90 else ("good" if marks>70
else ("average" if marks>60 else "fail")))(75))
output:
good
Syntax:
From Functions import reduce
reduce(function name, sequence variable)
Ex:-
Sum of first 10 natural numbers
From functions import reduce
L= [1,2,3,4,5,6,7,8,9,10]
Result=reduce (Lambda x , y: x+y , l)
Print(result)