0% found this document useful (0 votes)
35 views50 pages

Python QP Solution Jan-2023

Uploaded by

ytgenius05
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)
35 views50 pages

Python QP Solution Jan-2023

Uploaded by

ytgenius05
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/ 50

SECTION-A

(Short Answer Type Questions)

1. (A) Briefly explain about Python IDLE.

Ans:IDLE stands for Integrated Development and Learning Environment. The story
behind the name IDLE is similar to Python. Guido Van Rossum named Python after
the British comedy group Monty Python while the name IDLE was chosen to pay
tribute to Eric Idle, who was one of the Monty Python's founding members. IDLE
comes bundled with the default implementation of the Python language since the
01.5.2b1 release. It is packaged as an optional part of the Python packaging with
many Linux, Windows, and Mac distributions.

IDLE is not available by default in Python distributions for Linux. It needs to be


installed using the respective package managers. Execute the following command
to install IDLE on Ubuntu:
$ sudo apt-get install idle
IDLE is used to execute statements similar to Python Shell. IDLE is used to
create, modify, and execute Python code. IDLE provides a fully-featured text
editor to write Python scripts and provides features like syntax highlighting,
auto-completion, and smart indent. IDLE also has a debugger with features such
as stepping and breakpoints.

Some of the key features it offers are:

 Python shell with syntax highlighting,


 Multi-window text editor,
 Code autocompletion,
 Intelligent indenting,
 Program animation and stepping which allows one line of code to run at a time
helpful for debugging,
 Persistent breakpoints,
 Finally, Call stack visibility.

How does it work?


The shell is the default mode of operation for Python IDLE. When you click on the icon
to open the program, the shell is the first thing that you see:
In IDLE, we write code line by line. Each specific line will handle one thing, and you can
type whatever you want in that line and press enter to execute it. IDLE works more like
a terminal or command prompt - You write one line, press enter, it executes.

1. (B) Explain about Logical operator and Boolean expression.


Ans: Operators are used to perform operations on values and variables. These are
the special symbols that carry out arithmetic and logical computations. The value
the operator operates on is known as Operand.
In Python, Logical operators are used on conditional statements (either True or
False). They perform Logical AND, Logical OR and Logical NOT operations.

OPERATOR DESCRIPTION SYNTAX

and Logical AND: True if both the operands are true x and y

or Logical OR: True if either of the operands is true x or y

not Logical NOT: True if operand is false not x

Logical AND operator


Logical operator returns True if both the operands are True else it returns False.
Example:
a =10
b =12
c =0

ifa andb andc:


print("All the numbers have boolean value as True")
else:
print("Atleast one number has boolean value as False")

Logical OR operator
Logical or operator returns True if either of the operands is True.
# Python program to demonstrate
# logical or operator

a =10
b =-10
c =0

ifa > 0orb > 0:


print("Either of the number is greater than 0")
else:
print("No number is greater than 0")

ifb > 0orc > 0:


print("Either of the number is greater than 0")
else:
print("No number is greater than 0")

Logical not operator


Logical not operator work with the single boolean value. If the boolean value is
True it returns False and vice-versa.
# Python program to demonstrate
# logical not operator

a =10

ifnota:
print("Boolean value of a is True")

ifnot(a%3==0ora%5==0):
print("10 is not divisible by either 3 or 5")
else:
print("10 is divisible by either 3 or 5")

Boolean Expression:
It is an expression that always yields two values either true or false when
evaluated. If the condition is true then it will return true or false and vice versa.
Let’s take one simple example that will clear the concept of Boolean expression so
the expression (5>2) i.e. 5 greater than 2 as we can see it is true that means 5 is
greater than 2 therefore the result will be true as we can see the expression yields
true as value, therefore, it is called Boolean expression.

1. (C) Write a program to check a given number is prime or not. Number


is given by user.

Ans:# Program to check if a number is prime or not

# TO TAKE INPUT FROM THE USER


num = int(input("PLEASE ENTER A NUMBER: "))

# DEFINE A flag VARIABLE


flag = False

if num == 1:
print(num, "IS NOT A PRIME NUMBER")
elif num > 1:
# CHECK FOR FACTORS
for i in range(2, num):
if (num % i) == 0:
# IF FACTOR IS FOUND, SET flag TO True
flag = True
# break OUT OF LOOP
break

# CHECK IF flag IS True


if flag:
print(num, "IS NOT A PRIME NUMBER")
else:
print(num, "IS A PRIME NUMBER")

1. (D) Write a program to print Armstrong numbers from 100 to 200.


Ans:
# WAP to print Armstrong numbers
lower = int(input("PLEASE ENTER LOWER RANGE: "))
upper = int(input("PLEASE ENTER UPPER RANGE: "))

for num in range(lower,upper + 1):


sum = 0
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp //= 10
if num == sum:
print(num)

1. (E) Write the difference between List and Tuple.

Ans: Both of these are basically the classes of a data structure, but there is a
significant difference between list and tuple in Python. Here, the list is very
dynamic, but a tuple consists of static characteristics. Let us know a bit more about
both of these.

