0% found this document useful (0 votes)
30 views

Python Unit-3

Uploaded by

itsmemahi2003
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views

Python Unit-3

Uploaded by

itsmemahi2003
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

PYTHON PROGRAMMING BCA - 3001

UNIT - 3
{FUNCTION AND DICTIONARY}

Why Do We Need Function?


Functions are the building blocks for developing large programs or applications. Hence they
are very useful for fulfilling such kind of purpose.

Some unavoidable reasons that forces to apply function while developing a large
program or software.

1. Customized or user-defined function allows you to write a block of code once and use
it multiple times. You only need to write and debug the code once. This avoids the
repetition of that common code and hence also saves your lots of time.

2. Writing user-defined function can make your code easier to read and understandable.

3. It is very easier to test and debug a large program or software, if we are using the
idea of customized/user-defined function.

4. Implementing user-defined function also gives the better idea of reusability of


common code while creating a large program or software. This is done simply to put some
commonly or repeatedly task together and make a function so that instead writing the
same code again and again for different inputs, we can just call a function to reuse that
common code contained in function over and over.

5. Function manages the inputs and outputs in computer programs. Python programming
language is designed to work on large scale of data and idea of function is an effective
way to manage and transform such huge amount of data.

Types of Functions:
A function is broadly classified into two major categories.
1. Standard Library (Inbuilt/Pre-defined/Readymade) Functions
2. Customized/ User-defined Functions

1. Standard Library Functions:


Python has a large library of standard pre-defined functions. Such inbuilt functions are
used as per the demand of program. Hence we don’t need to create or define such a
function rather we just use it for fulfilling the purpose of our program.
Such readymade functions are print(), int(), eval(), input(), max(), min(), sum(), count()
etc.

2. User–Defined Functions:
In Python, user-defined function is a self-contained block or group of related
statements/instructions that performs a specific task.
Function provides the idea of high degree of reusability of common code.

1
PYTHON PROGRAMMING BCA - 3001

Such kind of function is required as per the demands of our program. Use of such kind of
function avoids the repetition of same code and utilizes the idea of reusability of that
same code wherever applicable in our program.

Major Aspects While Implementing User–defined Function:


There are two major aspects while using such kind of a function.
(a) Function Definition
(b) Function Call

(a) Function Definition:


A function definition contains self-contained block of one or more statements/instructions that
performs a specific task when it is called. This means that the function definition has the
main logic of the task that it will execute if that will be called.

The general structure of function definition is given as follows:

Keyword Formal Parameters

def Function_Name(List_of_Parameters): Function Header


Statement1
Statement2
Statement3
------------- Function Body / Self-Contained Block
-------------
StatementN

(b) Function Call:


A function definition will always be executed whenever it will be called.
The general syntax of function call is given as follows:

Function_Name(List_of_Parameters) Function Call

Actual Parameters

How Does User-defined Function Work?

Formal Parameters

def Function_Name(List_of_Parameters):

Statement1
Statement2
Statement3
------------- Function Body
-------------
StatementN

Function_Name(List_of_Parameters) Function Call


Statement(s)
Actual Parameters

2
PYTHON PROGRAMMING BCA - 3001

Example: Write a program that prints a message “WELCOME TO THE WORLD OF PYTHON
PROGRAMMING” through user-defined function.

CASE-1:
def display():
print(“DEAR ALOK, WELCOME TO THE WORLD OF PYTHON PROGRAMMING.”)

display() # Call Function

OUTPUT: DEAR ALOK, WELCOME TO THE WORLD OF PYTHON PROGRAMMING.

CASE-2:
def display():
str1 = input(“PLEASE ENTER YOUR NAME: ”)
print(“DEAR”, str1, “,”, “WELCOME TO THE WORLD OF PYTHON PROGRAMMING.”)

display() # Call Function

OUTPUT:
PLEASE ENTER YOUR NAME: ALOK
DEAR ALOK, WELCOME TO THE WORLD OF PYTHON PROGRAMMING.

CASE-3:
def display(str2):
str1 = input(“PLEASE ENTER YOUR NAME: ”)
print(“DEAR”, str1,”,”, str2)

msg = input(“PLEASE ENTER THE MESSAGE THAT YOU WANT: ”)


display(msg) # Call Function

OUTPUT:
PLEASE ENTER THE MESSAGE THAT YOU WANT: WELCOME TO THE WORLD OF PYTHON PROGRAMMING.
PLEASE ENTER YOUR NAME: ALOK
DEAR ALOK, WELCOME TO THE WORLD OF PYTHON PROGRAMMING.

USE OF CUSTOMIZED/USER-DEFINED FUNCTION:


Suppose that you want to find the sum of numbers starting from 1 to 25, 50 to 75, 90 to 100
and 125 to 140.

CASE-1: WITHOUT USING FUNCTION


sum = 0
for i in range(1, 26):
sum = sum + i
print(“SUM OF NUMBERS FROM 1 TO 25 = ”, sum)

sum = 0
for i in range(50, 76):
sum = sum + i

3
PYTHON PROGRAMMING BCA - 3001

print(“SUM OF NUMBERS FROM 50 TO 75 = ”, sum)

sum = 0
for i in range(90, 101):
sum = sum + i
print(“SUM OF NUMBERS FROM 90 TO 100 = ”, sum)

sum = 0
for i in range(125, 141):
sum = sum + i
print(“SUM OF NUMBERS FROM 125 TO 140 = ”, sum)

OUTPUT:
SUM OF NUMBERS FROM 1 TO 25 = 325
SUM OF NUMBERS FROM 50 TO 75 = 1625
SUM OF NUMBERS FROM 90 TO 100 = 1045
SUM OF NUMBERS FROM 125 TO 140 =

CASE-2: USING WITH FUNCTION


By observing the above code, we can say that it would be better if we could simply write
this common code once and then use it repeatedly. And this can be accomplished by
defining function once and using it repeatedly by calling over and over.

def sum(x, y): # Function Header


sum = 0
for i in range(x, y+1):
sum = sum + I #Function Definition/Body
print(“SUM OF NUMBERS FROM ”, x, “TO”, y, “ = ”, sum)

sum(1, 25) # Function Call1


sum(50, 75) # Function Call2
sum(90, 100) # Function Call3
sum(125, 140) # Function Call4

OUTPUT:
SUM OF NUMBERS FROM 1 TO 25 = 325
SUM OF NUMBERS FROM 50 TO 75 = 1625
SUM OF NUMBERS FROM 90 TO 100 = 1045
SUM OF NUMBERS FROM 125 TO 140 =

Actual Parameters Versus Formal Parameters:


The parameters which are actually provided by the program, for passing to the function call,
are called as the actual parameters.

The parameters passing in function definition, which have the responsibility to accept values
coming from actual parameters are called as formal parameters.

The return Statement:


This statement is specially used when something is required to be returned by function
definition to function call. For such a purpose, we use return statement.

4
PYTHON PROGRAMMING BCA - 3001

Tip: The return statement without a value is equivalent to return ‘None’. Where ‘None’ is a
special type in Python that represents nothingness.

Returning Single Value From Function Definition To Function Call


