0% found this document useful (0 votes)
17 views27 pages

Class Notes Till 5th March

The document is a course outline for a Python programming class taught by Dr. Sashi Bhusan Nayak at Ravenshaw University for the academic year 2024-2025. It covers fundamental concepts of Python programming including variables, data types, operators, control statements, functions, and data structures like lists and dictionaries. The document also includes examples and exercises to practice these concepts.
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)
17 views27 pages

Class Notes Till 5th March

The document is a course outline for a Python programming class taught by Dr. Sashi Bhusan Nayak at Ravenshaw University for the academic year 2024-2025. It covers fundamental concepts of Python programming including variables, data types, operators, control statements, functions, and data structures like lists and dictionaries. The document also includes examples and exercises to practice these concepts.
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/ 27

MDC COMPUTER SCIENCE

PYTHON PROGRAMMING
by
Dr. Sashi Bhusan Nayak

RAVENSHAW UNIVERSITY, CUTTACK


2024 – 2025
TABLE OF CONTENTS
Lecture Page
Date Topic
No. No.
Language, Conputer, Science and Computer
1 29/01/2025 01 – 02
Science, Programme, Programming
Variable, Print(), Rules for constructing a
2 31/01/2025 02 – 03
variable, Datatype, Operators used in Python
3 01/02/2025 Practice -

4 03/02/2025 Type Conversion and Type Casting, String 03 – 04

5 05/02/2025 Slicing of String 04 – 05

6 07/02/2025 Slicing of String, List 05 – 06

7 08/02/2025 List, Decision control statement 06 – 08

8 10/02/2025 Loop, while loop 08 – 10

9 12/02/2025 while loop, for loop 10 – 13

10 14/02/2025 for loop 13 – 14

11 17/02/2025 for loop, while loop, Ternary Operator 14 – 15

12 19/02/2025 Function 15 – 16

13 21/02/2025 Function 16 – 17

14 22/02/2025 Function 17 – 19

15 24/02/2025 Function 19 – 21

16 28/02/2025 Tuple 21 – 23

17 05/03/2025 Dictionary 24 – 25
❖ LANGUAGE:
Language are of 3 types:
i. Man to Man
ii. Man to Machine
iii. Machine to Machine

❖ COMPUTER:
Computer is an electronic data processing and calculating device.

▪ Electronic Device: Operates by DC


▪ Electrical Device: Operates by AC

❖ SCIENCE AND COMPUTER SCIENCE:


• Systematic study of anything is Science.
• Systematic study of Computer is Computer Science.
• Artificial Intelligence means man-made knowledge.

Source/Socket ⟶ UPS ⟶ (supplies 230V AC) ⟶ SMPS (converts AC to DC) ⟶ 12V DC ⟶ CPU

❖ PROGRAMME:
A set of instruction written in a sequential order to solve any problem is called as
programme.

❖ PROGRAMMING:
• Definition: The way of writing a programme is called programming.
• Python is a programming developed by Guido Van Rossum in the year of 1989, but it
came to market in 1991. He was inspired by the British comedy series named Monte
Python's Flying Circus and wanted the language Python during a holiday break which
was fun and approachable.
• This programme is an object oriented programming used in Web Applications designing as
well as stand alone application.
1
▪ Debugging: Process of finding and fixing errors
▪ Trouble Shooting: Process of identifying and fixing problem

❖ VARIABLE:
It is the name given to the memory location in computer memory where we can store
value.

x = 5
y = 10
z = ‘Ram’
k = 3.2
m = “Ravenshaw”
t = “““RUC”””

❖ Print( ):
It is a function or method in Python used to print content of a variable or any message.
• Example: print(“Welcome to Python World”)
• Example: x=5
print(“The value of x is”,x)

❖ RULES FOR CONSTRUCTING A VARIABLE:⁸


• A variable name can be combination of alphabet, digit or any special symbol, but the first
character must be an alphabet or underscror (_).

Ex: x1 ✓
_x ✓
32x ✘