What is a List?
It is like an array that we declare in another language. A list doesn’t need to be
always homogeneous- making it one of the most powerful tools used in Python. It
exists as a type of container in the data structures in Python. We use it for storing
multiple data and information at the very same time. The lists are very useful tools
that help in preserving a data and information sequence and iterating further over
it.
What is a Tuple?
It is also a sequence data type capable of containing elements of multiple data
types, and they are immutable. In simpler words, a tuple refers to a collection of
various Python objects that stay separated by commas. A tuple is comparatively
much faster than a list because it is static in nature.
Difference Between List and Tuple in Python

Parameters List Tuple

Type A list is mutable in nature. A tuple is immutable in nature.

Consumption of It is capable of consuming more It is capable of consuming less


Memory memory. memory.

Time The list iteration is more time- The tuple iteration is less time-
Consumption consuming. It is comparatively much consuming. It is comparatively much
slower than a tuple. faster than a list.

Methods It comes with multiple in-built methods. These have comparatively lesser
built-in methods in them.

Appropriate It is very helpful in the case of deletion It is comparatively helpful in the


Usage and insertion operations. case of read-only operations, such as
accessing elements.

Prone to Error The list operations are comparatively Any such thing is hard to take place
much more error-prone. Some in a tuple. The tuple operations are
unexpected changes and alterations very safe and not very error-prone.
may take place.
1. (F) What is module and package in Python?

Ans: Module: A module allows you to logically organize your Python code.
Grouping related code into a module makes the code easier to understand and
use. A module is a Python object with arbitrarily named attributes that you can
bind and reference.
Simply, a module is a file consisting of Python code. A module can define
functions, classes and variables. A module can also include runnable code.

Why do we need module?


As our program grows bigger, it may contain many lines of code. Instead of
putting everything in a single file, we can use modules to separate codes in
separate files as per their functionality. This makes our code organized and
easier to maintain.

Modular programming refers to the process of breaking a large, unwieldy


programming task into separate, smaller, more manageable subtasks or
modules. Individual modules can then be cobbled together like building blocks
to create a larger application.

Types of Module:
A module is classified into two major categories:
1. Built-in Modules
2. User-defined/Customized Modules

Package in Python
Suppose you have developed a very large application that includes many
modules.As the number of modules grows, it becomes difficult to keep track of
them all ifthey are dumped into one location. This is particularly so if they have
similar namesor functionality. You might wish for a means of grouping and
organizing them.

Packages allow for a hierarchical structuring of the module namespace using


dotnotation. In the same way that modules help avoid collisions between
globalvariable names, packages help avoid collisions between module names.
Creating a package is quite straightforward, since it makes use of the operating
system’s inherent hierarchical file structure.
1. (G) What is generator in Python? Explain with example.

Ans: Generators in Python:


Generators in python are functions that create an iterator.
The generator follows the same syntax as a function, but instead of writing return,
we write yield whenever it needs to return something.
Creating a generator function

Let’s say we need to generate the first 10 perfect squares starting from 1.
Syntax:
def perfect_square():
num = 1
while(num <= 10):
yield (num * num)
num += 1
Let’s go through the code line by line:

 def perfect_square(): A normal start of a function block.


 num = 1: The only memory we need to generate any number of perfect squares.
 while(num <= 10): We only need to generate 10 perfect squares.
 yield(num * num): The most important and noticeable distinction from a normal
function in Python. This is similar to a return statement in that it returns
the generated perfect square. Notice that I’m saying generated because all the
perfect squares this function returns are generated and not retrieved from memory.
 num += 1: Incrementing so that it yields the next perfect square.

Looking at the behavior of this generator. Simply calling it like a function will return
a generator object.

Squares is a generator object


This object is what we have to use. Calling next() on this will yield the first value,
calling next() again will yield the second value and so on till the tenth value.
After that, calling next() will attempt to yield another value, but because the
function is over, it will raise a StopIteration error.

Applications of Generators:
Suppose we create a stream of Fibonacci numbers, adopting the generator
approach makes it trivial; we just have to call next(x) to get the next Fibonacci
number without bothering about where or when the stream of numbers ends. A
more practical type of stream processing is handling large data files such as log
files. Generators provide a space-efficient method for such data processing as
only parts of the file are handled at one given point in time. We can also use
Iterators for these purposes, but Generator provides a quick way (We don’t need
to write __next__ and __iter__ methods here).

1. (H) Why do we need a date class in Python?


Ans: datetime.date Class:
You can instantiate date objects from the date class. A date object represents a
date (year, month and day).

Example-1: Date object to represent a date


import datetime
d = datetime.date(2019, 4, 13)
print(d)
When you run the program, the output will be:
2019-04-13

The constructor takes three arguments: year, month and day.


The variable a is a date object.
We can only import date class from the datetime module. Here's how:
from datetime import date
a = date(2019, 4, 13)
print(a)

Example-2: Get current date


You can create a date object containing the current date by using a classmethod
named today(). Here's how:
from datetime import date
today = date.today()

print("Current date =", today)

Example-3: Print today's year, month and day