Example-1: To Print The Absolute Value of An Integer Number
CASE-1:
def Absolute_Value(num):
if(num>=0):
return num # Returning Absolute Value of ‘num’ To Function Call
else:
return –num # Returning Absolute Value of ‘-num’ To Function Call
print(“ABSOLUTE VALUE = ”, Absolute_Value(2))
print((“ABSOLUTE VALUE = ”, Absolute_Value(-4))

CASE-2:
def Absolute_Value(num):
if(num>=0):
return num
else:
return –num
n1 = int(input(“PLEASE ENTER AN INTEGER NUMBER: ”))
n2 = int(input(“PLEASE ENTER AN INTEGER NUMBER: ”))
print(“ABSOLUTE VALUE = ”, Absolute_Value(n1))
print((“ABSOLUTE VALUE = ”, Absolute_Value(-n2))

Example-2: To Find And Print The Maximum And Minimum Value Between Two Numbers
CASE-1:
def Max_Value(a, b):
if(a>b):
return a
elif(b>a):
return b
else:
print(a, “ AND ”, b, “ ARE EQUAL”, )
x = int(input(“PLEASE ENTER FIRST NUMBER: ”))
y = int(input(“PLEASE ENTER SECOND NUMBER: ”))

print(“THE MAXIMUM VALUE = ”, Max_Value(x, y))

CASE-2:
def Min_Value(a, b):
if(a<b):
return a # Returning Minimum Value ‘a’ if a is less than b
elif(b<a):
return b # Returning Minimum Value ‘b’ if b is less than a
else:
print(a, “ AND ”, b, “ ARE EQUAL”, )
x = int(input(“PLEASE ENTER FIRST NUMBER: ”))
y = int(input(“PLEASE ENTER SECOND NUMBER: ”))

print(“THE MINIMUM VALUE = ”, Min_Value(x, y))

5
PYTHON PROGRAMMING BCA - 3001

Example-3: To Compute And Print The Factorial Value of A Positive Number Input By User
def Cal_Facto(n):
if(n == 0):
return 1
elif(n < 0):
return n
else:
f=1
for i in range(1, n+1):
f = f*i
return f # Returning The Calculated Factorial Value ‘f’ To The Function Call

num = int(input(“PLEASE ENTER A POSITIVE NUMBER: ”))


print(“THE FACTORIAL VALUE OF ”, num, “ = ”, Cal_Facto(num))# Printing Factorial Value ‘f’
# By Calling The Function
OUTPUT:
PLEASE ENTER A POSITIVE NUMBER: 5
THE FACTORIAL VALUE OF 5 = 120

Returning Multiple Value From Function Definition To Function Call


Example-1:
def Max_Min_Values(a, b):
if(a>b):
max = a
min = b
return max, min # Returning Multiple Values ‘max’ And ‘min’ To Function Call
if(a == b)
print(a, “ AND ”, b, “ BOTH ARE EQUAL”, )

x = int(input(“PLEASE ENTER FIRST NUMBER: ”))


y = int(input(“PLEASE ENTER SECOND NUMBER: ”))

max, min = Max_Min_Values(x, y) # Function Call


print(“THE MAXIMUM VALUE = ”, max, “\n”, “THE MINIMUM VALUE = ”, min)

Example-2:
def Compute(n):
return n*n, n*n*n # Returning Multiple Values n*n, n*n*n To Function Call

num = int(input(“PLEASE ENTER A POSITIVE INTEGER NUMBER: ”))


square, cube = Compute(num) # Function Call
print(“THE SQUARE OF ”, num, “ = ”, square, “\n”, “THE CUBE OF “, num, “ = ”, cube)

Example-3:
def Arithmetic_Compute(x, y): # Function Header
return x+y, x-y, x*y, x/y, x%y # Returning Multiple Values To Function Call

a = int(input(“PLEASE ENTER FIRST NUMBER: ”))


b = int(input(“PLEASE ENTER SECOND NUMBER: ”))

add, sub, mul, div, remain = Arithmetic_Compute(a, b) # Function Call

6
PYTHON PROGRAMMING BCA - 3001

print(“The Addition of ”, a, “ And ”, b, “ = ”, add)


print(“The Subtraction of ”, a, “ And ”, b, “ = ”, sub)
print(“The Multiplication of ”, a, “ And ”, b, “ = ”, mul)
print(“The Division of ”, a, “ And ”, b, “ = ”, div)
print(“The Remainder of ”, a, “ And ”, b, “ = ”, remain)

Local And Global Scope of A Variable:


A variable once defined and used within function definition/function body, is to be known as
local variable. Such kind of a variable cannot be accessed from outside of function
definition. This means that such kind of a variable has a local scope to that function
definition where it is defined and accessed.

Example:
def sum(x, y):
add = x + y # WHERE ‘add’ IS A LOCAL VARIABLE
return add
print(“THE SUM OF TWO NUMBERS = ”, sum(10, 20))

A variable once defined outside of a function definition/function body, is to be known as


global variable. Such kind of a variable can be frequently accessed throughout the whole
program. This means that such kind of a variable has a global scope to the whole program
and can be accessed anywhere in the program.

Example-1:
def sum(x, y):
add = x + y # WHERE ‘add’ IS A LOCAL VARIABLE
return add

a = int(input(“PLEASE ENTER FIRST NUMBER: ”)) # WHERE ‘a’ IS A GLOBAL VARIABLE


b = int(input(“PLEASE ENTER SECOND NUMBER: ”)) # WHERE ‘b’ IS A GLOBAL VARIABLE

print(“THE SUM OF TWO NUMBERS = ”, sum(a, b))

Example-2:
def fun1():
x = 10 # WHERE ‘x’ IS A LOCAL VARIABLE
print(“VALUE OF ‘x’ INSIDE FUNCTION = ”, x)

x = 20 # Global Variable
fun1() # Function Call
print(“VALUE OF ‘x’ OUTSIDE THE FUNCTION = ”, x)

OUTPUT:
VALUE OF ‘x’ INSIDE FUNCTION = 10
VALUE OF ‘x’ OUTSIDE THE FUNCTION = 20

Local Variables Cannot Be Used In Global Scope:


The scope of local variable is limited to the function where it is created and also be used
only within that function.

7
PYTHON PROGRAMMING BCA - 3001

Example: Consider the following code snippet clarifying the scope of local variable
def Local_Scope():
q = 10 # Local Variable
print(“THE VALUE OF LOCAL VARIABLE q = ”, q)

Local_Scope() # Function Call

# Accessing Local Variable q Outside of The Function Definition of Local_Scope()


print(“THE VALUE OF LOCAL VARIABLE q = ”, q) # Showing Error

OUTPUT:
THE VALUE OF LOCAL VARIABLE q = 10

NameError: name ‘q’ is not defined

Reading Global Variable From Local Scope:


We know that a variable declared as global can be used frequently from a local scope and
also be used anywhere in the current program.

Example:
def Sample():
print(s) # Using Global Variable ‘s’ In The Local Scope of The Function Sample()

s = “WELCOME TO THE GLOBAL MARKET OF PYTHON AND R - PROGRAMMING”


Sample() # Function Call

OUTPUT: WELCOME TO THE GLOBAL MARKET OF PYTHON AND R - PROGRAMMING

Local And Global Variable With The Same Name:


Let us have a look on a situation when local and global variables are of same name.

Example:
def Sample();
s=“Don’t Underestimate The Commercial Market of JAVA” # Local Variable Named As ‘s’
print(s)

s = “JAVA IS STILL ALIVE…..” # Global Variable Also Named As ‘s’


Sample() # Function Call
print(s)

OUTPUT:
Don’t Underestimate The Commercial Market of JAVA
JAVA IS STILL ALIVE…..

Use of global Statement:


Consider a situation when a programmer needs to modify the value of global variable within
a function definition. To fulfil the purpose for such a demanding situation, a global statement
is required to be used.

8
PYTHON PROGRAMMING BCA - 3001

Example: The Above Said Situational Problem Is Following As:


a = 20
def display():
a = 30 # Local Variable
print(“THE VALUE OF ‘a’ INSIDE THIS FUNCTION = ”,a)

display() # Function Call


print(“THE VALUE OF ‘a’ OUTSIDE OF THIS FUNCTION = ”, a)

OUTPUT:
THE VALUE OF ‘a’ INSIDE THIS FUNCTION = 30
THE VALUE OF ‘a’ OUTSIDE OF THIS FUNCTION = 20

CLARIFICATION:
In the above program, we have assigned value 20 to the global variable ‘a’ defined outside of
the function definition display(). Suppose a programmer uses the same variable name ‘a’
inside the function definition but now he/she wants to modify the actual value of global
variable ‘a’ through changing the value of local variable ‘a’ inside the function definition
display(). But how will you do that?

Use of global Statement As A Remedial Solution To That Situational Problem


a = 20
def display():
global a # Local Variable ‘a’ is now globalized
a = 30
print(“THE VALUE OF ‘a’ INSIDE THIS FUNCTION = ”,a)

display() # Function Call


print(“THE VALUE OF ‘a’ OUTSIDE OF THIS FUNCTION = ”, a)

OUTPUT:
THE VALUE OF ‘a’ INSIDE THIS FUNCTION = 30
THE VALUE OF ‘a’ OUTSIDE OF THIS FUNCTION = 30

Positional Arguments:
Suppose if there are more than one parameter, then how does Python decide which argument
in the function call statement has to be assigned to which formal parameter in function
definition?
This is simply done by assigning the order of positions of arguments. That means the first
argument in function call statement is assigned to first formal parameter listed in function
definition and so on. This style of matching up arguments and parameters is called as
positional arguments.

Example:
CASE-1: Now try to understand the following scenario.
def display(name, age):
print(“Name = ”, name, “\t”, “Age = ”, age)

display(“Rohit”, 35) # Function Call1


OUTPUT: Name = Rohit Age = 35 [It is correct as usual]

9
PYTHON PROGRAMMING BCA - 3001

display(40, “Sachin”) # Function Call2


OUTPUT: Name = 40 Age = Sachin [It is incorrect As Name is 40 And Age is Sachin]

CASE-2: Again try to understand another scenario.


def display(name, age):
print(“Name = ”, name, “\t”, “Age = ”, age)

display(“Rohit”) # Function Call

OUTPUT: Missing 1 required positional argument: ‘age’ [Display An Error Message]

Remarkable Tip: Python interpreter will show an error when an incorrect number of
arguments are passed to the function call. Hence arguments must be matched with
corresponding parameters in order, number and type in function definition.

Keyword Arguments: An Alternate Solution To Positional Arguments


If a programmer knows the parameter name used within function, then he/she can explicitly
use this parameter name while calling the function. It means that arguments can be
appeared in any order (position of arguments does not matter) using the concept of keyword
arguments.

Example: Now try to understand the use of Keyword Arguments.


def display(name, age):
print(“Name = ”, name, “\t”, “Age = ”, age)

display(age=35, name=Rohit) # Function Call Using Keyword Arguments


OUTPUT: Name = Rohit Age = 35 [It is correct as usual]

Lambda Function:
A Lambda function is named after Greek letter λ(lambda). A Lambda function is also known
as anonymous function. That means the function is without a name. The lambda keyword is
used to define an anonymous function in Python. Such kind of function is not bound to a
name. Such functions only have a code to execute that which is associated with them.

Syntax: The basic syntax to use Lambda function is following as:


lambda arguments: expression

Why do we need lambda function?


1. One of the foremost common use cases for lambdas is in functional programming as
Python supports a style of functional programming.
2. Python provides a compact syntax for writing one line function that returns one expression.
3. We use lambda function (anonymous function) when we require a nameless function for a
short period of time.
4. This is a small and restricted function having only one line.
5. When there is a need to pass a short function as an argument to a higher order function
(a function that takes in other function as argument).

10
PYTHON PROGRAMMING BCA - 3001

Example-1: Suppose we want to calculate the cube of a positive number, then we have two
cases:

CASE-1: calculate the cube of a positive number using normal user-defined function
def cube(n):
return n*n*n

print(cube(5)) # Display The Cubic Value of 5 By Calling The lambda Function cube(5)

CASE-2: calculate the cube of a positive number using Lambda function

cube = lambda n: n*n*n # Defining Lambda Function Using Keyword ‘lambda’

print(cube(5)) # Displaying Cubic Value of 5 By Calling The lambda function cube(5)

Clarification: The statement cube = lambda n: n*n*n creates a lambda function called cube,
which takes a single argument and returns the cube of a number 5.

Tips:
1. A lambda function does not contain a return statement.
2. A lambda function contains only a single expression rather than a block of statements
as a body.
3. A lambda function can take any number of arguments.

Example-2:
add = lambda a : a+10
print(add(5)) #Displaying Updated Value of ‘a’ By Calling The lambda function add(5)
OUTPUT: 15

Example-3:
mul = lambda a, b : a*b
print(mul(5,6)) #Displaying Product Value of ‘a*b’ By Calling lambda function mul(5,6)

OUTPUT: 30

Example-4:
add = lambda a, b, c : a+b+c
print(add(1,5,8)) #Displaying Result of (a+b+c) By Calling lambda function add(1,5,8)

OUTPUT: 14

11
PYTHON PROGRAMMING BCA - 3001

Concept of Recursion:
Recursion is a powerful technique for writing a complicated algorithm in an easy way.
According to this technique, a problem is defined in terms of itself. Such problem is solved by
dividing it into smaller problems, which are similar in nature to the original problem. These
smaller problems are solved and their solutions are applied to get the final solution of our
original problem.

To implement recursion technique in programming, a function should be capable of calling


itself and such kind of facility is available in Python.

Advantages of Using Recursion:


 A complicated function can be split down into smaller sub-problems utilizing recursion.
 Sequence creation is simpler through recursion than utilizing any nested iteration.
 Recursive functions render the code look simple and effective.

Disadvantages of Using Recursion:


 A lot of memory and time is taken through recursive calls which make it expensive or
inefficient for use.
 Recursive functions are challenging to debug.
 The reasoning behind recursion can sometimes be tough to think through.

Recursive Function:
The function that calls itself (inside function body) again and again is known as a recursive
function. Before writing a recursive function for a problem, we should pay attention towards
the following two major aspects.
1. We should be able to define the solution of the problem in terms of a similar type of
smaller problem. At each step, we get closer to the final solution of our original problem.
2. There must be a terminating condition (Base Case) to stop the recursion.

12
PYTHON PROGRAMMING BCA - 3001

Example-1: Write a recursive function that compute and display the result of ab (a raised to
the power b).
def power(base, exponent):
if(exponent == 0):
return 1
if(exponent == 1):
return base
if(exponent > 1):
return (base*pow(base, exponent-1)) # Recursive Function Call

base = int(input(“ENTER THE VALUE OF BASE: ”))


exponent = int(input(“ENTER THE VALUE OF EXPONENT: ”))

print(“RESULT OF ”, base, “TO THE POWER ”, exponent, “ = ”, power(base, exponent)) # Function Call

OUTPUT:
ENTER THE VALUE OF BASE: 2
ENTER THE VALUE OF EXPONENT: 5
RESULT OF 2 TO THE POWER 5 = 32

Example-2: Write a recursive function that computes and displays the factorial value of a
positive number.
def rec_facto(n):
f=1
if(n == 0):
return 1
if(n == 1):
return n
if(n > 1):
return (n*rec_facto(n-1)) # Recursive Function Call

num = int(input(“ENTER A POSITIVE INTEGER NUMBER: ”))


print(“FACTORIAL VALUE OF ”, num, “ = ”, rec_facto(num)) # Function Call

OUTPUT:
ENTER A POSITIVE INTEGER NUMBER: 3
FACTORIAL VALUE OF 3 = 6

13
PYTHON PROGRAMMING BCA - 3001

14
PYTHON PROGRAMMING BCA - 3001

Example-3: Write a recursive function that generate and display the Fibonacci series of terms
n, if the total number of terms n is given by user.
def rec_fibo(n):
if(n <= 1): # Base Case
return n
else:
return (rec_fibo(n-1) + rec_fibo(n-2)) # Recursive Function Call

terms = int(input(“ENTER NUMBER OF TERMS AS POSITIVE INTEGER NUMBER: ”))

if(terms <= 0):


print(“PLEASE ENTER A POSTIVE INTEGER NUMBER”)
else:
print(“Fibonacci Series:”)
for i in range(terms):
print(rec_fibo(i)) # Function Call

OUTPUT:
ENTER NUMBER OF TERMS AS POSITIVE INTEGER NUMBER: 6
Fibonacci Series:
0
1
1
2
3
5
Example-4: Write a recursive function that calculate and display the sum of first n-natural
numbers, if the total number of terms n is given by user.
def sum_nums(n):
If(n == 1): # Base Case
return 1
return n + sum_nums(n - 1) # Recursive Function Call

num = int(input("Enter a number: "))


print(sum_nums(num)) # Displaying Sum of N-Natural Numbers By Function Call

Example-5: Write a recursive function that calculate and display the least common multiple
(LCM) of two numbers, if such two numbers are given by the user.
def LCM(x, y):
z=x%y
if z == 0: # Base Case
return x
return x * LCM(y, z) / z # Recursive Function Call
print("The least common factor is: ", LCM(4, 16)) # Displaying LCM of Two Numbers By Function Call

15
PYTHON PROGRAMMING BCA - 3001

Example-6: Write a recursive function that calculate and display the sum of digits of a
number, if that number is given by the user.
def sum_digits(n):
if(n == 0): # Base Case
return 0
else :
return int(n % 10) + sum_digits(int(n / 10)) # Recursive Function Call

num = int(input("Please Enter A Number: "))


print("The Sum is:", sum_digits(num))#Display Sum of Digits of A Number By Function Call

Variable Length Non-Keyword Arguments:


The variable length argument allows a function to pass or accept ‘n’ arbitrary number of
arguments. The arguments within the function are not named explicitly while calling the
function. With * operator, the function can accept or pass non-keyword variable length
argument.
The syntax to create a function that can take variable length non-keyword argument is as
follows.
Syntax:
def func_name(*args):
statement-1
statement-2
statement-3
-------------
-------------
func_name(value1) # Function Call1 By Passing One Non-Keyword Arguments
func_name(value1, value2) # Function Call2 By Passing Two Non-Keyword Arguments
func_name(value1, value2, value3)#Function Call3 By Passing Three Non-Keyword Arguments
--------------------------------------
--------------------------------------

Example: Write a function that can accept or pass ‘n’ number of non-keyword variable length
arguments to calculate the sum of ‘n’ numbers.

def Compute_Sum(*args):
s=0
print(“The Numbers Are As Follows:”)
for num in args:
print(num, end=’ ’)
s = s + num
return s

total = Compute_Sum(10, 20) # Calling Function By Passing 2 Non-Keyword Arguments


print(‘Sum = ’, total)

total = Compute_Sum(10, 20, 30) # Calling Function By Passing 3 Non-Keyword Arguments


print(‘Sum = ’, total)

total = Compute_Sum(10, 20, 30, 40) # Calling Function By Passing 4 Non-Keyword Arguments
print(‘Sum = ’, total)

16
PYTHON PROGRAMMING BCA - 3001

OUTPUT:
The Numbers Are As Follows:
10, 20
Sum = 30

The Numbers Are As Follows:


10, 20, 30
Sum = 60

The Numbers Are As Follows:


10, 20, 30, 40
Sum = 100

Variable Length Keyword Arguments:


With ** operator the function accepts keyword variable length argument.
The syntax to create a function that can take variable length keyword argument is as follows.

Syntax:
def func_name(**kwargs):
statement-1
statement-2
statement-3
-------------
-------------
func_name(variable_name1 = value1, ……..) # Function Call By Passing Keyword Arguments

Example: Write a function to accept any number of keyword arguments.


def Sample(**kwrgs):
print(kwrgs)

# Calling Function Sample() By Passing Keyword Arguments


Sample(Country = ‘India’, Population = 1000000000)
Sample(Team = ‘India’, Sport = ‘Cricket’, Captain = ‘Virat Kohli’)

OUTPUT:
{‘Country’: ‘India’, ‘Population’: 1000000000}

{‘Team’: ‘India’, ‘Sport’: ‘Cricket’, ‘Captain’: ‘Virat Kohli’}

17
PYTHON PROGRAMMING BCA - 3001

** SOME COMMON PROGRAMS USING CUSTOMIZED/USER-DEFINED FUNCTION **

1. Write a function that accepts a number of n-digits, reverse all digits of that number and
finally check and display whether this number is a Palindrome number or not.

A Palindrome number is a number that remains the same even if that number is inverted.
Example: 121, 11, 414, 1221, 74747 are the Palindrome numbers.

def Check_Palindrome(n): # Function Header


# Calculating Reverse of Number
reverse = 0
reminder = 0 # Function Body/Definition
while(n != 0):
remainder = n % 10 # Extracting The Last Digit of Number n
reverse = reverse * 10 + remainder # Process To Reverse Digits of Number n
n = int(n / 10) # Updating The Number n
return reverse

# Take Inputs From User


num = int(input('Enter the number: '))

reverse = Check_Palindrome(num) # Calling The Function


if(num == reverse):
print(num,"IS A PALINDROME NUMBER")
else:
print(num,"IS NOT A PALINDROME NUMBER")

2. Write a function that accepts a string, reverse all characters of that string and finally check
and display whether that string is a Palindrome string or not.

A Palindrome string is a string that remains the same even if the letters of that string are
inverted (reversed).
Example: MOM, MADAM, DAD, ADDA, REFER are the Palindrome string.
JAVATPOINT, PROGRAM, JAVA are not the Palindrome string.

CASE-1:
def String_Palindrome(s):
return s == s[::-1]

# Driver code
s = "malayalam"
ans = String_Palindrome(s)

if(ans):
print("YES", s, "IS A PALINDROME STRING")
else:
print("NO", s, "IS NOT A PALINDROME STRING")

18
PYTHON PROGRAMMING BCA - 3001

CASE-2:
x = "malayalam"
w = ""
for i in x:
w=i+w

if (x == w):
print("YES", x, "IS A PALINDROME STRING")
else:
print("NO", x, "IS NOT A PALINDROME STRING")

3. Write a function that accepts a number of n-digits, now check and display whether this
input number is an Armstrong Number or not.
INPUT: n = 153 [Other Armstrong Numbers: 370, 371, 407, 1634(100 To 2000)]
CHECK: Sum = 13 + 53 + 33 = 153,
Since n = Sum = 153, hence ‘n’ is an Armstrong Number.

def display_armstrong(lower, upper):


for n in range(lower, upper + 1):
# order of number
order = len(str(n))
sum = 0
temp = n

while(n > 0):


digit = n % 10 # Extracting The Last Digit of Number n
sum += digit ** order # Process To Sum up The Cubic Values of Extracted Last Digit
n //= 10 # Updating The Number n

if(temp == sum):
print(temp)

start = 100
end = 2000

display_armstrong(start, end) # Calling The Function

4. Write a function that accepts number of terms from user to generate Fibonacci Series.
If very first two terms are initially given by user in the program.

def gen_fibo_series(n):
f1, f2 = 0, 1
print(f1, “ ”, f2)
count = 3
while(count <= n):
f3 = f1 + f2
print(f3, end=' ')
f1 = f2
f2 = f3
num = int(input(“PLEASE ENTER NUMBER OF TERMS: ”))
gen_fibo_series(num) # Calling The Function

19
PYTHON PROGRAMMING BCA - 3001

5. Write a function that accepts a positive number n, if n is given by user. Now display table
of that number n in the following format.
INPUT: n = 5
Display: 5X1=5
5 X 2 = 10
5 X 3 = 15
------------
------------
5 X 10 = 50

def Display_Table(n):
i=1
while(i <=10):
print(n, “X”, i, “=”, n*i)
i+=1 # Increment The Value of Counting Variable i

num = int(input(“PLEASE ENTER A POSITIVE NUMBER: ”))


Display_Table (num) # Calling The Function

6. Write a function that reads marks in 5 subjects obtained by a student in an examination.


Assume that the maximum marks in each subject is 100. Now calculate aggregate and
percentage marks and then display the respective grades obtained by this student as per the
following criteria-
If percentage>90 And percentage<=100, display Grade – A
If percentage>80 And percentage<=90, display Grade – B
If percentage>70 And percentage<=80, display Grade – C
If percentage>60 And percentage<=70, display Grade - D

def Display_Grade(n): # Function Header


# Process To Input Marks In 5 Different Subjects
hindi = eval(input(“PLEASE ENTER MARKS IN HINDI: ”))
english = eval(input(“PLEASE ENTER MARKS IN ENGLISH: ”))
maths = eval(input(“PLEASE ENTER MARKS IN MATHS: ”))
physics = eval(input(“PLEASE ENTER MARKS IN PHYSICS: ”))
chemistry = eval(input(“PLEASE ENTER MARKS IN CHEMISTRY: ”))

# Process To Calculate Total And Percentage Marks


total = hindi + english + maths + physics + chemistry
percentage = (total*100)/500

# Process To Check And Print Grade As Per The Percentage Criteria Specified
if(percentage>60 and percentage<=70)
print(“Grade-D”)
if(percentage>70 and percentage<=80)
print(“Grade-C”)
if(percentage>80 and percentage<=90)
print(“Grade-B”)
if(percentage>90 and percentage<=100)
print(“Grade-A”)

20
PYTHON PROGRAMMING BCA - 3001

Display_Grade (num) # Calling The Function


7. Write a function to find and display the maximum and minimum values among the
numbers stored in a list, if this list is given by the user.
#Function To Find Maximum and Minimum Value In The list
def max_min(list):
max = list[0]
min = list[0]
# Process To Find Maximum And Minimum Number In list
for i in list:
if i > max:
max = i
if i < min:
min = i
return max, min
list = [] # Creating An Empty List
n = int(input("PLEASE ENTER THE NUMBER OF ELEMENTS: "))
# Process To Input n-Numbers One By One In The list
for i in range(0, n):
list.append(int(input("Enter the number: ")))

max, min = max_min(list) #Calling the function max_min()


print("Maximum number = ","\n", "Minimum Number = ", max, min)

8. For a quadratic equation in the form of ax2 + bx + c, the discriminant D, is b2-4ac.


Now write a function to compute discriminant D, that returns the following output depending
on the value of discriminant D.
if D>0: The Equation has two Real Roots
if D=0: The Equation has one Real Root
if D<0: The Equation has two Complex Roots
#Function To Find Maximum and Minimum Value In The list
def Quad_D(a, b, c):
d = b*b-4*a*c
print(“a = ”, a)
print(“b = ”, b)
print(“c = ”, c)
print(“D = ”, d)
# Process To Find Maximum And Minimum Number In list
if(d > 0):
return “The Equation has two Real Roots”
elif(d < 0):
return “The Equation has two Complex Roots”
else:
return “The Equation has one Real Root”
n1, n2, n3 = 1, 2, 3
print(Quad_D(n1, n2, n3)) #Calling the function Quad_D()
OUTPUT:
a=1
b=2
c=3
D = -8
The Equation has two Complex Roots

21
PYTHON PROGRAMMING BCA - 3001

9. Write a function that accepts a list of n-numbers and perform the following tasks:
a. Linear Search
b. Binary Search
#Function To Perform Binary Search
def binary_search(list, item):
low = 0
high = len(list)-1
while low <= high:
mid = (low + high)//2
guess = list[mid]
if guess == item:
return mid
if guess > item:
high = mid - 1
else:
low = mid + 1
return None

#Function To Perform Linear Search


def linear_search(list, item):
for i in range(len(list)):
if list[i] == item:
return i
return None

#Main Program
list = [] # Creating An Empty List Named list
x = int(input("Enter the number of elements: "))

for i in range(0, x):


list.append(int(input("Enter The Number: ")))
print("List is", list)

item = int(input("Enter The Number To Search Be Searched: "))


print("1. Binary Search")
print("2. Linear Search")
choice = int(input("Enter Your Choice: "))
if(choice == 1):
result = binary_search(list, item) #Calling binary search function
if(result != None):
print("Number found at position", result+1)
else:
print("Number not found")
elif(choice == 2):
result = linear_search(list, item) #Calling linear search function
if(result != None):
print("Number Found At Position: ", result+1)
else:
print("Number Doesn’t Found")
else:
print("Invalid Choice")

22
PYTHON PROGRAMMING BCA - 3001

Why Do We Need Dictionary?


We have learnt about a Python data structure called list. A List organizes their
elements/items by position and this kind of structuring is useful when we want to
locate elements in a specific order that means locate either first, last element or visit
each element in a sequence.

There may be a situation where a programmer is not so much interested in the


position of the item or element in the structure but in association of that element
with some other element in the structure.

For example, to look up Adam’s phone number we are just interested in his phone
number from the phonebook and don’t so much concern about the location of that
phone number in the phonebook.

Introduction To Dictionary:
A dictionary is a collection that stores values along with associated unique keys. The
sequences of such keys and values pairs are separated by commas(,). Such pairs are
sometimes called items/entries. All items are enclosed within curly brackets{}. A colon(:)
sign is used to associate a value to its respective unique key.

KEY-1 VALUE-1 Item-1

KEY-2 VALUE-2 Item-2

-------------------------------------------------------
-------------------------------------------------------

KEY-N VALUE-N Item-N

(Fig. [General Diagrammatic Structure of A Dictionary])

Example:
Consider a dictionary named ‘Phone_Book’ that contains phone numbers of some persons.

Phone_Book = {“Amit” : 8764557863, “Sumit” : 6294335318, “Alok” : 7965342217}

Key1 Value1 Key2 Value2 Key3 Value3

State_Capitals = {“Uttar Pradesh” : “Lucknow”, “Punjab” : “Chandigarh”, “Rajasthan” : “Jaipur”}

Key1 Value1 Key2 Value2 Key3 Value3

23
PYTHON PROGRAMMING BCA - 3001

Tips:
1. Keys are like an index operator in a dictionary.
2. A key can be of any type.
3. A dictionary does not contain any duplicate keys.
4. Dictionary is a mapping of unique keys to their respective associated values, which means
each unique key is mapped to its only single value.
5. A dictionary is a collection of items/entries that are changeable and ordered (now new
version 3.7 and onwards a dictionary items are ordered except version 3.6 and earlier)
6. Python uses curly braces for both dictionary and set. Therefore to create an empty
dictionary, we must have to use {} or dict() function and for creating an empty set, we must
have to use set() function.

Creating Dictionary:
We can create a dictionary as following as:
1. Creating An Empty Dictionary:
We can create an empty dictionary by the two ways:
(a) D1 = {} # Creating An Empty Dictionary ‘D1’
print(D1)
print(type(D1)) # Displaying The Data Type of ‘D1’
OUTPUT:
{} An Empty Dictionary
<class ‘dict’>

(b) D1 = dict() # Creating An Empty Dictionary ‘D1’ Through Built-In Function dict()
print(D1)

OUTPUT:
{} An Empty Dictionary

2. Creating Dictionary Having Collection of N-Items:


A dictionary of N-items can be created by 4 different ways.
(a) Method-1:
# Creating A Dictionary Named ‘Phone_Book’
Phone_Book = {“Amit” : 8764557863, “Sumit” : 6294335318, “Alok” : 7965342217}

Key1 Value1 Key2 Value2 Key3 Value3

# Creating A Dictionary Named ‘Employee_Info’


Employee_Info = {“Name” : “Jhony”, “Age” : 40, “Address” : “W-1, Green City”}

24
PYTHON PROGRAMMING BCA - 3001

print(Phone_Book)
OUTPUT: {“Amit” : 8764557863, “Sumit” : 6294335318, “Alok” : 7965342217}

print(Employee_Info)
OUTPUT: {“Name” : “Jhony”, “Age” : 40, “Address” : “W-1, Green City”}
(b) Method-2:
Employee_Info = {} # Creating An Empty Dictionary Named ‘Employee_Info’
Employee_Info[“Name”] = “Aniket”
Employee_Info[“Age”] = 30
Employee_Info[“Address”] = “Street-5, Robin Tower, The Dream City”
print(Employee_Info)
OUTPUT:
{“Name” : “Aniket”, “Age” : 30, “Address” : “Street-5, Robin Tower, The Dream City”}

(c) Method-3:
Employee_Info = dict(Name = ‘Sachin’, Age = 28, Address = ‘Sector-15, Kinetic Road’)
print(Employee_Info)
OUTPUT:
{‘Name’ : ‘Sachin’, ‘Age’ : 28, ‘Address’ : ‘Sector-15, Kinetic Road’}

(d) Method-4:
print(dict([(“Name”, “Sachin”), (“Age”, 28), (“Address”, “Sector-15, Kinetic Road”)]))
OUTPUT:
{‘Name’ : ‘Sachin’, ‘Age’ : 30, ‘Address’ : ‘Sector-15, Kinetic Road’}

Adding / Replacing Items:


To add a new item to a dictionary, we can use the subscript[] operator.
Syntax:
dictionary_name[key] = value
Example-1:
Phone_Book[“Manish”] = 6214573280
print(Phone_Book)

25
PYTHON PROGRAMMING BCA - 3001

Example-2: Creating dictionary of Phone_Book


# Creating A Dictionary Named ‘Phone_Book’
Phone_Book = {“Amit” : 8764557863, “Sumit” : 6294335318, “Alok” : 7965342217}

Key1 Value1 Key2 Value2 Key3 Value3


print(Phone_Book)
OUTPUT: {“Amit” : 8764557863, “Sumit” : 6294335318, “Alok” : 7965342217}

# Now Add Another Item To The Existing Dictionary Named ‘Phone_Book’


Phone_Book[“Rohit”] = 8755568345 # Add New Item To Phone_Book
print(Phone_Book)
OUTPUT:
{“Rohit” : 8755568345, “Amit” : 8764557863, “Sumit” : 6294335318, “Alok” : 7965342217}

Tip: If a key is already present in an existing dictionary, then it replaces the old value for this
key as mentioned with the new value added.
Example:
# Creating A Dictionary Named ‘Phone_Book’
Phone_Book = {“Amit” : 8764557863, “Sumit” : 6294335318, “Alok” : 7965342217}

Phone_Book[“Amit”] = 6325568345 # Add New Value To Already Existing Key


print(Phone_Book)

OUTPUT:
{“Amit” : 6325568345, “Sumit” : 6294335318, “Alok” : 7965342217}

Accessing/Retrieving/Getting Values of Dictionary Items:


Subscript [] operator can also be used to obtain the value associated with the relevant key.
Syntax: dictionary_name[key] # Accessing Values Associated With The Relevant Key

Example:
# Creating A Dictionary Named ‘Phone_Book’
Phone_Book = {“Amit” : 8764557863, “Sumit” : 6294335318, “Alok” : 7965342217}
print(Phone_Book[“Sumit”])

OUTPUT: 6294335318

Tip: If a key is not present in an existing dictionary, then Python interpreter raises or throws
an error.

26
PYTHON PROGRAMMING BCA - 3001

Example:
# Creating A Dictionary Named ‘Phone_Book’
Phone_Book = {“Amit” : 8764557863, “Sumit” : 6294335318, “Alok” : 7965342217}
print(Phone_Book[“Johnson”])

OUTPUT: KeyError: “Johnson”

Traversing All Items of A Dictionary:


We can use for loop to traverse all items (all pairs of keys and its respective values) of a
dictionary. A variable used with for loop is bound to each key in an unspecified order.
It means that it retrieves the key and its value in any order. Now let us try to understand the
process for traversing all items of a dictionary through following example.

Example:
CASE-1:
Grades = {“Tanmay” : “A”, “Chinmay” : “B”, “Anay” : “C”, “Manmay” : “D”}
for key in Grades:
print(key, “:”, Grades[key])

OUTPUT:
Tanmay : A
Chinmay : B
Anay : C
Manmay : D

CASE-2:
Grades = {“Tanmay” : “A”, “Chinmay” : “B”, “Anay” : “C”, “Manmay” : “D”}
for key in Grades.keys():
print(key, “ ”, Grades.get(key, 0))

OUTPUT:
Tanmay : A
Chinmay : B
Anay : C
Manmay : D

Deleting Items From Dictionary:


We can delete or remove any item/entry from the dictionary. The del operator is used to
remove a key with its associated value.
Syntax: del dictionary_name[key]
Example:
# Creating A Dictionary Named ‘Phone_Book’
Phone_Book = {“Amit” : 8764557863, “Sumit” : 6294335318, “Alok” : 7965342217}
del Phone_Book[“Sumit”] # Deleting The Item Sumit
print(Phone_Book)
OUTPUT: Phone_Book = {“Amit” : 8764557863, “Alok” : 7965342217}

27
PYTHON PROGRAMMING BCA - 3001

Formatting Dictionary:
The % operator is used to substitute values from a dictionary into a string by a name.

Example:
Items[“LAPTOP”] = “Lenovo”
Items[“COUNT”] = 500
print(Items) # Displaying Dictionary Named Items

OUTPUT: {“LAPTOP” : “Lenovo”, “COUNT” : 500}

# Now We Want To Access The Values of LAPTOP And COUNT from dictionary ‘Item’ And
# Then Use Such Values To Make A Meaningful Sentence Formatted As:
We WANT TO PURCHASE 500 Lenovo LAPTOPS For OUR BUSINESS PURPOSE.

P = “We WANT TO PURCHASE %(COUNT)d %(LAPTOP)s LAPTOPS For OUR BUSINESS PURPOSE.” %Items

OUTPUT: We WANT TO PURCHASE 500 Lenovo LAPTOPS For OUR BUSINESS PURPOSE.

Comparing Two Dictionaries:


We can use the equality(==) operator to test if two dictionaries contain the same items.
The ‘!=’ operator returns True if the items within dictionaries are not the same.

Example:
#Creating Two Dictionaries With Items (Student Names, Roll Numbers)
Student_Info = {“Abodh” : 10, “Nibodh” : 11, “Subodh” : 12}
Student_Details = {“Abodh” : 10, “Nibodh” : 11, “Pramod” : 13}

print(Student_Info == Student_Details)

output: False

print(Student_Info != Student_Details)

output: True

Built-In Methods Used With Dictionary:


Python contains dict class for dictionaries. To get the complete information for dictionary, we
can execute the command help(dict) in interactive mode.

Some Readymade Methods Useful For Working With Dictionary:

1. keys(): This method returns a sequence of keys of a dictionary.


Example:
ASCII_CODES = {“A” : 65, “B” : 66, “C” : 67, “D” : 68}
print(ASCII_CODES)
OUTPUT: {“A” : 65, “B” : 66, “C” : 67, “D” : 68}

print(ASCII_CODES.keys()) # Return And Display All Keys

28
PYTHON PROGRAMMING BCA - 3001

OUTPUT: dict_keys([“A”, “B”, “C”, “D”])

ASCII_CODES[“E”] = 69 # Add New Item To Dictionary ‘ASCII_CODES’


print(ASCII_CODES.keys())# Return And Display All Keys
OUTPUT: dict_keys([“A”, “B”, “C”, “D”, “E“])

2. items(): This method returns all items in form of a sequence of tuples.


Example:
ASCII_CODES = {“A” : 65, “B” : 66, “C” : 67, “D” : 68}
print(ASCII_CODES)
OUTPUT: {“A” : 65, “B” : 66, “C” : 67, “D” : 68}

print(ASCII_CODES.items()) # Return And Display All Items In Form of Sequence of Tuples


OUTPUT: dict_items([(“A”, 65), (“B”, 66), (“C”, 67), (“D”, 68)])

3. values(): This method returns a sequence of all values corresponds to all existing keys.
Example:
ASCII_CODES = {“A” : 65, “B” : 66, “C” : 67, “D” : 68}
print(ASCII_CODES)
OUTPUT: {“A” : 65, “B” : 66, “C” : 67, “D” : 68}

print(ASCII_CODES.values())# Return & Display Sequence of All Values Corresponds To Keys


OUTPUT: dict_values([ 65, 66, 67, 68)])

4. clear(): This method is used to delete or remove all items or entries of a dictionary.
Example:
ASCII_CODES = {“A” : 65, “B” : 66, “C” : 67, “D” : 68}

ASCII_CODES.clear() # Deletes/Removes All Items of Dictionary Named ASCII_CODES


print(ASCII_CODES)
OUTPUT: {} # An Empty Dictionary

5. get(key): This method is used to return a value corresponds to a specific key existing in
the dictionary.
Example:
Temperature = {“Mumbai” : 35, “Delhi” : 40, “Chennai” : 45, “Kanpur” : 42}

print(Temperature.get(“Mumbai”)) # Return & Display A Value Belongs To A Respective Key


OUTPUT: 35

6. pop(key): This method is used to return a value corresponds to a key removed from the
dictionary.
Example:
Temperature = {“Mumbai” : 35, “Delhi” : 40, “Chennai” : 45, “Kanpur” : 42}

29
PYTHON PROGRAMMING BCA - 3001

print(Temperature.pop(“Mumbai”)) # Return & Display A Value Belongs To Respective Key


OUTPUT: 35

print(Temperature) # Display An Updated Dictionary After Applying pop() function


OUTPUT: {“Delhi” : 40, “Chennai” : 45, “Kanpur” : 42}
7. len(dictionary_name): This method is used to return size or counting of all items
existing in the dictionary.
Example:
Temperature = {“Mumbai” : 35, “Delhi” : 40, “Chennai” : 45, “Kanpur” : 42}

print(len(Temperature)) # Return & Display Total Number of Items In Counting


OUTPUT: 4

8. copy(): This method is used to return the copy of an existing dictionary.


Example:
Temperature = {“Mumbai” : 35, “Delhi” : 40, “Chennai” : 45, “Kanpur” : 42}

New_Temperature = Temperature.copy() # Copies Items of Existing Dictionary To New One


print(New_Temperature) # Display New Dictionary After Copying Existing Dictionary
OUTPUT: {“Mumbai” : 35, “Delhi” : 40, “Chennai” : 45, “Kanpur” : 42}

9. update(): This method updates an existing dictionary with new items added
CASE-1:
Example:
Temperature1 = {“Mumbai” : 35, “Delhi” : 40, “Chennai” : 45, “Kanpur” : 42}
Temperature2 = {“Lucknow” : 38, “Noida” : 41, “Bhopal” : 39, “Chandigarh” : 35}

Temperature1.update(Temperature2)
print(Temperature1)) # Display Updated Temperature1 By Adding Items of Temperature2