❖ DATA TYPE:
These are used to present what type of data we are going to use in our programme. So,
in Python basically the following data types are used.
i. Integers: positive and negative numbers including zero
ii. Float: decimal numbers
iii. String: A string is a sequence of characters that can include letters, numbers,
symbols and spaces. Written inside single or double or triple quote
iv. Boolean: True or False
v. None

• Example:
a=5
b=3.2
2
c=“Ram”
d=True
e=None
print(type(a))
print(type(b))
print(type(c))
print(type(d))
print(type(e))
Output
<class ‘int’>
<class ‘float’>
<class ‘str’>
<class ‘bool’>
<class ‘NoneType’>

❖ OPERATORS USED IN PYTHON:


i. Arithmetic Operator (+, -, *, /)
ii. Relational Operator (>, <, >=, <=, ==)
iii. Assignment Operator (=)
iv. Logical Operator (and, or)

• Example:
a=5
b=2
c=a/b
d=a%b
e=a**b
Print(c) # This will print the Quotient
Print(d) # This will print the Remainder
Print(e) # This will Answer print a to the power b
Output
2.5
1
25

❖ TYPE CONVERSION AND TYPE CASTING:


I. In Type Conversion, the Python interpreter automatically converts one data type to
another.
Example: x=input(“Enter your name: ”)
y=input(“Enter your age: ”)
print(“Welcome”,x) – <class ‘str'>
print(“Your age is”,y) – <class ‘str'>

3
II. In Type Casting, the programmer converts the data type as per their requirement manually.
Example: x=input(“Enter your name: ”)
y=int(input(“Enter your age: ”))
print(“Welcome”,x) – <class ‘str’>
print(“Your age is”,y) – <class ‘int’>

❖ STRING:
• It is a special datatype.
• A sequence of character is called as String.
• Example – 1:
a=“My divine life”
print(a)
o In this string, space is also considered as a character.
o A string always indexed from 0 to (n-1).
• Example – 2:
s=“India”
print(s)
a S[4]
i S[3]
d S[2]
n S[1]
I S[0]

o We can access string from its index. But we can’t modify it’s index.
o So, String is immutable.