We can get year, month, day, day of the week etc. from the date object easily.
Here's how:
from datetime import date
# date object of today's date
today = date.today()
print("Current year:", today.year)
print("Current month:", today.month)
print("Current day:", today.day)
1. (I) How can you raise an exception in Python? Explain with example.
Ans: We have known that Python interpreter raises the exception whenever it
tries to execute an invalid code. Raising an exception is also like to stop
running the code in function or move the program execution to the
except statement. All these exceptions are wrapped in objects and are created
from the classes. Therefore, the programmer can raise this kind of exception
using raise keyword. It can also be used to force an exception to occur, that
means it raises an exception.

It causes an exception to be generated explicitly. Built-in errors are raised


implicitly. However, a built-in or custom exception can be forced during
execution.

Syntax:The syntax to raise an exception is following as:

raise exception_type(value)
Where exception_type is the class of exception

Example-1: Write a program to raise an exception.


def division_Op(a, b):
try:
if(b==0):
raiseArithmeticError(“YOU CANNOT DIVIDE A NUMBER BY
ZERO”)
else:
c = a/b
exceptZeroDivisionError:
print(“Something is Wrong.”)
raise
print(division_Op(10,0)) # Function Call

OUTPUT:
Traceback (most recent call last)
ArithmeticError: YOU CANNOT DIVIDE A NUMBER BY ZERO
SECTION-B
(Long Answer Type Questions)

2. What is Python programming cycle? Mention what are the rules for
local and global variable in Python. How can you share global variables
across modules?

Ans: Python Programming Cycle


Python is an interpreted, high-level, general-purpose programming language. A
python programming cycle consists of below main steps.
1. Design a solution
2. Write a code
3. Test the code
4. Debug the code
5. Repeat 2-4 until the program runs correctly.

1. Design the solution for the problem


Designing the solution for the problem can be done in many ways. One way to do
this is to think about what the problem is and what the possible solution might be.

The best way to design a solution is to think about how you would solve the
problem if you were the computer. It is known as “thinking like a computer.”

You will also determine the program’s structure and the algorithms you will use to
solve the problem.

It is important to design the solution before starting to code. It will give a clear idea
of what you are trying to achieve. If you start coding without a plan, it is easy to
get lost and end up with a mess of code that does not work.

Once you have a general idea of the solution, you can start coding it in python.

2. Write the code


This step is known as “coding.” This step aims to turn the design into a set of
instructions that a computer can understand.
Here you will start coding, you will take your pre-writing plans and turn them into
working code.

Python programming has a specific structure and style that all programmers must
follow. The first stage of writing a Python program is to create a source code.
This source code is a text file containing the Python interpreter’s instructions. The
source code must be written in a text editor, such as Notepad. or in the IDE, such
as Pycharm, Anaconda, or Visual Studio. The source code file must be saved with
the .py extension.
After the code has been written, the next step is to test the code. This step is
known as “Testing.” This step aims to make sure that the code solves the problem.

3. Test The Code


Testing is an essential part of the programming process. It can help you find errors
in your code and give you a chance to debug or fix them.

You might test your code manually by running it and trying it out. Here you run the
code and check the output. If the output is not what was expected, the code is
modified and tested again until it produces the desired results.

Another method is to use a tool. Python has a few options. The unittest module is
a built-in Python library that provides a rich set of tools for testing python code.
The nose package is also a popular third-party library for running tests.
If you’re just getting started with testing, a good place to start is with the Python
docs on unittest. This page gives a good overview of the module and how to use it.
The nose is another popular testing tool for python. Nose is similar to unittest
in that it provides a rich set of features for writing and running tests.
Lastly, No matter which testing tool you choose, remember that testing is
essential for the development process. Taking the time to write and run tests will
save you a lot of time in the long run.

4. Debug the code


Having a good understanding of how to debug your code is also crucial. It will save
you a lot of time and frustration in the long run. There are a few different ways to
debug Python code.

The first way to debug your code is to use a python debugger. A Python
debugger is a tool that allows you to step through your code line by line. It is a
great way to see what your code is doing and find any errors.
The second way to debug your code is to use the Python console. The Python
console is a REPL (read-eval-print loop) that allows you to type in Python code and
see the results immediately. It is a great way to test small code pieces and see
what your code is doing.

The third way to debug your code is to use the Python logging module. The
Python logging module allows you to add logging statements to your code. It is a
great way to track what your code is doing and find any errors.
The fourth way to debug your code is to use a Python profiler. A Python
profiler is a tool that allows you to see how much time your code is spending on
each function. It is a great way to find bottlenecks in your code.
No matter what method you use to debug your code, the important thing is that
you take the time to do it, as it can save a lot of future time and frustration.

5. Repeat steps 2-4 until the program runs correctly


It is not a step involved in the python programming cycle. It defines the process or
the working loop. You write code, test it and find a bug that leads to a program
malfunctioning. And you solve that by modifying your existing code and going
through the same cycle again. This process is repeated until you develop the
correct code that solves the problem statements.

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

Understanding global variables in Python


In Python, a conventional global variable is only used to share a value within
classes and functions. A variable- once declared as a global within a function or
class can then be modified within the segment.
num = 1

def increment():
global num
num += 1

The above code would allow the variable 'num' to be used within that function,
whereas if you were to omit the global statement, it would be undefined.