OUTPUT:
{“Mumbai” : 35, “Delhi” : 40, “Chennai” : 45, “Kanpur” : 42, “Lucknow” : 38, “Noida” : 41, “Bhopal” : 39, “Chandigarh” : 35}

CASE-2: Updating An Existing Dictionary By Passing Sequence of Tuple


Example:
Temperature1 = {“Mumbai” : 35, “Delhi” : 40, “Chennai” : 45, “Kanpur” : 42}

# Updating Temperature1 Through update() method By Passing Sequence of Tuples In It


Temperature1.update([({“Lucknow”, 38),( “Noida”, 41),( “Bhopal”, 39),( “Chandigarh”,35)])

print(Temperature1)) # Display Updated Temperature1 By Passing Sequence of Tuples


OUTPUT:
{“Mumbai” : 35, “Delhi” : 40, “Chennai” : 45, “Kanpur” : 42, “Lucknow” : 38, “Noida” : 41, “Bhopal” : 39,
“Chandigarh” : 35}

30
PYTHON PROGRAMMING BCA - 3001

Nested Dictionary:
A dictionary defined within a dictionary is called as a nested dictionary. It is needed
immensely when we want to get fruitful detailed information.
Now let’s try to understand about the nested dictionary by the following example.

Example: Consider a dictionary of Indian Cricket Players with some information about them.
Players = {“Virat” :{“ODI” : 7212, “Test” : 5000}, “Sachin” :{ “ODI” : 18426, “Test” : 15921}}