❖ SLICING OF STRING:
• Definition: Breaking a string into small parts is called slicing of string.
• Syntax: string[start_index:End_index:Step]
• Example – 1:
str=“india” 0 1 2 3 4
print(str[1:3]) – Output: nd i n d i a
print(str[:2]) – Output: in -5 -4 -3 -2 -1
print(str[2:]) – Output: dia
Last Index = (n-1)
print(str[-4:-1]) – Output: ndi Start index missing = print from beginning
print(str[-3:]) – Output: dia Last index missing = print till end
print(str[:-2]) – Output: ind
print(str[0:5:1]) – Output: india
print(str[0:5:2]) – Output: ida
print(str[1:5:2]) – Output: ni
print(str[::-1]) – Output: aidni
print(str[::-2]) – Output: adi
print(len(str)) – Output: 5
print(str.endswith(“ia”) – Output: True
4
print(lstr.endswith(“u”) – Output: False
print(str.capitalize()) – Output: India
print(str.find(“n”) – Output: 1
print(str.count(“i”) – Output: 2
print(str.replace(“i”,”k”) – Output: kndka

• Example – 2:
str=input("Enter a name with dollar sign: ")
print(str.count("$"))
print(str.replace("$","h”)
Output
Enter a name with dollar sign: S$ub$am
2
Shubham

• Example – 3:
str=”ABCDE”
print(str[:])
print(str[:5])
print(str[:5:1])
print(str[:5:-1])
print(str[2:5])
Output
ABCDE
ABCDE
ABCDE
EDCBA
CDE

• Example – 4:
x="India is my country"
y=x.split()
print(y)
print(len(y))
Output
['India', 'is', 'my', 'country']
4

❖ LIST:
• List is a built-in datatype which is mutable.
• It allow duplicate elements and ordered (indexed) in which we can store multiple values of
different datatypes.
• List elements are enclosed between square bractet [ ] and separated by comma (,).
• Example – 1:
l=[1,3,4,9,"Ram"] # Creates a list with 5 elements
print(l) # This prints the original list
5
print(type(l)) # type(l) returns the datatype of the list
print(l[0]) # Index 0 refers to the first element of the list, which is “1”
print(l[4]) # Index 4 refers to the last element of the list, which is “Ram”
print(l[2:]) # Extracts elements from index 2 to the end
l[4]=2 # The last element “Ram” is replaced by 2

print(l)
l.append(7) # Appends 7 at the end
print(l)
l.pop() # Removes the last element
print(l)
l.pop() # Removes the last element
print(l)
l.pop(2) # Removes the element at index 2
print(l)
l.clear() # Clears all elements from the list, making it an empty list
print(l)
Output
[1, 3, 4, 9,

• Example – 2:
l=["Ram","Sita"] # Creates a list with two string elements
print(l) # This prints the list “l"
print(type(l)) # This will return the datatype of the list “l”
li=list(("Laxman","Hanuman")) # list ((“Laxman",“Hanuman")) converts a tuple
(“Laxman",“Hanuman”) into a list
print(type(li)) # type(li) confirms that li is of type list
l.extend(li) # This adds all elements of li to l
print(l) # This prints the final list of l
k=[1,2,3,4,5] # Creates another list
li.extend(k) # This adds all elements of k to li
print(li) # This prints the final list of li
Output
['Ram', 'Sita']
<class 'list'>
<class 'list'>
['Ram', 'Sita', 'Laxman', 'Hanuman']
['Ram', 'Sita', 'Laxman', 'Hanuman',1,2,3,4,5]

• Example – 3:
l=["Ram","Laxman","Sita"] # Creates a list with three elements
l.insert(3,"Hanuman") # This adds “Hanuman” at index 3
print(l)
l.pop(1) # This removes the element at index 1
print(l)
l.remove("Hanuman") # This removes “Hanuman" from the list
6
print(l)
Output
['Ram', 'Laxman', 'Sita', 'Hanuman']
['Ram', 'Sita', 'Hanuman']
['Ram', 'Sita']

❖ DECISION CONTROL STATEMENT:


• It is a control statement which control execution of program.
• It decides which statement will be executed next.
• Basically 3 types of control statements are used:
i. if
ii. ifelse
iii. elseif (Nested ifelse or ifelse ladder)
• Syntax: if (condition):
Statement
• It executes only when the condition is True. It does nothing when condition fails.
• Example – 1:
a=5
if (a>3):
print("It is a positive number")
Output
It is a positive number # The code assigns a = 5 and checks if a > 3. Since the
condition is True, it prints

• Example – 2:
a=5
if (a>5):
print("It is a positive number")
Output
(No output) # The code assigns a = 5 and checks if a > 5. Since the condition is False,
so no output is printed

• Example – 3: Programme to input 2 numbers from the keyboard and finding the
largest between them
a=int(input("Enter first number: "))
b=int(input("Enter second number: "))
if(a>b):
print("a is greater")
else:
print("b is greater")
Output - I
Enter first number: 60
Enter second number: 50
a is greater
Output – II
Enter first number: 50
7
Enter second number: 60
b is greater

• Example – 4: Programme to enter marks (out of 100) in 3 subjects to find the average.
If average is more than 80 then the student will get scholarship otherwise not.
a=int(input("Marks in Physics: "))
b=int(input("Marks in Chemistry: "))
c=int(input("Marks in Mathematics: "))
avg=(a+b+c)/3
if (avg>80):
print("Congratulations you got scholarship")
else:
print("Better luck next time")
Output - I
Marks in Physics: 95
Marks in Chemistry: 92
Marks in Mathematics: 94
Congratulations you got scholarship
Output – II
Marks in Physics: 78
Marks in Chemistry: 80
Marks in Mathematics: 74
Better luck next time

• Example – 5: Programme to enter a year and check whether it is a leap year or not.
a=int(input("Enter any year: "))
b=a%4
if (b==0):
print(a,"is a leap year")
else:
print(a,"is not a leap year")
Output - I
Enter any year: 2024
2024 is a leap year
Output – II
Enter any year: 2025
2025 is not a leap year

❖ LOOP:
• When we want to execute a single statement or group pf statements repeatedly in a
programme then we use loop.
• Basicall 3 types of loop are used:
i. while
ii. for
iii. do while

8
➢ while loop:
• It is a pre-test loop.
• It executes only when the condition is true.
• Syntax: initialization of loop counter
while(condition)
body of the loop
updation of loop counter
• Example – 1:
i=1
while i<10:
print(i)
i=i+1
Output
1
2
3
4
5
6
7
8
9

• Example – 2:
i=1
while i<5:
print("Ravenshaw University")
i=i+1
Output
Ravenshaw University
Ravenshaw University
Ravenshaw University
Ravenshaw University

• Example – 3:
i=1
while i<=10:
print("3","×",i,"=",3*i)
i=i+1
Output
3 × 1 = 3
3 × 2 = 6
3 × 3 = 9
3 × 4 = 12
3 × 5 = 15
3 × 6 = 18
3 × 7 = 21
9
3 × 8 = 24
3 × 9 = 27
3 × 10 = 30

• Example – 4:
num=int(input("Enter a number: "))
i=1
while i<=10:
print(num,"×",i,"=",num*i)
i=i+1
Output
Enter a number: 5
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

• Example – 5: Programme to enter a number and finding its factor


n=int(input("Enter a number: "))
f=1
while f<n:
if n%f==0:
print(f)
f=f+1
Output
Enter a number: 8
1
2
4

• Note:
o in is a membership operator
o It's result always yield as True or False

• Example – 6:
x=["Ram","Laxman","Hanuman"]
print(type(x))
print("Ram" in x) # Checks if “Ram” is present in the list x. Since it present it will print
True
i=0
while i<len(x): # len(x) will return 3, so the loop runs from i = 0 to 2
print(x[i]) # It will print all elements of the list
10
i=i+1
Output:
<class 'list'>
True
Ram
Laxman
Hanuman

• Example – 7:
n=int(input("Enter a number: "))
f=1
while f<=n:
f=f*n
f=f+1
print(f)
Output:
Enter a number: 9
10

• Example – 8: To find the factorial of a number


n=int(input("Enter a number: ")) # Takes an integer input from the user
f=1 # Initializes factorial variable with 1
while n>=1: # Runs the loop until n becomes 0
f=f*n # Multiplies ‘f’ by ‘n’
n=n-1 # Decreases ‘n' by 1
print(f) # Print ‘f' after each multiplication. The last printed value is the actual
factorial
Output:
Enter a number: 4
4
12
24
24

• Example – 9: To find the factorial of a number


n=int(input("Enter a number: ")) # Takes an integer input from the user
f=1 # Loop counter starts from 1
fact=1 # Variable to store factorial
while f<=n: # Runs the loop from f = 1 to n
fact=fact*f # Multiplies fact by f (calculates factorial)
f=f+1 # Increments f by 1
print(fact) # Prints factorial at each step
print(fact) # Prints final factorial value
Output:
Enter a number: 4
1
2

11
6
24
24

➢ for loop:
• Syntax: for variable in range (start_index, last_index,
incremented/decremented)
• Example – 1:
for i in range (1,10,2):
print(i)
Output
1
3
5
7
9

• Example – 2:
for i in range (10,0,-1):
print(i)
Output:
10
9
8
7
6
5
4
3
2
1

• Example – 3:
x=["Ram","Kiwi","Apple"]
for i in range(0,len(x)):
print(x[i])
Output
Ram
Kiwi
Apple

• Example – 4:
x=int(input("Enter a Number: "))
i=1
for i in range(i,x):
if x%i==0:
print(i)
Output
Enter a Number: 6
12
1
2
3

• Example – 5: Creating and Appending User Input to a list


n = int(input("Enter length of list: ")) # User inputs the number of
elements in the list
l = [] # Initializes an empty list
for i in range(n): # Loops 'n' times to take user inputs
list = int(input("Enter elements into list: ")) # Takes an integer
input
l.append(list) # Appends the input to the list
print(l) # Prints the list after each addition
• Output
Enter length of list: 4
Enter elements into list: 5
[5]
Enter elements into list: 6
[5, 6]
Enter elements into list: 7
[5, 6, 7]
Enter elements into list: 8
[5, 6, 7, 8]

• Example – 6: Using a Loop with a break Statement


for i in range(1, 10): # Loops from 1 to 9
print(i) # Prints the current value of i
if i == 4: # Checks if i is equal to 4
break # Exits the loop immediately
print(i) # This line is unreachable due to 'break'
Output
1
2
3
4

• Example – 7: To skip a specific value in a loop using continue


for i in range(1, 10): # Loops from 1 to 9
if i == 4: # Checks if i is equal to 4
continue # Skips the rest of the loop for this step
print(i) # Prints i (except when i == 4)
Output
1
2
3
5

13
6
7
8
9

• Example – 8: To find the factorial of a Number


n=int(input("Enter the number: "))
fact=1
i=1
for f in range(i,n+1):
fact=fact*f
print(fact)
Output
Enter the number: 4
24

• Example – 9: To find the factorial of a Number


n=int(input("Enter a number: "))
f=1
for i in range (1,n+1):
f=f*i
print(f)
Output
Enter a number: 5
1
2
6
24
120

❖ TERNARY OPERATOR:
• A ternary operator (also called a conditional expression) is a one-liner that replaces an
if-else statement to assign values based on a condition.
• It is a compact way to write simple conditional statements.
• Syntax: <variable> = <true value> if <condition> else <false value>
• Example – 1:
a=5
b=10
max=a if a>b else b
print(max)
Output:
10

• Example – 2:
a=5
b=10

14
c=15
max=a if a>b and a>c else b if b>c else c
print(max)
Output
15

❖ FUNCTION:
• Definition: A self contained block of statements which proceed independently is called as
function.
• Function is of 2 types:
i. Built-in or Pre-defined function
Ex: input()
print()
len()
ii. User defined function
Ex: Created by user using a keyword
• Function executes only when it is called.
• Why Function?
o It reduces the code.
o It helps in code reusability.
• Syntax: def name_of_function(): # Function definition
Body of Programme
name_of_function # Function call
• The name of the function is called as function definition.
• We can define a function using a keyword ‘def’.
• Function definition contains the actual calculation and the body of the programme.
• A function definition executes only when it is called.
• A function call has the same name as the function definition.
• At the time of function call, the function definition is executed.

➢ Function without Argument:


• If there is no argument passes in a function then it is called as function argument.
• A function may or may not have argument.
• Example – 1:
def f():
print("Welcome to Python World")
f()
f()
f()
Output
Welcome to Python World
Welcome to Python World
Welcome to Python World

• Example – 2:
def f(name):
15
print("Welcome to Python World",name)
print("How do you do?")
f("Shubham")
Output
Welcome to Python World Shubham
How do you do?

• Example – 3:
def add():
x=5
y=10
z=x+y
print(z)
a=21
b=23
c=a+b
print(c)
add()
add()
Output
15
44
15
44

• Example – 4(a): Programme to calculate the sum and difference of two numbers
using function (without parameters)
def add():
a=5
b=10
c=a+b
print(c)
add() # Calling the add() function
def sub():
a=5
b=10
d=a-b
print(d)
sub() # Calling the sub() function
Output
15
-5

• Example – 4(b): Programme to calculate the sum and difference of two numbers
using function (with parameters)
def add(a,b): # Function definition with two parameters
c=a+b # Adds a and b

16
print(c) # Prints the result
a=5 # Assigns 5 to variable a
b=10 # Assigns 10 to variable b
add(a,b) # Calls the add() function with arguments (5,10)
def sub(a,b): # Function definition with two parameters
d=a-b # Subtracts b from a
print(d) # Prints the result
a=5 # Assigns 5 to variable a
b=10 # Assigns 10 to variable b
sub(a, b) # Calls the sub() function with arguments (5,10)
Output
15
-5

• Example – 5(a): Programme to calculate the area of a circle using function (without
parameters)
def area_of_circle():
r=2
area=3.14*r**2
print("The area of circle is",area)
area_of_circle()
Output
The area of circle is 12.56

• Example – 5(b): Programme to calculate the area of a circle (with parameters)


def area_of_circle(r):
area=3.14*r**2
print("The area of circle is",area)
r=3
area_of_circle(r)
Output
The area of circle is 28.26

• Example – 6(a): Program to Generate Fibonacci Series Up to a Given Number


The Fibonacci Series is a sequence where each number is the sum of the two
preceding ones, starting from 0 and 1.
e.g. 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...
0+1=1
1+1=2
1+2=3
2+3=5
3 + 5 = 8, and so on

n=int(input("Enter the series up to which do you want: ")) # User


inputs the number of terms
a=0 # First term of the Fibonacci series

17
b=1 # Second term of the Fibonacci series
c=0 # Variable to store the next term
print("a =", a, "b =", b) # Printing the first two terms (0 and 1)
for i in range(2, n): # Loop starts from index 2 (as 0 and 1 are already printed)
c=a+b # The next term is the sum of the previous two terms
print(c) # Printing the next term
a=b # Updating 'a' to the previous 'b'
b=c # Updating 'b' to the newly calculated 'c'
Output
Enter the series up to which you want: 6
a = 0 b = 1
1
2
3
5

• Example – 6(b): Program to Generate Fibonacci Series Up to a Given Number using


function
def fab(): # Defines a function fab() to generate the Fabonacci series
n=int(input("Enter the series up to which you want: "))
a=0
b=1
c=0
print("a =",a,"b =",b)
for i in range(2,n):
c=a+b
print(c)
a=b
b=c
fab() # Calls the function to execute
Output
Enter the series up to which you want: 7
a = 0 b = 1
1
2
3
5
8

• Example – 7(a): Programme to print pattern


n = 10 # Number of rows in the pattern
for i in range(0,n): # Inner loop for printing 'i' in each row
for j in range(0, i):
print(i,end=" ") # Print 'i' with a space, staying on the same line
print("") # Move to the next line after printing a row
Output
1
18
2 2
3 3 3
4 4 4 4
5 5 5 5 5
6 6 6 6 6 6
7 7 7 7 7 7 7
8 8 8 8 8 8 8 8
9 9 9 9 9 9 9 9 9

• Example – 7(b): Programme to Print pattern of increasing numbers


n = 10 # Number of rows in the pattern
for i in range(0,n): # Inner loop for printing 'i' in each row
for j in range(0, i):
print(j,end=" ") # Print 'j' with a space, staying on the same line
print("") # Move to the next line after printing a row
Output
0
0 1
0 1 2
0 1 2 3
0 1 2 3 4
0 1 2 3 4 5
0 1 2 3 4 5 6
0 1 2 3 4 5 6 7
0 1 2 3 4 5 6 7 8

• Example – 8: Programme to Check the pH of a solution using function


def pH():
pH=float(input("Enter the pH of solution: "))
if pH<7:
print("The solution is acidic")
elif pH>7:
print("The solution is basic")
else:
print("The solution is neutral")
pH()
pH()
pH()
Output
Enter the pH of solution: 4
The solution is acidic
Enter the pH of solution: 9
The solution is basic
Enter the pH of solution: 7
The solution is neutral

19
• Example – 9: Programme to Swap two integers, floats and strings
def swap(a,b):
a,b=b,a
print("After Swapping: a =",a, "b =",b)
# Swapping Integers
x,y=5,10
print("Before Swapping: x =",x, "y =",y)
swap(x,y)
# Swapping Floats
p,q=3.5,7.8
print("Before Swapping: p =",p,"q =",q)
swap(p,q)
# Swapping Strings
str1,str2="Ram","Sita"
print("Before Swapping: str1 =",str1,"str2 =",str2)
swap(str1,str2)
Output
Before Swapping: x = 5 y = 10
After Swapping: a = 10 b = 5
Before Swapping: p = 3.5 q = 7.8
After Swapping: a = 7.8 b = 3.5
Before Swapping: str1 = Ram str2 = Sita
After Swapping: a = Sita b = Ram

➢ Function with and without return type:

Function without return type Function with return type


Example – 1: Example – 1:
def area(l,b): def area(l,b):
ar=l*b return l*b
print(ar) a=area(5,10)
area(5,20) print(a)
Output Output
100 50

Example – 2:
def area(l,b):
ar=l*b
return ar
a=area(5,2)
print(a)
Output
10

• Note:
o The return statement immediately exits the function.
o Anything written after return will not execute.

20
o Example:
def f(n):
print("Welcome to Python World",n)
return
print("How do you do?",n)
f("Shubham")
Output
Welcome to Python World Shubham

➢ Lambda Function:
• It is an anonymous function.
• As it has no name, it is called as anonymous function.
• Basically this function is used to do some small calculations with single line.
• It reduces the code.
• Limitation: In lambda function, any numbers of arguments can be passed but it must
contain atmost one expression only.
• Example – 1:
f=lambda a:a*a
r=f(5)
print(r)
Output
25

• Example – 2:
f=lambda a,b:a+b
k=f(10,20)
print(k)
Output
30

❖ TUPLE:
• Definition: It is a built-in datatype which is immutable, ordered and allow duplicate
elements.
• Example – 1:
x=(1,13,3,4,15,6)
y=("Ram",1,"Shyam",5)
print(x)
print(y)
print(type(x))
print(type(y))
Output
(1, 13, 3, 4, 15, 6)
('Ram', 1, 'Shyam', 5)
<class 'tuple'>
<class 'tuple'>
21
• Packing: Assigning values to tuple variables is called as packing.
• Unpacking: Retriving back values to variables is calles as unpacking.
• Example – 2(a):
x=("Apple","Banana","Kiwi","Mango","Coconut") # Creating a tuple with 5 fruit
names
(Red,Yellow,*Green)=x # Unpacking the tuple into variables
print(Red) # 'Red' gets the first element "Apple"
print(Yellow) # 'Yellow' gets the second element "Banana"
print(Green) # '*Green' stores the remaining elements as a list ["Kiwi", "Mango",
"Coconut"]
Output
Apple
Banana
['Kiwi', 'Mango', 'Coconut']

• Example – 2(b):
x=("Apple","Banana","Kiwi","Mango","Coconut") # Creating a tuple with 5 fruit
names
(Red,Yellow,Green,Orange,White)=x # Unpacking all elements of the tuple into
separate variables
print(Red) # 'Red' gets the first element "Apple"
print(Yellow) # 'Yellow' gets the second element "Banana"
print(White) # 'White' gets the last element "Coconut"
Output
Apple
Banana
Coconut

• Example – 2(c):
x=("Apple","Banana","Kiwi","Mango","Coconut") # Creating a tuple with 5 fruit
names
(Red,*Yellow,White)=x # Unpacking the tuple into variables
print(Red) # 'Red' gets the first element "Apple"
print(Yellow) # '*Yellow' stores the middle elements as a list ["Banana", "Kiwi",
"Mango"]
print(White) # 'White' gets the last element "Coconut"
Output
Apple
['Banana', 'Kiwi', 'Mango']
Coconut

• Example – 3: Printing single element in a tuple


x=("Apple",)
print(x)
print(type(x))

22
Output
('Apple',)
<class 'tuple'>

• Note:
o The comma (,) is necessary when defining a single-element tuple; otherwise, Python
treats it as a string or normal variable.
o ("Apple",) is a tuple, but ("Apple") is just a string
o Example:
x=("Apple",)
y=("Apple")
print(x)
print(type(x))
print(y)
print(type(y))
Output
('Apple',)
<class 'tuple'>
Apple
<class 'str'>

• Example – 4: Converting a Tuple to a List for Modification


x=("Ram","Laxman","Hanuman") # Creating a tuple with three elements
y=list(x) # Converting the tuple into a list to allow modification
y[1]="India" # Changing the second element ("Laxman") to "India"
x=tuple(y) # Converting the list back into a tuple
print(x) # Printing the modified tuple
Output
('Ram', 'India', 'Hanuman')

Note: Since tuples are immutable, they can be modified indirectly by converting them into a
list, making changes and then converting them back into a tuple.

• Example – 5: Adding an Element to a Tuple


x=("Ram","Laxman","Hanuman") # Creating a tuple with three elements
y=list(x) # Converting the tuple into a list to allow modification
y.append("Sita") # Adding a new element "Sita" to the list
x=tuple(y) # Converting the modified list back into a tuple
print(x) # Printing the updated tuple
Output
('Ram', 'Laxman', 'Hanuman', 'Sita')

Note: Since tuples are immutable, they can be modified indirectly by converting them into a
list, adding elements using .append(), and then converting them back into a tuple.

23
❖ DICTIONARY:
• Definition: It is a built-in datatype which is mutable, unordered and don’t allow duplicate
elements.
• In dictionary a pair of key and its value are stored.
• Example – 1:
d={"Name":"Ram","Age":21,"Address":"India"} # Creating a dictionary d with
key-value pairs
print(d) # printing the dictionary d
print(type(d)) # Printing the type of the variable 'd'
Output
{'Name': 'Ram', 'Age': 21, 'Address': 'India'}
<class 'dict'>

• Example – 2: Printing Dictionary Items, Keys and Values


d={"Name":"Ram","Age":21,"Address":"India"} # Creating a dictionary with
key-value pairs
print(d)
x=d.items() # Getting all key-value pairs as a list of tuples
print(x)
x=d.keys() # Getting all keys from the dictionary
print(x)
x=d.values() # Getting all values from the dictionary
print(x)
Output
{'Name': 'Ram', 'Age': 21, 'Address': 'India'}
dict_items([('Name', 'Ram'), ('Age', 21), ('Address', 'India')])
dict_keys(['Name', 'Age', 'Address'])
dict_values(['Ram', 21, 'India'])

• Example – 3: Handling Duplicate Keys in a Dictionary


d={"Name":"Ram","Age":21,"Address":"India","Address":"Odisha"}
# Creating a dictionary with duplicate keys
print(d)
Output
{'Name': 'Ram', 'Age': 21, 'Address': 'Odisha'}

Note: Dictionaries do not allow duplicate keys; if a key is repeated, the latest value
overwrites the previous one.

• Example – 4: Adding and Updating Dictionary Elements


d={"Name":"Ram","Age":21,"Address":"Odisha"} # Creating a dictionary with
initial key-value pairs
d["Salary"]=21000 # Adding a new key-value pair
print(d)
d.update({"Salary":"3 Lakhs"}) # Updating the value of "Salary"
print(d)

24
Output
{'Name': 'Ram', 'Age': 21, 'Address': 'Odisha', 'Salary': 21000}
{'Name': 'Ram', 'Age': 21, 'Address': 'Odisha', 'Salary': '3
Lakhs'}

• Example – 5: Creating a Dictionary with User Input


d={} # Initializing an empty dictionary
n=int(input("Enter how many key-value pairs do you want: ")) # Taking
user input for the number of key-value pairs
for x in range(n): # Loop to take key-value input and add to the dictionary
Key=input("Enter Key: ")
Value=input("Enter Value: ")
d[Key]=Value # Adding key-value pair to the dictionary
print(d) # Printing the updated dictionary after each entry
Output
Enter how many key-value pairs do you want: 2
Enter Key: Subject
Enter Value: Computer Science
{'Subject': 'Computer Science'}
Enter Key: Topic
Enter Value: Python Programming
{'Subject': 'Computer Science', 'Topic': 'Python Programming'}

• Example – 6: Dictionary with a List as a Value


d={"Name":"Ram","Marks":[76,84,93]} # Creating a dictionary with a list as a
value
print(d) # Printing the dictionary
Output
{'Name': 'Ram', 'Marks': [76, 84, 93]}

25

You might also like