If you were to attempt to use this logic to declare a global variable from another
class however, it would not work as it would in other languages such as Java or
C++.

For example, if we had one class with a variable that needed to be accessed from
within another imported class, there would be no way for us to access this variable
using the global keyword:

main.py
import test

num = 1

test.increment()

test.py
def increment():
global num
num += 1 # num here would still be undefined

As you can see above, even though we try to access 'num' as a global within the
increment() function after it has been given a value in main.py, it will still not be
defined and will result in an error.

Sharing global variables between files/modules in Python


Even though the global keyword is conventionally only used to access variables
from within the same module, there are ways to use it in order to share variables
between files. For example, we could take influence from PHP and create something
similar to the "superglobals" variables.

To do this, you can create a new module specifically for storing all the global
variables your application might need. For this you can create a function that will
initialize any of these globals with a default value, you only need to call this
function once from your main class, then you can import the globals file from any
other class and use those globals as needed.

For example, let's create a function similar to the example above that will
increment a global variable. For this we'll need 3 classes to prove the concept; a
main class, a class containing our increment function and a class containing the
globals.

globals.py

def initialize():
global num
num = 1

main.py

import globals
import test

if __name__ == "__main__":
globals.initialize()
print( globals.num ) # print the initial value
test.increment()
print( globals.num ) # print the value after being modified within test.py

test.py
import globals

def increment():
globals.num += 1

When we run main.py the output will be:

1
2

As you can see, once we've initialized the global variable in globals.py, we can then
access 'num' as a property from any other module within the application and it will
retain its value.

3. Explain the need for continue, break and pass statements. Write a
program in Python where these three statements are implemented.

Ans: The break Statement:


The break statement is used to exit the loop when a condition is triggered or
met.

Syntax: break

Example-1: # To Check And Print Whether A Specific Number Found In


The List
L1 = [1, 2, 3, 4, 5, 6]
n=2
found = False
for i in L1:
if (n == i):
found = True
break
print(n, “is found In the list L1.”)

Example-2:
L1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
total_even = 0
for i in L1:
if(i%2!=0):
break
total_even = total_even + i
else:
print(“Sum of Even Numbers = ”, total_even)
output: Sum of Even Numbers = 30

We can also terminate the while loop using the break statement.

Example:
# program to find first 5 multiples of 6
i=1
while i <= 10:
print('6 * ',(i), '=',6 * i)

if i >= 5:
break
i=i+1

The continue Statement:


The continue statement is used to skip the current iteration of the loop and the
control flow of the program goes to the next iteration.
We can use continue statement inside a for loop to skip or ignore the execution
of body of loop for a specific condition.

Syntax: continue

Working of Python continue Statement

Example: To Print Only Sum of Positive Numbers If Any Negative


Number Is Found Then Skip It
L1 = [1, 2, -3, 4, -5, 6]
Sum_positives = 0
for i in L1:
if (i<0):
continue
sum_positives = sum_positives + i
print(“Sum of Positive Numbers = ”, sum_positives)

Python continue Statement with for Loop


We can use the continue statement with the for loop to skip the current iteration of
the loop. Then the control of the program jumps to the next iteration. For example,
for i in range(5):
if i == 3:
continue
print(i)

Output:
0
1
2
3
4

Python continue Statement with while Loop


In Python, we can also skip the current iteration of the while loop using the
continue statement. For example,

# program to print odd numbers from 1 to 10

num = 0

while num < 10:


num += 1

if (num % 2) == 0:
continue

print(num)

Output:
1
3
5
7
9

Pass Statement:
The pass statement is used when a statement is required syntactically but you
do not want any command or code to execute.
The pass statement is used as a placeholder for future code.
When the pass statement is executed, nothing happens, but you avoid getting an
error when empty code is not allowed.
Empty code is not allowed in loops, function definitions, class definitions, or in if
statements.

The pass statement is a null statement. But the difference between pass and
comment is that comment is ignored by the interpreter whereas pass is not
ignored.

Syntax: pass

Example

Using the pass keyword in a function definition:

def myfunction():
pass

Example

Using the pass keyword in a class definition:

class Person:
pass

Example

Using the pass keyword in an if statement:

a = 33
b = 200

if b > a:
pass

Temporary Uses of pass


There are many situations in which pass can be useful to you while you’re
developing, even if it won’t appear in the final version of your code. Much like
scaffolding, pass can be handy for holding up the main structure of your program
before you fill in the details.
It might sound strange to write code that will be deleted later, but doing things this
way can accelerate your initial development.
4. What is dictionary in Python? Write a Python program to convert a
given dictionary into a list of lists.

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

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.

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

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

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}

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}

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


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}

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}

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

5. Explain about string data type in Python. What is slicing and


indexing? Explain about negative indexing. Give four examples of slicing
and indexing with negative indexing.

Ans: Strings in Python are identified as a contiguous set of characters


represented in the quotation marks. Python allows for either pairs of single or
double quotes. Subsets of strings can be taken using the slice operator ([ ] and
[:] ) with indexes starting at 0 in the beginning of the string and working their
way from -1 at the end.