External Key-1, Key-2


print(Players[“Virat”][“ODI”]) # Displaying Runs Scored By Virat In “ODI” Format

OUTPUT: 7212

print(Players[“Virat”][“Test”]) # Displaying Runs Scored By Virat In “Test” Format

OUTPUT: 5000

print(Players[“Sachin”][“ODI”]) # Displaying Runs Scored By Sachin In “ODI” Format

OUTPUT: 18426

print(Players[“Sachin”][“Test”]) # Displaying Runs Scored By Sachin In “Test” Format

OUTPUT: 15921

Traversing Nested Dictionary:


Consider a dictionary of Indian Cricket Players with some information about them.

Players = {“Virat” :{“ODI” : 7212, “Test” : 5000}, “Sachin” :{ “ODI” : 18426, “Test” : 15921}}

We can traverse/access each and every items of nested dictionary by the following ways.

Method-1:

for Player_Name, Player_Details in Players.items():


print(“ ”, Player_Name)
print(“ ”, Player_Details)

OUTPUT:
Sachin
{“Test” : 15921, “ODI” : 18426}
Virat
{“Test” : 5000, “ODI” : 7212}

Method-2:

for Player_Name, Player_Details in Players.items():


print(“Player Name: ”, Player_Name)
print(“Runs Scored In ODI: ”, Player_Details[“ODI”])
print(“Runs Scored In Test: ”, Player_Details[“Test”])

