Unit 3 & 4
Unit 3 & 4
7)
1. Introduction to Dictionaries
1.1 What is a Dictionary?
A dictionary in Python is an ordered, mutable collection that stores data in key-value pairs. Unlike
lists or tuples, dictionaries use keys for indexing instead of numerical indices.
Example:
We can access dictionary values using keys inside square brackets [].
Example:
The get() method retrieves a value and prevents errors if the key is missing.
Example:
print(details.get("age")) # Output: 25
print(details.get("country", "Not Available")) # Output: Not Available
Example:
details["country"] = "USA"
print(details)
details["age"] = 26
del details["city"]
age = details.pop("age")
print(age) # Output: 26
Clearing a Dictionary
details.clear()
print(details) # Output: {}
4. Nested Dictionaries
Dictionaries can contain other dictionaries as values.
Example:
students = {
"Alice": {"age": 22, "course": "CS"},
"Bob": {"age": 24, "course": "Math"}
}
print(students["Alice"]["course"]) # Output: CS
Example:
Sorting by Values
8. Practice Exercises
8.1 Creating a Student Database
Write a program that stores student details (name, age, and course) using a dictionary and allows
updating values.
Write a program to count the frequency of words in a given text using a dictionary.
Example:
Python allows us to divide a large program into the basic building blocks known as
function. The function contains the set of programming statements enclosed by {}. A
function can be called multiple times to provide reusability and modularity to the
python program.
In other words, we can say that the collection of functions creates a program. The
function is also known as procedure or subroutine in other programming languages.
Python provide us various inbuilt functions like range() or print(). Although, the user
can create its functions which can be called user-defined functions.
o By using functions, we can avoid rewriting same logic/code again and again in
a program.
o We can call python functions any number of times in a program and from any
place in a program.
o We can track a large python program easily when it is divided into multiple
functions.
o Reusability is the main achievement of python functions.
o However, Function calling is always overhead in a python program.
Creating a function
In python, we can use def keyword to define the function. The syntax to define a
function in python is given below.
1. def my_function():
2. function-suite
3. return <expression>
The function block is started with the colon (:) and all the same level block
statements remain at the same indentation.
A function can accept any number of parameters that must be the same in the
definition and function calling.
Function calling
In python, a function must be defined before the function calling otherwise the python
interpreter gives an error. Once the function is defined, we can call it from another
function or the python prompt. To call the function, use the function name followed by
the parentheses.
A simple function that prints the message "Hello Word" is given below.
1. def hello_world():
2. print("hello world")
3.
4. hello_world()
Output:
hello world
Parameters in function
The information into the functions can be passed as the parameters. The parameters
are specified in the parentheses. We can give any number of parameters, but we
have to separate them with a comma.
Consider the following example which contains a function that accepts a string as the
parameter and prints it.
Example 1
1. #defining the function
2. def func (name):
3. print("Hi ",name);
4.
5. #calling the function
6. func("Ayush")
Example 2
1. #python function to calculate the sum of two variables
2. #defining the function
3. def sum (a,b):
4. return a+b;
5.
6. #taking values from the user
7. a = int(input("Enter a: "))
8. b = int(input("Enter b: "))
9.
10. #printing the sum of a and b
11. print("Sum = ",sum(a,b))
Output:
Enter a: 10
Enter b: 20
Sum = 30
However, there is an exception in the case of mutable objects since the changes
made to the mutable objects like string do not revert to the original string rather, a
new string object is made, and therefore the two different objects are printed.
Output:
Output:
Types of arguments
There may be several types of arguments which can be passed at the time of function
calling.
1. Required arguments
2. Keyword arguments
3. Default arguments
4. Variable-length arguments
Required Arguments
Till now, we have learned about function calling in python. However, we can provide the
arguments at the time of function calling. As far as the required arguments are
concerned, these are the arguments which are required to be passed at the time of
function calling with the exact match of their positions in the function call and function
definition. If either of the arguments is not provided in the function call, or the position
of the arguments is changed, then the python interpreter will show the error.
Example 1
1. #the argument name is the required argument to the function func
2. def func(name):
3. message = "Hi "+name;
4. return message;
5. name = input("Enter the name?")
6. print(func(name))
Output:
Example 2
1. #the function simple_interest accepts three arguments and returns the simple interest a
ccordingly
2. def simple_interest(p,t,r):
3. return (p*t*r)/100
4. p = float(input("Enter the principle amount? "))
5. r = float(input("Enter the rate of interest? "))
6. t = float(input("Enter the time in years? "))
7. print("Simple Interest: ",simple_interest(p,r,t))
Output:
Example 3
1. #the function calculate returns the sum of two arguments a and b
2. def calculate(a,b):
3. return a+b
4. calculate(10) # this causes an error as we are missing a required arguments b.
Output:
Keyword arguments
Python allows us to call the function with the keyword arguments. This kind of function
call will enable us to pass the arguments in the random order.
The name of the arguments is treated as the keywords and matched in the function
calling and definition. If the same match is found, the values of the arguments are
copied in the function definition.
Example 1
1. #function func is called with the name and message as the keyword arguments
2. def func(name,message):
3. print("printing the message with",name,"and ",message)
4. func(name = "John",message="hello") #name and message is copied with the values Jo
hn and hello respectively
Output:
Output:
Simple Interest: 1900.0
If we provide the different name of arguments at the time of function call, an error will
be thrown.
Example 3
1. #The function simple_interest(p, t, r) is called with the keyword arguments.
2. def simple_interest(p,t,r):
3. return (p*t*r)/100
4.
5. print("Simple Interest: ",simple_interest(time=10,rate=10,principle=1900)) # doesn
't find the exact match of the name of the arguments (keywords)
Output:
The python allows us to provide the mix of the required arguments and keyword
arguments at the time of function call. However, the required argument must not be
given after the keyword argument, i.e., once the keyword argument is encountered in
the function call, the following arguments must also be the keyword arguments.
Example 4
1. def func(name1,message,name2):
2. print("printing the message with",name1,",",message,",and",name2)
3. func("John",message="hello",name2="David") #the first argument is not the keywor
d argument
Output:
Example 5
1. def func(name1,message,name2):
2. print("printing the message with",name1,",",message,",and",name2)
3. func("John",message="hello","David")
Output:
Default Arguments
Python allows us to initialize the arguments at the function definition. If the value of
any of the argument is not provided at the time of function call, then that argument
can be initialized with the value given in the definition even if the argument is not
specified at the function call.
Example 1
1. def printme(name,age=22):
2. print("My name is",name,"and age is",age)
3. printme(name = "john") #the variable age is not passed into the function however th
e default value of age is considered in the function
Output:
Example 2
1. def printme(name,age=22):
2. print("My name is",name,"and age is",age)
3. printme(name = "john") #the variable age is not passed into the function however th
e default value of age is considered in the function
4. printme(age = 10,name="David") #the value of age is overwritten here, 10 will be pr
inted as age
Output:
However, at the function definition, we have to define the variable with * (star) as
*<variable - name >.
Example
1. def printme(*names):
2. print("type of passed argument is ",type(names))
3. print("printing the passed arguments...")
4. for name in names:
5. print(name)
6. printme("john","David","smith","nick")
Output:
john
David
smith
nick
Scope of variables
The scopes of the variables depend upon the location where the variable is being
declared. The variable declared in one part of the program may not be accessible to
the other parts.
In python, the variables are defined with the two types of scopes.
1. Global variables
2. Local variables
The variable defined outside any function is known to have a global scope whereas
the variable defined inside a function is known to have a local scope.
Example 1
1. def print_message():
2. message = "hello !! I am going to print a message." # the variable message is loc
al to the function itself
3. print(message)
4. print_message()
5. print(message) # this will cause an error since a local variable cannot be accessible
here.
Output:
print(message)
Example 2
1. def calculate(*args):
2. sum=0
3. for arg in args:
4. sum = sum +arg
5. print("The sum is",sum)
6. sum=0
7. calculate(10,20,30) #60 will be printed as the sum
8. print("Value of sum outside the function:",sum) # 0 will be printed
Output:
The sum is 60
Value of sum outside the function: 0
Lambda Function
Python lambda function doesn’t have any return statement.Ithas only a single expression
which is always returned by default.The Python lambda function is anonymous as it is a
function without a def keyword and name. To create a Python lambda function, we have to
use the lambda keyword.
The Python lambda function accepts any number of arguments but use only one expression.
For instance, lambda a, b: a + b. Here, a and b are the arguments accepted by the lambda
function. a + b is the expression.
Both lambda function and regular function returns the same result. However, the
regular function needs a def keyword, function name, and a return value.
Whereas, lambda function does not need any of them. By default, it returns the
expression result.
Modules & Packages
Module is a logical group of functions, classes, variables in a single python file saved
with .pyextension. In other words, we can also say that a python file is a module. We
have seen few examples of built-in modules, which are used in the program by
import statement. Python provides many built-in modules. We can also create our
own module.
A major benefit of a module is that functions, variable or objects defined in one
module can be easily used by other modules or files, which make the code re-usable.
A module can be created like any other python file. Name of the module is the same
as the name of a file. Let us create out first module- series.py.
Our module is successfully created. Now let us test our module by importing in some
other file and check whether it is working or not. For verifying that, in a new file, two
steps are needed to be done.
import Series
Series.fibonacci(2, 10)
Importing a module:
Importing Complete module: In this method, we can import the whole module all
together with a single import statement. In this process, after importing the module,
each function (or variable, objects etc.) must be called by the name of the module
followed by dot (.) symbol and name of the function.
import module
module.function_name()
Packages like modules are also used to organize the code in a better way. A package
is a directory which contains multiple python modules. It is used to group multiple
related python modules together. A python package in addition to modules must
contain a file called __init__.py. This file may be empty or contains data like other
modules of package.
File __init__.py
Let us create a package namedpack and within this package create two modules
first.py and second.py
Python standard library provides number of built-in modules. They are automatically
loaded when an interpreter starts. It should be noted that before using any module,
it should be imported first. Some of the commonly used library modules are-
sys
os
math
random
statistics
Module Attributes
There are some attributes or functions that work for every module whether it is built-
in library module or custom module. These attributes help in smooth operations of
these modules.
Some of them are explained below:
OS MODULE
This is a module responsible for performing many operating system tasks. It
provides functionality like- creating directory, removing directory, changing
directory, etc.Some of the functions in os modules are given in the table below. It
should be noted that before using these functions, the module should be imported.
SYS MODULE
This module contains various variables and functions that can manipulate python
runtime environment. Some of them are listed intable given below:
MATH MODULE
This module provides various mathematical functions and constant variables. It
includes logarithmic, trigonometric functions etc. Some of the functions are listed in
table below:
STATISTICS MODULE
This module contains various functions used in statistics. These functions are widely
used for data analysis or data science.
File Operation
Main memory is volatile in nature, hence, nothing can be stored permanently. File
handling is a very important functionality which must be provided by any language to
deal with this problem. Inputs can be taken from files instead of users, output can be
displayed and saved permanently in files which can further be accessed later and
appended or updated. All these functionalities come under file handling. Like other
languages, python also provides various built-in functions for file handling
operations.
There are two types of files supported by python- Binary and Text.
Binary files – These are the files that can be represented as 0’s and 1’s. These files
can be processed by applications knowing about the file’s structure. Image files are
example of binary files.
Text files – These files are organized as sequence of characters. Here, each line is
separated by a special end of line character. Any file handling operation can be
performed in three steps-
1. Opening a file
2. Operating on file – read, write , append etc.
3. Closing a file
1. Opening a file:
A file can be opened in a Python using built-in function open(). By default the files
are opened in read text (‘r’) file mode.
Syntax of open() function
Where,
File_name.ext - is the name of the file to be opened and ext is the extension of file.
file – is the object returned by the function. This object can be used for further
operations on file.
The possible mode of operations in python –
2. Operating on file
There are various operations –
Reading from a file: There are many ways to read from a file. Given below are the
functions available for reading
from a file.
In the below table assume
that file is the object returned
from open() function.
Writing to a file: Similar to read operations, functions are there in python to write
data to file.
Operations on file: Python allows many other operations to be done in with files.
Listed below are some functions used for file handling.
Closing a file: After completing all the operations on file, it must be closed properly.
This step frees up the resources and allows graceful termination of file operations.
file.close()
It may be noted that the file that we want to read or write, may be present in some
other directory or folder. In that case, we can give absolute or relatative path of that
file along with its name, shown in the example below. The path separated by \ must
be proceeded by one more \ (backslash) to turn-off special feature of this character.
If the file to be read or written is in the same folder, in which python program is
present, we need not give its path.
Creating a file
For creation of new file, the file can be opened in ‘w’ mode. If the file already exists,
the contents can be overwritten. Also, if we want to be sure that no existing file gets
overwritten, then ‘x’ mode can be used to create new file. If the file already exists, it
will show error message. Given below is the example to open a file and write
contents to it.