Strings in python are surrounded by either single quotation marks, or double


quotation marks.

'hello' is the same as "hello".

You can display a string literal with the print() function:

Example

print("Hello")
print('Hello')

Assign String to a Variable

Assigning a string to a variable is done with the variable name followed by an equal
sign and the string:

Example

a = "Hello"
print(a)

Multiline Strings

You can assign a multiline string to a variable by using three quotes:


Example

You can use three double quotes:

a = """Lorem ipsum dolor sit amet,


consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)

Strings are Arrays:

Like many other popular programming languages, strings in Python are arrays of
bytes representing unicode characters.

However, Python does not have a character data type, a single character is simply a
string with a length of 1.

Square brackets can be used to access elements of the string.

Example

Get the character at position 1 (remember that the first character has the position
0):

a = "Hello, World!"
print(a[1])

String Length

To get the length of a string, use the len() function.

Example

The len() function returns the length of a string:

a = "Hello, World!"
print(len(a))

Check String

To check if a certain phrase or character is present in a string, we can use the


keyword in.
Example

Check if "free" is present in the following text:

txt = "The best things in life are free!"


print("free" in txt)

Example

Print only if "free" is present:

txt = "The best things in life are free!"


if "free" in txt:
print("Yes, 'free' is present.")

Check if NOT

To check if a certain phrase or character is NOT present in a string, we can use the
keyword not in.

Example

Check if "expensive" is NOT present in the following text:

txt = "The best things in life are free!"


print("expensive" not in txt)

Indexing Strings:
Indexing allows you to access individual characters in a string directly by
using a numeric value. String indexing is zero-based: the first character in
the string has index 0, the next is 1, and so on. In this lesson, you’ll learn
string indexing syntax and practice with several examples:
myString = "PythonForbeginners" index = 0
character = myString[index] print("Character at index {} in the string '{}' is
{}.".format(index, myString, character)) index = 1
character = myString[index] print("Character at index {} in the string '{}' is
{}.".format(index, myString, character)) index = 2

character = myString[index] print("Character at index {} in the string '{}' is


{}.".format(index, myString, character)) index = 3
character = myString[index] print("Character at index {} in the string '{}' is
{}.".format(index, myString, character)) index = 17
character = myString[index] print("Character at index {} in the string '{}' is
{}.".format(index, myString, character))
Output:
Character at index 0 in the string 'PythonForbeginners' is P.
Character at index 1 in the string 'PythonForbeginners' is y.
Character at index 2 in the string 'PythonForbeginners' is t.
Character at index 3 in the string 'PythonForbeginners' is h.
Character at index 17 in the string 'PythonForbeginners' is s.
Slicing

You can return a range of characters by using the slice syntax.

Specify the start index and the end index, separated by a colon, to return a part of
the string.

Example

Get the characters from position 2 to position 5 (not included):

b = "Hello, World!"
print(b[2:5])

Slice From the Start

By leaving out the start index, the range will start at the first character:

Example

Get the characters from the start to position 5 (not included):

b = "Hello, World!"
print(b[:5])

Slice To the End

By leaving out the end index, the range will go to the end:

Example

Get the characters from position 2, and all the way to the end:

b = "Hello, World!"
print(b[2:])
Python - Modify Strings
Python has a set of built-in methods that you can use on strings.
Upper Case
Example

The upper() method returns the string in upper case:

a = "Hello, World!"
print(a.upper())

Lower Case
Example

The lower() method returns the string in lower case:

a = "Hello, World!"
print(a.lower())

Remove Whitespace

Whitespace is the space before and/or after the actual text, and very often you
want to remove this space.

Example

The strip() method removes any whitespace from the beginning or the end:

a = " Hello, World! "


print(a.strip()) # returns "Hello, World!"

Replace String
Example

The replace() method replaces a string with another string:

a = "Hello, World!"
print(a.replace("H", "J"))

Split String

The split() method returns a list where the text between the specified separator
becomes the list items.
Example

The split() method splits the string into substrings if it finds instances of the
separator:

a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']
SECTION-C
(Long Answer Type Questions)

6. Explain about functions in Python. Write a Python program using function to


find the roots of a quadratic equation.

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

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.

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

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.

Returning Single Value From Function Definition To Function Call

Example: To Find And Print The Maximum And Minimum Value Between Two
Numbers

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

Returning Multiple Value From Function Definition To Function Call


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

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

WAP to print roots of a quadratic equation ax2 + bx + c, the discriminant d, is


b2-4ac.

#Function To Compute Roots x1 And x2


def Find_Roots(a, b, c):

x1 = (-b + math.sqrt(b*b-4*a*c))/2*a
x2 = (-b - math.sqrt(b*b-4*a*c))/2*a
print(“Root X1 =”, x1)
print(“Root X2 =”, x2)

a = int(input(“PLEASE ENTER VALUE OF a: ”))


b = int(input(“PLEASE ENTER VALUE OF a: ”))
c = int(input(“PLEASE ENTER VALUE OF a: ”))

Find_Roots(a, b, c)
7. What is lambda function? Explain the features of lambda function. Write a
Python program to calculate the average value of numbers in a given tuple
of tuples using lambda.

Ans: 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).

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

Characteristics of Lambda Function:


Lambda function takes an unlimited number of arguments however has only one
expression. This expression returns the result when the lambda function is called.
2. Since it contains only one expression which returns the result by default, it does
not require the return statement.

Let us consider an example of lambda function:

res = lambda x: x + 5
print(res(10))

Difference between lambda functions and user-defined functions

Lambda functions are anonymous functions which mean a function is defined using
a lambda keyword and without a name, whereas a user-defined function is defined
using a def keyword and has a function name.

Lambda functions with List comprehension List comprehension is a well-ordered


way to create a new list from an existing list.
Example:

numbers=[1,2,3]
square_numbers=[number ** 2 for number in numbers]
print(square_numbers)

Write a Python program to calculate the average value of the numbers


in a given tuple of tuples .
def average_tuple(nums):
result = [sum(x) / len(x) for x in zip(*nums)]
return result

nums = ((10, 10, 10, 12), (30, 45, 56, 45), (81, 80, 39, 32), (1, 2, 3, 4))
print ("Original Tuple: ")
print(nums)
print("\nAverage value of the numbers of the said tuple of
tuples:\n",average_tuple(nums))

nums = ((1, 1, -5), (30, -15, 56), (81, -60, -39), (-10, 2, 3))
print ("\nOriginal Tuple: ")
print(nums)
print("\nAverage value of the numbers of the said tuple of
tuples:\n",average_tuple(nums))

Output:
Original Tuple:
((10, 10, 10, 12), (30, 45, 56, 45), (81, 80, 39, 32), (1, 2, 3, 4))

Average value of the numbers of the said tuple of tuples:


[30.5, 34.25, 27.0, 23.25]

Original Tuple:
((1, 1, -5), (30, -15, 56), (81, -60, -39), (-10, 2, 3))

Average value of the numbers of the said tuple of tuples:


[25.5, -18.0, 3.75]
8. What is time module? Explain five functions of time module with example.
Write a Python program to subtract five days from current date.

Ans: Time Module:


Python time module allows to work with time in Python. It allows functionality
like getting the current time, pausing the Program from executing, etc. So before
starting with this module we need to import it.
datetime.time:
A time object instantiated from the time class represents the local time.

Example: Time object to represent time


from datetime import time
# time(hour = 0, minute = 0, second = 0)
a = time()
print("a =", a)
# time(hour, minute and second)
b = time(11, 34, 56)
print("b =", b)
# time(hour, minute and second)
c = time(hour = 11, minute = 34, second = 56)
print("c =", c)
# time(hour, minute, second, microsecond)
d = time(11, 34, 56, 234566)
print("d =", d)
When you run the program, the output will be:
a = 00:00:00
b = 11:34:56
c = 11:34:56
d = 11:34:56.234566 7
Example: Print hour, minute, second and microsecond
Once you create a time object, you can easily print its attributes such as hour,
minute etc.
from datetime import time
a = time(11, 34, 56)
print("hour =", a.hour)
print("minute =", a.minute)
print("second =", a.second)
print("microsecond =", a.microsecond)
When you run the example, the output will be:
hour = 11
minute = 34
second = 56
microsecond = 0
Notice that we haven't passed microsecond argument. Hence, its default value 0
is printed.

Importing time module


The time module comes with Python’s standard utility module, so there is no
need to install it externally. We can simply import it using the import statement.
import time
What is epoch?
The epoch is the point where the time starts and is platform-dependent. On
Windows and most Unix systems, the epoch is January 1, 1970, 00:00:00 (UTC),
and leap seconds are not counted towards the time in seconds since the epoch.

Getting time string from seconds


time.ctime() function returns a 24 character time string but takes seconds as
argument and computes time till mentioned seconds. If no argument is passed,
time is calculated till the present.
Example: Getting time string from seconds

import time

# getting current time by passing


# the number of seconds since epoch
curr = time.ctime(1627908313.717886)
print("Current time:", curr)

Output
Current time: Mon Aug 2 12:45:13 2021
Delaying Execution of programs
Execution can be delayed using time.sleep() method. This method is used to halt
the program execution for the time specified in the arguments.
Example: Delaying execution time of programs in Python.

import time

for i in range(4):

# using sleep() to halt execution


time.sleep(1)
print(i)

Output
0
1
2
3

time.localtime() method
localtime() method returns the struct_time object in local time. It takes the
number of seconds passed since epoch as an argument. If the seconds parameter
is not given then the current time returned by time.time() method is used.

Example: Getting local time from epoch

# importing time module


import time

# Convert the current time in seconds


# since the epoch to a
# time.struct_time object in Local time
obj = time.localtime(1627987508.6496193)

print(obj)

Output
time.struct_time(tm_year=2021, tm_mon=8, tm_mday=3, tm_hour=16,
tm_min=15, tm_sec=8, tm_wday=1, tm_yday=215, tm_isdst=0)
time.mktime() method
time.mktime() is the inverse function of time.localtime() which converts the time
expressed in seconds since the epoch to a time.struct_time object in local time.

Example: Converting the struct_time object to seconds since epoch

# importing time module


import time

obj1 = time.gmtime(1627987508.6496193)

# Convert the time.struct_time


# object to local time expressed in
# seconds since the epoch
# using time.mktime() method
time_sec = time.mktime(obj1)

# Print the local time in seconds


print("Local time (in seconds):", time_sec)

Output
Local time (in seconds): 1627987508.0

time.gmtime() method
time.gmtime() is used to convert a time expressed in seconds since the epoch to
a time.struct_time object in UTC in which tm_isdst attribute is always 0. If the
seconds parameter is not given then the current time returned by time.time()
method is used.

Example: Use of time.gmtime() method

# importing time module


import time

# Convert the current time in seconds


# since the epoch to a
# time.struct_time object in UTC
obj = time.gmtime(1627987508.6496193)

# Print the time.struct.time object


print(obj)

Output
time.struct_time(tm_year=2021, tm_mon=8, tm_mday=3, tm_hour=10,
tm_min=45, tm_sec=8, tm_wday=1, tm_yday=215, tm_isdst=0)
time.strftime() method
time.strftime() function converts a tuple or struct_time representing a time as
returned by gmtime() or localtime() to a string as specified by the format
argument. If t is not provided, the current time as returned by localtime() is
used. The format must be a string. ValueError is raised if any field in t is outside
of the allowed range.

Example: Converting struct_time object to a string using strftime() method

from time import gmtime, strftime

# using simple format of showing time


s = strftime("%a, %d %b %Y %H:%M:%S",
gmtime(1627987508.6496193))
print(s)

Output
Tue, 03 Aug 2021 10:45:08

Write a Python program to subtract five days from the current date.
from datetime import date, timedelta
dt = date.today() - timedelta(5)
print('Current Date :',date.today())
print('5 days before Current Date :',dt)

Output:
Current Date : 2017-05-05
5 days before Current Date : 2017-04-30
9. What is exception? Explain about try, except, else and finally blocks used in

exception handling. Write a user defined exception using exception class.

Ans: WHAT IS AN EXCEPTION?


An exception in Python is an incident that happens while executing a program
that causes the regular course of the program’s commands to be disrupted.
When a code comes across a condition that it can’t handle, it raises an
exception.
Hence, an exception is a special kind of error (logical or run-time) that occurs
during the run-time of the program.

Examples:
1. If a user attempts to open a file that doesn’t exist, then it produces
“FileNotFoundError ”.

2. If a user tries to access an index of a list which is out-of-bound, that means


to access the index of list which is more or less than the given size of list, then
it produces ‘IndexError ’.

3. If a user tries to divide a number by zero, then it produces


‘ZeroDivisionError ’.
Thus, an exception is the condition that prevents execution of statements of a
program in Python to proceed normally. Thus, if the exceptions are not handled
properly, the programs will be terminated abnormally . In order to run the
program without termination, there is always an immense need of a mechanism
called exception handling .

EXCEPTION VERSUS SYNTAX ERROR:


When the interpreter identifies a statement that has an error while creating a
program, a syntax error occurs.
Consider the following case:

Case-1: In Case of Syntax Error


str1 = “Welcome To Python”
for s in str1:
if(s!=o: # missing of closed round bracket
print(s)
SyntaxError: invalid syntax
Explanation:
Clearly, there is a missing of closed round bracket in above condition and hence such
kind of error is to be known as syntactical error.

Case-2: In Case of Exception(NameError)


str1 = “Welcome To Python”
for s in str1:
if(s!=o): # ‘o’ is not defined
print(s)
NameError: name ‘o’ is not defined
Explanation:
Clearly, it is a NameError in this situation as name ‘o’ is not defined. we encountered
an exception after executing this code. When syntactically valid Python code produces
an error, then such a specialized error is an exception.

Case-3: In Case of Exception(ZeroDivisionError)


a = 10
b=0
print(a/b)
ZeroDivisionError: division by zero
Explanation:
Clearly, it is a ZeroDivisionError in this situation as ‘a’ is divided ‘b’(where b=0). We
encountered an exception after executing this code. When syntactically valid Python
code produces an error, then such a specialized error is an exception.

Handling Exception:
Exception handling in Python is managed by three keywords – try, except and
finally.
Program statements that you want to monitor for exception should be in try
block. If an exception occurs within try block, then the particular exception is
raised(thrown).

Working of Exception Handling Mechanism:


When an error occurs while running the program, an exception mechanism
performs the following tasks:
1. Finds the problem. (Get the exception by try block)
2. Informs an error has occurred. (Raise the exception by try block)
3. Receives the error information (By the except statement)
4. Takes the remedial actions. (Handles the exception as per the type of
exception)

General Structure of Exception Handling Mechanism:


try:
statement-1
statement-2
-------------
-------------
except Exception_Type_1:
statement-1
statement-2
-------------
-------------
except Exception_Type_2:
statement-1
statement-2
-------------
-------------
except Exception_Type_N:
statement-1
statement-2
-------------
-------------

Example: WAP to read two numbers from user and find quotient by dividing
first number by second number.

CASE-1: Executing “Divide By Zero” Program Without Exception Handling


a = int(input(“PLEASE ENTER THE FIRST NUMBER: ”))
b = int(input(“PLEASE ENTER THE SECOND NUMBER: ”))
print(“a =”, a)
print(“b =”, b)
print(“a/b =”, a/b)

OUTPUT:

Case-1:
PLEASE ENTER THE FIRST NUMBER: 10
PLEASE ENTER THE SECOND NUMBER: 5
a = 10
b=5
a/b = 2.0

Case-2:
PLEASE ENTER THE FIRST NUMBER: 10
PLEASE ENTER THE SECOND NUMBER: 0
Traceback(most recent call last):
File “C:\Python45\Division.py”, line 3, in <module>
a/b
ZeroDivisionError: division by zero

CASE-2: Executing “Divide By Zero” Program With The Help of Exception


Handling
try:
a = int(input(“PLEASE ENTER THE FIRST NUMBER: ”))
b = int(input(“PLEASE ENTER THE SECOND NUMBER: ”))
print(“a =”, a)
print(“b =”, b)
print(“a/b =”, a/b)
exception ZeroDivisionError:
print(“YOU CANNOT DIVIDE A NUMBER BY ZERO ”)

OUTPUT:

Case-1:
PLEASE ENTER THE FIRST NUMBER: 10
PLEASE ENTER THE SECOND NUMBER: 5
a = 10
b=5
a/b = 2.0

Case-2:
PLEASE ENTER THE FIRST NUMBER: 10
PLEASE ENTER THE SECOND NUMBER: 0
YOU CANNOT DIVIDE A NUMBER BY ZERO

try except finally Block:


The finally block is sometime referred to as finally clause . The finally block
consists of finally keyword. The finally block is placed after the last except
block. If there is no except block, the finally block should immediately follow
the try block.
The finally block will execute whether or not an exception is going to be
thrown from the try block . If an exception is thrown, the finally block will
execute even if no except statement matches the exception.
General Structure of try except finally Block:
try:
statement-1
statement-2
statement-3
--------------
--------------
except Exception_Type_1:
statement-1
statement-2
--------------
--------------
except Exception_Type_2:
statement-1
statement-1
--------------
except Exception_Type_3:
statement-1
statement-2
--------------
--------------
------------------------------
------------------------------
except Exception_Type_N:
statement-1
statement-2
--------------
--------------
finally:
statement-1
statement-2
--------------
--------------
Example:
L = [1, 2, 3, 4, 5]
try:
print(L)
n = int(input(“PLEASE ENTER THE INDEX TO GET THE ELEMENT: ”))
print(‘Index=’, n, ‘Element = ’, L[n])
except IndexError:
print(“PLEASE CHECK THE INDEX”)
PRINT(“INDEX OUT OF BOUNDS/RANGE”)
finally:
print(“NO ONE CAN STOP THE PROGRAM TO RUN”)
OUTPUT:
[1, 2, 3, 4, 5]
PLEASE ENTER THE INDEX TO GET THE ELEMENT: 10
PLEASE CHECK THE INDEX
INDEX OUT OF BOUNDS/RANGE
NO ONE CAN STOP THE PROGRAM TO RUN

else and finally block:


In Python, keywords else and finally can also be used along with the try and
except clauses. While the except block is executed if the exception occurs inside
the try block, the else block gets processed if the try block is found to be
exception free.
try:
#statements in try block
except:
#executed when error in try block
else:
#executed if try block is error-free
finally:
#executed irrespective of exception occurred or not

The finally block consists of statements which should be processed regardless


of an exception occurring in the try block or not . As a consequence, the error-
free try block skips the except clause and enters the finally block before going
on to execute the rest of the code . If, however, there's an exception in the try
block, the appropriate except block will be processed, and the statements in
the finally block will be processed before proceeding to the rest of the code.

Example: The example below accepts two numbers from the user and
performs their division. It demonstrates the uses of else and finally blocks.

try:
print('try block')
x=int(input('Enter a number: '))
y=int(input('Enter another number: '))
z=x/y

except ZeroDivisionError:
print("except ZeroDivisionError block")
print("Division by 0 not accepted")
else:
print("else block")
print("Division = ", z)

finally:
print("finally block")
x=0
y=0
print ("Out of try, except, else and finally blocks." )

CASE-1: The first run is a normal case. The out of the else and finally blocks
is displayed because the try block is error-free.

Output:
try block
Enter a number: 10
Enter another number: 2
else block
Division = 5.0
finally block
Out of try, except, else and finally blocks.

CASE-2: The second run is a case of division by zero, hence, the except
block and the finally block are executed, but the else block is not executed.

OUTPUT:
try block
Enter a number: 10
Enter another number: 0
except ZeroDivisionError block
Division by 0 not accepted
finally block
Out of try, except, else and finally blocks.
CASE-3: In the third run case, an uncaught exception occurs. The finally
block is still executed but the program terminates and does not execute the
program after the finally block.

OUTPUT:
try block
Enter a number: 10
Enter another number: xyz
finally block
Traceback (most recent call last):
File "C:\python36\codes\test.py", line 3, in <module>
y=int(input('Enter another number: '))
ValueError: invalid literal for int() with base 10: 'xyz'

You might also like