31
PYTHON PROGRAMMING BCA - 3001

OUTPUT:
Player Name: Sachin
Runs Scored In ODI : 18426
Runs Scored In Test : 15921

Player Name: Virat


Runs Scored In ODI : 7212
Runs Scored In Test : 5000

Method-3:

for Player_Name, Player_Details in Players.items():


print(“ ”, Player_Name)
for key in Player_Details:
print(key, “:”, str(Player_Details[“key”]))

OUTPUT:
Sachin
ODI : 18426
Test : 15921

Virat
ODI : 7212
Test : 5000

Representation of Polynomial In Form of Dictionary:


We can also represent a polynomial in form of dictionary.

Suppose there is a polynomial in terms of one variable represented as:


P(X) = -2 + X2 + 3X6
P(X) = -2X0 + 1X2 + 3X6
Then the above polynomial is represented in form of dictionary as:

P = {Power1: Coefficient1, Power2: Coefficient2, Power3: Coefficient3}


P = {0: -2, 2:1, 6:3}

Example: WAP to evaluate a polynomial of one variable ‘x’, if the value of x is 2.


P(X) = -2 + X2 + 3X6
P(2) = 194
def Compute_Poly(P, X):
sum = 0
for Power in P:
sum = sum + P[Power]*X**Power
print(“The Value of Polynomial After Evaluation: ”, sum)

