Python QP Solution Jan-2023
Python QP Solution Jan-2023
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.
and Logical AND: True if both the operands are true x and y
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
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.
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
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
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.
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.
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.
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:
Looking at the behavior of this generator. Simply calling it like a function will return
a generator object.
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).
raise exception_type(value)
Where exception_type is the class of exception
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?
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.
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.
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.
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.
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))
Example-1:
def sum(x, y):
add = x + y # WHERE ‘add’ IS A LOCAL VARIABLE
return add
OUTPUT:
VALUE OF ‘x’ INSIDE FUNCTION = 10
VALUE OF ‘x’ OUTSIDE THE FUNCTION = 20
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.
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
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.
Syntax: break
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
Syntax: continue
Output:
0
1
2
3
4
num = 0
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
def myfunction():
pass
Example
class Person:
pass
Example
a = 33
b = 200
if b > a:
pass
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.
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’>
OUTPUT:
{} An Empty Dictionary
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’}
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}
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}
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}
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()
Example
print("Hello")
print('Hello')
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
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.
Example
Get the character at position 1 (remember that the first character has the position
0):
a = "Hello, World!"
print(a[1])
String Length
Example
a = "Hello, World!"
print(len(a))
Check String
Example
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
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
Specify the start index and the end index, separated by a colon, to return a part of
the string.
Example
b = "Hello, World!"
print(b[2:5])
By leaving out the start index, the range will start at the first character:
Example
b = "Hello, World!"
print(b[:5])
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
a = "Hello, World!"
print(a.upper())
Lower Case
Example
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:
Replace String
Example
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)
2. Writing user-defined function can make your code easier to read and
understandable.
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
Actual Parameters
OUTPUT:
PLEASE ENTER YOUR NAME: ALOK
DEAR ALOK, WELCOME TO THE WORLD OF PYTHON PROGRAMMING.
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 =
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 =
Example: To Find And Print The Maximum And Minimum Value Between Two
Numbers
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)
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.
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
res = lambda x: x + 5
print(res(10))
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.
numbers=[1,2,3]
square_numbers=[number ** 2 for number in numbers]
print(square_numbers)
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))
Original Tuple:
((1, 1, -5), (30, -15, 56), (81, -60, -39), (-10, 2, 3))
import time
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):
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.
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.
obj1 = time.gmtime(1627987508.6496193)
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.
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.
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
Examples:
1. If a user attempts to open a file that doesn’t exist, then it produces
“FileNotFoundError ”.
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).
Example: WAP to read two numbers from user and find quotient by dividing
first number by second number.
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
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
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'