P = {0: -2, 2: 1, 3: 3}
Compute_Poly(P, 2)

OUTPUT: The Value of Polynomial After Evaluation: 194

32
PYTHON PROGRAMMING BCA - 3001

** SOME COMMON PROGRAMS BASED ON DICTIONARY **

1. WAP to calculate the total number of even and odd numbers in a list and return the result
in form of dictionary.
def dict_even_odd(l):
d = dict()
d['even'] = 0
d['odd'] = 0
for i in l:
if i%2 == 0:
d['even'] += 1
else:
d['odd'] += 1
return d

l = [1,2,3,4,5,6,7,8,9,10] # Creating And Initializing A List Named l


print(dict_even_odd(l)) # Calling The Function dict_even_odd()

2. Write a function to calculate total number of postive and negative numbers in a list and
return the result in form of dictionary
def dict_Pos_Neg(l):
d = dict()
d['positive'] = 0
d['negative'] = 0
for i in l:
if i > 0:
d['positive'] += 1
elif i < 0:
d['negative'] += 1
return d

l = [1, 2, 3, -1, -2, -3] # Creating And Initializing A List Named l


print(dict_Pos_Neg(l)) # Calling The Function dict_Pos_Neg()

3. WAP to print the square of the first ‘N’ natural numbers in form of dictionary.
def dict_square(n):
d = dict()
for i in range(1,n+1):
d[i] = i**2
return d
n = int(input('Enter the number: '))
print(dict_square(n)) # Function Call

4. Write a function histogram that takes a string as parameter and prints the frequency of
characters contained in it in form of dictionary.
CASE-1:
def histogram(s):
d = dict()

33
PYTHON PROGRAMMING BCA - 3001

for c in s:
if c not in d:
d[c] = 1
else:
d[c] += 1
return d

H = histogram('AAPPLE') # Function Call


print(H)

CASE-2:
def histogram(s):
d = dict()
for c in s:
if c not in d:
d[c] = 1
else:
d[c] = d.get(c, 0) + 1 # Using get() Method
return d

H = histogram('AAPPLE') # Function Call


print(H)

5. WAP to search for a key in a dictionary and show the value


d = {'a':1,'b':2,'c':3,'d':4,'e':5}
key = input('Enter the key to search: ')
if key in d:
print('The value of the key is: ',d[key])
else:
print('The key is not found')

6. WAP that accepts a nested dictionary of 4-Indian Cricket Players having scores in different
formats such as One-Day International, T-20 and Test matches. Now calculate and print the
total score of each player in all formats of Cricket.

#Nested dictionary of 4-Indian cricketers With Their Scores In Different Formats


cricketers = {
'Sachin':{ 'ODI':20000, 'T20':2000, ‘Test’:15921},
'Dhoni':{'ODI':10000, 'T20':1500, ‘Test’: 9000},
'Kohli':{ 'ODI':10000, 'T20':5500, ‘Test’: 8000}
'Rohit':{ 'ODI':9500, 'T20':5100, ‘Test’: 5200}
}
#Calculate And Display The Total Scores of Each Cricketer In Different Formats
for cricketer in cricketers:
ODI = cricketers[cricketer]['ODI']
T20 = cricketers[cricketer]['T20']
Test = cricketers[cricketer]['Test']
total_score = ODI + T20 + Test
print(‘Player Name =’, cricketer)
print(‘Total Score =’, total_score)

34
PYTHON PROGRAMMING BCA - 3001

7. Consider the following dictionary named car_sales, which has sales of multiple cars in
different states.
Now write functions that perform the following tasks:
a. Display sales statewise and total sales of 4 states
b. Display overall sales of each automobile company (Hyundai, Ford, Tata)
c. Calculate and display the average sales of cars of all four states (UP, Maharashtra, Delhi,
Haryana)
d. Calculate and display the average sales of automobiles companies (Hyundai, Ford, Tata)

car_sales = {
"UP":{"Hyundai": 6000, "Ford": 5000, "Tata":8000},
"Delhi":{ "Hyundai": 7000, "Ford": 6000, "Tata":10000},
"Maharastra":{ "Hyundai": 8000, "Ford": 4000, "Tata":12000},
"Haryana":{ "Hyundai": 4000, "Ford": 8000, "Tata":15000}
}
#Function To Display Sales Statewise And Total Sales
def sales_state_wise(car_sales):
for state in car_sales:
print("Sales in", state)
for car in car_sales[state]:
print(car, ":", car_sales[state][car])
print()

#Funtion To Display Overall Sales of Each Car Company


def overall_sales(car_sales):
for state in car_sales:
for car in car_sales[state]:
if car == "Hyundai":
hyundai = hyundai + car_sales[state][car]
elif car == "Ford":
ford = ford + car_sales[state][car]
elif car == "Tata":
tata = tata + car_sales[state][car]
print("Overall sales of Hyundai is", hyundai)
print("Overall sales of Ford is", ford)
print("Overall sales of Tata is", tata)

#Function To Display Average Sales of All Cars In Each State


def average_sales(car_sales):
for state in car_sales:
sum = 0
for car in car_sales[state]:
sum = sum + car_sales[state][car]
print("Average sales in", state, "is", sum/3)

#Function To Display Average Sales Of Each Car Company


def average_sales_car(car_sales):
for car in car_sales["UP"]:
sum = 0
for state in car_sales:
sum = sum + car_sales[state][car]

35
PYTHON PROGRAMMING BCA - 3001

print("Average sales of", car, "is", sum/4)

# Main Program
sales_state_wise(car_sales) # Function Call1
overall_sales(car_sales) # Function Call2
average_sales(car_sales) # Function Call3
average_sales_car(car_sales) # Function Call4

36

You might also like