Python Solutions
Python Solutions
2023
Q1a.What is the need for role of precedence? Illustrate the rules of precedence
in Python with example (6 marks)
1a) The concept of precedence is important when it comes to operator evaluation. Precedence
determines the order in which operators are evaluated in an expression. It ensures that the
expressions are parsed and computed correctly.
The order of operations (also called precedence) of Python math operators is similar to that of
mathematics. The ** operator is evaluated first; the *, /, //, and % operators are evaluated next,
from left to right; and the+ and - operators are evaluated last (also from left to right).Python will
keep evaluating parts of the expression until it becomes a single value.
Example:
1 b. Explain the local and global scope with suitable examples (6 marks)
1b) Parameters and variables that are assigned in a called function are said to exist in that
function’s local scope. Variables that are assigned outside all functions are said to exist in the
global scope. A variable that exists in a local scope is called a local variable, while a variable that
exists in the global scopes called a global variable. A variable must be one or the other; it cannot
be both local and global. Think of a scope as a container for variables. When a scope is
destroyed, all the values stored in the scope’s variables are forgotten. There is only one global
scope, and it is created when program begins. When your program terminates, the global scope is
destroyed, and all its variables are forgotten.
A local scope is created whenever a function is called. Any variables assigned in this function
exist within the local scope. When the function returns, the local scope is destroyed, and these
variables are forgotten. The next time you call this function, the local variables will not
remember the values stored in them from the last time the function was called.
def spam():
eggs = 31337
spam()
print(eggs)
The error happens because the eggs variable exists only in the local scope created when spam() is
called. Once the program execution returns from spam, that local scope is destroyed, and there is
no longer a variable named eggs. So when program tries to run print (eggs), Python gives an
error saying that eggs is not defined. This makes sense if you think about it; when the program
execution is in the global scope, no local scopes exist, so there can’t be any local variables. This
is why only global variables can be used in the global scope.
When the program starts, the spam() function is called (5), and a local scope is created. The local
variable eggs (1) is set to 99. Then the bacon()function is called(2) , and a second local scope is
created. Multiple local scopes can exist at the same time. In this new local scope, the local
variable ham is set to 101, and a local variable egg which is different from the one in spam()’s
local scope is also created (4)and set to 0.
When bacon() returns, the local scope for that call is destroyed. The program execution continues
in the spam() function to print the value of eggs(3) ,and since the local scope for the call to
spam() still exists here, the eggs variable is set to 99. This is what the program prints.
Global Variables Can Be Read from a Local Scope
Output:
Enter the nth value: 5
Fibonacci Series : 0 1 1 2 3
Q2 a) What are functions? Explain Python function with parameters and return
statements(7 marks)
2 a) Functions is to group code that gets executed multiple times. Without a function defined,
you would have to copy and paste this code each time
Output:
When an expression is used with a return statement, the return value is what this expression
evaluates to. For example, the following program defines a function that returns a different string
depending on what number it is passed as an argument.
Example magic8Ball.py:
When this program starts, Python first imports the random module (1).Then the getAnswer()
function is defined (2). Because the function is being defined (and not called), the execution
skips over the code in it. Next, the random.randint() function is called with two arguments, 1 and
9 (4) . It evaluates to a random integer between 1 and 9 (including 1 and 9 themselves),and this
value is stored in a variable named .The getAnswer() function is called with r as the argument
(5). The program execution moves to the top of the getAnswer() function (3), and the value r is
stored in a parameter named answerNumber. Then, depending on this value in answerNumber,
the function returns one of many possible string values. The program execution returns to the
line at the bottom of the program that originally called getAnswer() (5). The returned string is
assigned to a variable named fortune, which then gets passed to a print() call 6( and is printed to
the screen.
2b) Define exception handling. How exceptions are handled in python? Write
a program to solve divide by zero exception (7 marks)
2b) Exception Handling:
Right now, getting an error, or exception, in your Python program means the entire program will
crash. We don’t want this to happen in real-world programs. Instead, we want the program to
detect errors, handle them, and then continue to run.
We’ve defined a function called spam, given it a parameter, and then printed the value of that
function with various parameters to see what happens. This is the output we get when run the
previous code:
A ZeroDivisionError happens whenever you try to divide a number by zero. From the line
number given in the error message, we know that the return statement in spam() is causing an
error.
Errors can be handled with try and except statements. The code that could potentially have an
error is put in a try clause. The program execution moves to the start of a following except clause
if an error happens.
We can put the previous divide-by-zero code in a try clause and have an except clause contain
code to handle what happens when this error occurs.
Output:
2c.) Develop a python program to calculate the area of rectangle and triangle print the result.(6
marks)
2c) Code
def calculate_rectangle_area(length, width):
return length * width
def calculate_triangle_area(base, height):
return 0.5 * base * height
Output:
Indexing 0 1 2 3 4 5 6 7 8
Elements A B C D E F G H I
Negative -9 -8 -7 -6 -5 -4 -3 -2 -1
Indexing
Slicing: slicing refers to as a selection of a range of elements from a list or tuple. The return
type is same as that of the original data container.
Eg : If we have a list a = [1,2,3,4,5,6] and we want to print a slice from 2nd index to 4th (both
inclusive) then we do the following
index() : index() functions returns the index of the element, passed in it as a parameter, from a
list or tuple. It returns a value error if the element is not present in the container.
Eg : a=[1,2,3,4,5,6]
print(a.index(3)) => 2
append() : is used to add or append a value in a list or tuple, not altering any value present
within the containers.
Eg : a = [1,2,3,4,5,6]
a.append(7)
Eg : a = [1,2,3,4,5,6]
a.remove(5)
print(a) => [1,2,3,4,6]
pop() : pop() function is used to remove an element from a list whose index is passed as a
parameter. If nothing is passed, then the last element in the list is removed.
Eg : a = [1,2,3,4,5,6]
a.pop(5)
print(a) => [1,2,3,4,5]
insert() : insert() function is used to insert an element in a list or tuple. It takes 2 parameters
which are the index and item.
Eg : a = [1,2,3,4,5,6]
a.insert(2,20)
print(a) => [1,2,20,3,4,5,6]
sort() : it is a function that sorts a list in ascending or descending order. It generally sorts in
ascending order and to do it in descending, we need to set the reverse parameter in the function
to True, which by default is False.
Eg : a = [7,8,9,1,2,3,4,5,6]
a.sort()
print(a) => [1,2,3,4,5,6,7,8,9]
a.sort(reverse=True)
print(a)=>[9,8,7,6,5,4,3,2,1]
Q3b.) Explain the use of in and not in operators. in list with suitable examples.
3b) Python “in” operator is used to check whether a specified value is a constituent element of a
sequence like string, array, list, tuple, etc. When used in a condition, the statement returns a
Boolean result evaluating either True or False. When the specified value is found inside the
sequence, the statement returns True. Whereas when it is not found, we get a False.
Eg:
list1= [1,2,3,4,5]
string1= "My name is AskPython"
tuple1=(11,22,33,44)
The “not in” operator in Python works exactly the opposite way as the “in” operator. It also
checks the presence of a specified value inside a given sequence but its return values are totally
opposite to that of the “in” operator.
When used in a condition with the specified value present inside the sequence, the statement
returns False. Whereas when it is not, we get a True.
Eg:
list1= [1,2,3,4,5]
string1= "My name is AskPython"
tuple1=(11,22,33,44)
3c)
a=[1,2,3,4,5,6,7,8,9]
sd=[]
mean = sum(a)/len(a)
print("Mean : ", mean) => Mean : 5.0
for x in a:
sd.append((x-mean)**2)
V = sum(sd)/len(sd)
print("Variance : ", V) => Variance : 6.6666666666667
print("Standard Deviation : ", V**0.5) => Standard Deviation : 2.58198889747
4a) len() : it returns the length of the passed string or data container. Its return type is that of an
integer.
Eg: a=[1,2,3,4,5,6,7,8,9]
print(len(a)) => 9
sum(): it returns the sum of all the elements(numbers) of a list or tuple, passed as a parameter.
Eg: a=[1,2,3,4,5,6,7,8,9]
print(sum(a)) =>45
max() : The max() function returns the item with the highest value, or the item with the highest
value in an iterable. If the elements are string then it will return the string with the maximum
lexicographic value
Eg:
var1 = 1
var2 = 8
var3 = 2
var1 = "geeks"
var2 = "for"
var3 = "geek"
min(): min() function returns the smallest of the values or the smallest item in an iterable passed
as its parameter.
Eg :
print(min([1, 2, 3])) => 1
print(min({'a': 1, 'b': 2, 'c': 3})) => ‘a’
print(min((7, 9, 11))) => 7
4b. The setdefault() method returns the value of the item with the specified key. If the key does
not exist, insert the key, with the specified value.
Eg:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.setdefault("color", "white")
print(x) => White
4c.
a="Java"
for x in a:
if x.isupper():
print(x.lower(), end="")
elif x.islower():
print(x.upper(), end="")
The join() method is useful when you have a list of strings that need to be joined together into
a single string value. The join() method is called on a string, gets passed a list of strings, and
returns a string. The returned string is the concatenation of each string in the passed-in list. (2
Marks)
Example: (2 Marks)
The split() method called on a string value and returns a list of strings. You can pass a delimiter
string to the split () method to specify a different string to split upon. (2 Marks)
Example: (2 Marks)
>>> 'MyABCnameABCisABCSimon'.split('ABC')
['My', 'name', 'is', 'Simon']
isalpha() returns True if the string consists only of letters and is not blank.(1 Mark)
isalnum() returns True if the string consists only of letters and numbers and is not blank.(1
Mark)
isspace() returns True if the string consists only of spaces, tabs, and new- lines and is not
blank.(1 Mark)
Example : (3 Marks)
while True:
print('Enter your name:')
age = input()
if age.isalpha():
break
print('Please enter alphabets for name')
while True:
print('Select a new password (letters and numbers only):')
password = input()
if password.isalnum():
break
print('Passwords can only have letters and numbers.')
OUTPUT:
Enter your name:
123
Please enter alphabets for name
Enter your name:
vijay
Select a new password (letters and numbers only):
vijay_123
Passwords can only have letters and numbers.
Select a new password (letters and numbers only):
vijay123
5 c) Develop a python code to determine whether the given string is a palindrome or not a
palindrome. (6)
OUTPUT:
Enter the string to check if it is a palindrome: ABa
The string is a palindrome.
6. a) Explain the concept of file handling. Also explain reading and writing process with
suitable example. (8)
Before performing any operation on the file like reading or writing, first, we have to open that
file. For this, we should use Python’s inbuilt function open () but at the time of opening, we have
to specify the mode. The following mode is supported:
Reading: If you want to read the entire contents of a file as a string value, use
the File object’s read() method. Alternatively, you can use the readlines() method to get a list of
string values from the file, one string for each line of text.(2 Marks)
Writing: Write mode will overwrite the existing file and start from scratch, just like when you
overwrite a variable’s value with a new value. Pass 'w' as the second argument to open() to open
the file in write mode. Append mode, on the other hand, will append text to the end of the
existing file. (2 Marks)
Example: (2 Marks)
A file has two key properties: a filename (usually written as one word) and a path. The path
specifies the location of a file on the computer.
Path() will return a string with a file path using the correct path separators. (2 Marks)
An absolute path, which always begins with the root folder. os.path.abspath(path) will return a
string of the absolute path of the argument. os.path.isabs(path) will return True if the argument is
an absolute path and False if it is a relative path.
>>> os.path.abspath('.')
'C:\\Users\\Al\\AppData\\Local\\Programs\\Python\\Python37'
>>> os.path.abspath('.\\Scripts')
'C:\\Users\\Al\\AppData\\Local\\Programs\\Python\\Python37\\Scripts' (2 Marks)
When the relative path is within the same parent folder as the path, but is within subfolders of a
different path, such as 'C:\\Windows' and 'C:\\spam\\eggs', you can use the “dot-dot” notation to
return to the parent folder.(2 Marks)
We can save variables in your Python programs to binary shelf files using the shelve module. For
example, if you ran a program and entered some configuration settings, you could save those
settings to a shelf file and then have the program load them the next time it is run.
To read and write data using the shelve module, first import shelve. Call shelve.open() and pass
it a filename, and then store the returned shelf value in a variable. You can make changes to the
shelf value as if it were a dictionary. When all are done, call close() on the shelf value. (2
Marks)
Example : (4 Marks)
We open the shelf files to check that our data was stored correctly.
Entering shelfFile['cats'] returns the same list that we stored earlier, so we know that the list is
correctly stored, and we call close().
Just like dictionaries, shelf values have keys() and values() methods that will return list-like
values of the keys and values in the shelf
7.Explain the following file oporations in Python wilh suitable example: (6 Marks)
i) The shutil (or shell utilities) module has functions to let you copy, move, rename, and delete
files in your Python programs. To use the shutil functions, you will first need to use import
shutil.
The shutil module provides functions for copying files, as well as entire folders. Calling
shutil.copy(source, destination) will copy the file at the path source to the folder at the path
destination. (Both source and destination are strings.) If destination is a filename, it will be used
as the new name of the copied file. This function returns a string of the path of the copied file.
Code:-
import shutil, os
os.chdir('C:\\')
shutil.copy('C:\\spam.txt', 'C:\\delicious')
'C:\\delicious\\spam.txt'
shutil.copy('eggs.txt', 'C:\\delicious\\eggs2.txt')
'C:\\delicious\\eggs2.txt'
ii) Calling shutil.move(source, destination) will move the file or folder at the path source to the
path destination and will return a string of the absolute path of the new location. If destination
points to a folder, the source file gets moved into destination and keeps its current filename.
Code:-
import shutil
shutil.move('C:\\bacon.txt', 'C:\\eggs')
'C:\\eggs\\bacon.txt'
iii) You can delete a single file or a single empty folder with functions in the os module, whereas
to delete a folder and all of its contents, you use the shutil module.
• Calling os.rmdir(path) will delete the folder at path. This folder must be
• Calling shutil.rmtree(path) will remove the folder at path, and all files
Code:-
import os
if filename.endswith('.rxt'):
os.unlink(filename)
7.b) List out the benefits of compressing file? Also explain reading of a zip file (8Marks)
7.b) In Python Zipfile is an archive file format and a compression standard; it is a single file that
holds compressed files. Compressing a file reduces its size, which is useful when transferring it
over the Internet. And since a ZIP file can also contain multiple files and subfolders, it’s a handy
way to package several files into one. This single file, called an archive file, can then be, say,
attached to an email.
Python programs can both create and open (or extract) ZIP files using functions in the zipfile
module.
Python Zipfile is an ideal way to group similar files and compress large files to reduce their size.
The compression is lossless. This means that using the compression algorithm, we can operate on
the compressed data to perfectly reconstruct the original data. So, in Python Zipfile is an archive
file format and a compression standard; it is a single file that holds compressed files.
Since ZIP files use compression, they can hold much more for the same amount of storage
To read the contents of a ZIP file, we can use the ZipFile class from the built-in zipfile module in
Python.
First, import the zipfile module. Then, we can create a new instance of the ZipFile class and
specify the name and path of the zip file that we want to read. After that, we can use the methods
provided by the ZipFile class to access the contents of the zip file.
The ZipFile class provides several methods for reading zip files, such as namelist() , infolist() ,
read() , and extract() . The namelist() method returns a list of all the file names in the zip archive,
while the infolist() method returns a list of ZipInfo objects for all the files in the archive.
The read() method can be used to read the contents of a specific file in the zip archive, while the
extract() method can be used to extract a specific file from the archive and save it to a specified
location Zip file 3 on the filesystem.
When reading a zip file in Python, it is important to be aware of the file paths and naming
conventions used in the archive, as these may differ from the paths and naming conventions used
on the local filesystem. In addition, some zip archives may be password-protected or encrypted,
which may require additional steps to read or extract the contents of the archive.
Code:-
print(myfile.readline())
7.c) List out the differences between shutil.copy( ) and shutil.copytree( ) method.( 6 Marks)
7.c) While shutil.copy() will copy a single file, shutil.copytree() will copy an entire folder and
every folder and file contained in it. Calling shutil.copytree(source, destination) will copy the
folder at the path source, along with all of its files and subfolders, to the folder at the path
destination. The source and destination parameters are both strings. The function returns a string
of the path of the copied folder.
Code: -
import shutil, os
os.chdir('C:\\')
shutil.copytree('C:\\bacon', 'C:\\bacon_backup')
'C:\\bacon_backup'
Raising Exceptions
Python raises an exception whenever it tries to execute invalid code. One can also raise his own
exceptions in your code. Raising an exception is a way of saying, “Stop running the code in this
function and move the program execution to the except statement.”
Exceptions are raised with a raise statement. In code, a raise statement consists of the following:
print(symbol * width)
for i in range(height - 2):
print(symbol + (' ' * (width - 2)) + symbol)
print(symbol * width)
for sym, w, h in (('*', 4, 4), ('O', 20, 5), ('x', 1, 3), ('ZZ', 3, 3)):
try:
boxPrint(sym, w, h)
➍ except Exception as err:
➎ print('An exception happened: ' + str(err))
You can view the execution of this program at https://autbor.com/boxprint. Here we’ve defined
a boxPrint() function that takes a character, a width, and a height, and uses the character to make
a little picture of a box with that width and height. This box shape is printed to the screen.
Say we want the character to be a single character, and the width and height to be greater than 2.
We add if statements to raise exceptions if these requirements aren’t satisfied. Later, when we
call boxPrint() with various arguments, our try/except will handle invalid arguments.
This program uses the except Exception as err form of the except statement ➍. If
an Exception object is returned from boxPrint() ➊ ➋ ➌, this except statement will store it in a
variable named err. We can then convert the Exception object to a string by passing it to str() to
produce a user-friendly error message ➎. When you run this boxPrint.py, the output will look
like this:
****
* *
* *
****
OOOOOOOOOOOOOOOOOOOO
O O
O O
O O
OOOOOOOOOOOOOOOOOOOO
An exception happened: Width must be greater than 2.
An exception happened: Symbols must be a single character string.
Using the try and except statements, you can handle errors more gracefully instead of letting the
entire program crash.
To enable the logging module to display log messages on your screen as your program runs,
copy the following to the top of your program (but under the #! python shebang line):
import logging
logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s - %(levelname)
s - %(message)s')
You don’t need to worry too much about how this works, but basically,
● when Python logs an event, it creates a LogRecord object that holds information about that
event.
● The logging module’s basicConfig() function lets you specify what details about
the LogRecord object you want to see and how you want those details displayed.
Say you wrote a function to calculate the factorial of a number. In mathematics, factorial 4 is 1 ×
2 × 3 × 4, or 24. Factorial 7 is 1 × 2 × 3 × 4 × 5 × 6 × 7, or 5,040. Open a new file editor tab and
enter the following code. It has a bug in it, but you will also enter several log messages to help
yourself figure out what is going wrong. Save the program as factorialLog.py.
import logging
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s
- %(message)s')
logging.debug('Start of program')
def factorial(n):
logging.debug('Start of factorial(%s%%)' % (n))
total = 1
for i in range(n + 1):
total *= i
logging.debug('i is ' + str(i) + ', total is ' + str(total))
logging.debug('End of factorial(%s%%)' % (n))
return total
print(factorial(5))
logging.debug('End of program')
Here, we use the logging.debug() function when we want to print log information.
This debug() function will call basicConfig(), and a line of information will be printed. This
information will be in the format we specified in basicConfig() and will include the messages we
passed to debug(). The print(factorial(5)) call is part of the original program, so the result is
displayed even if logging messages are disabled.
The output of this program looks like this:
2019-05-23 16:20:12,664 - DEBUG - Start of program
2019-05-23 16:20:12,664 - DEBUG - Start of factorial(5)
2019-05-23 16:20:12,665 - DEBUG - i is 0, total is 0
2019-05-23 16:20:12,668 - DEBUG - i is 1, total is 0
2019-05-23 16:20:12,670 - DEBUG - i is 2, total is 0
2019-05-23 16:20:12,673 - DEBUG - i is 3, total is 0
2019-05-23 16:20:12,675 - DEBUG - i is 4, total is 0
2019-05-23 16:20:12,678 - DEBUG - i is 5, total is 0
2019-05-23 16:20:12,680 - DEBUG - End of factorial(5)
0
2019-05-23 16:20:12,684 - DEBUG - End of program
The factorial() function is returning 0 as the factorial of 5, which isn’t right. The for loop should
be multiplying the value in total by the numbers from 1 to 5. But the log messages displayed
by logging.debug() show that the i variable is starting at 0 instead of 1. Since zero times anything
is zero, the rest of the iterations also have the wrong value for total. Logging messages provide a
trail of breadcrumbs that can help you figure out when things started to go wrong.
Change the for i in range(n + 1): line to for i in range(1, n + 1):, and run the program again. The
output will look like this:
2019-05-23 17:13:40,650 - DEBUG - Start of program
2019-05-23 17:13:40,651 - DEBUG - Start of factorial(5)
2019-05-23 17:13:40,651 - DEBUG - i is 1, total is 1
2019-05-23 17:13:40,654 - DEBUG - i is 2, total is 2
2019-05-23 17:13:40,656 - DEBUG - i is 3, total is 6
2019-05-23 17:13:40,659 - DEBUG - i is 4, total is 24
2019-05-23 17:13:40,661 - DEBUG - i is 5, total is 120
2019-05-23 17:13:40,661 - DEBUG - End of factorial(5)
120
2019-05-23 17:13:40,666 - DEBUG - End of program
The factorial(5) call correctly returns 120. The log messages showed what was going on inside
the loop, which led straight to the bug.
You can see that the logging.debug() calls printed out not just the strings passed to them but also
a timestamp and the word DEBUG.
The benefit of logging levels is that you can change what priority of logging message you want
to see. Passing logging.DEBUG to the basicConfig() function’s level keyword argument will
show messages from all the logging levels (DEBUG being the lowest level). But after
developing your program some more, you may be interested only in errors. In that case, you can
set basicConfig()’s level argument to logging.ERROR. This will show only ERROR and
CRITICAL messages and skip the DEBUG, INFO, and WARNING messages.
def DivExp(a,b):
# AssertionError with error_message.
Q.9 a) Define a class and object, construct the class called rectangle
and initialize it with height =100, width = 200, starting point as (x =
0, y =0). Write a program to display the center point coordinates of a
rectangle.
class Point:
""" This is a class Point
representing coordinate point
"""
class Rectangle:
""" This is a class Rectangle.
Attributes: width, height and Corner Point
"""
def find_center(rect):
p=Point()
p.x = rect.corner.x + rect.width/2
p.y = rect.corner.y + rect.height/2
return p
def resize(rect, w, h):
rect.width +=w
rect.height +=h
def print_point(p):
print("(%g,%g)"%(p.x, p.y))
9b) Explain the concept of copying using the copy module with
an example.
The copy() method of the copy module duplicates the object. The content (i.e. attributes) of
one object is copied into another object as we have discussed till now. But, when an object
itself is an attribute inside another object, the duplication will result in a strange manner. To
understand this concept, try to copy Rectangle object (created in previous section) as given
below –
import copy
class Point:
""" This is a class Point
representing coordinate point
"""
class Rectangle:
""" This is a class Rectangle.
Attributes: width, height and Corner Point
"""
box1=Rectangle()
box1.corner=Point()
box1.width=100
box1.height=200
box1.corner.x=0
box1.corner.y=0
box2=copy.copy(box1)
print(box1 is box2) #prints False
print(box1.corner is box2.corner) #prints True
Now, the question is – why box1.corner and box2.corner are same objects, when
box1 and box2 are different? Whenever the statement
box2=copy.copy(box1)
is executed, the contents of all the attributes of box1 object are copied into the respective
attributes of box2 object. That is, box1.width is copied into box2.width,
box1.height is copied into box2.height. Similarly, box1.corner is copied into
box2.corner. Now, recollect the fact that corner is not exactly the object itself, but it is a
reference to the object of type Point (Read the discussion done for Figure 4.1 at the
beginning of this Chapter). Hence, the value of reference (that is, the physical address)
stored in box1.corner is copied into box2.corner. Thus, the physical object to which
box1.corner and box2.corner are pointing is only one. This type of copying the
objects is known as shallow copy.
Now, the attributes width and height for two objects box1 and box2 are independent.
Whereas, the attribute corner is shared by both the objects. Thus, any modification done
to box1.corner will reflect box2.corner as well. Obviously, we don’t want this to
happen, whenever we create duplicate objects. That is, we want two independent physical
objects. Python provides a method deepcopy() for doing this task. This method copies not
only the object but also the objects it refers to, and the objects they refer to, and so on.
box3=copy.deepcopy(box1)
print(box1 is box3) #prints False
print(box1.corner is box3.corner) #prints False
Thus, the objects box1 and box3 are now completely independent.
If we apply this concept for programming, it can be easily understood that a code written is
reusable. Thus, in this mechanism, it is possible for one object to be a specific instance of a more
general case. Using inheritance, an object need only define those qualities that make it unique
object within its class. It can inherit its general attributes from its parent.
10.a) Define a function which takes two objects representing complex numbers and returns
new complex number with a addition of two complex numbers. Define a suitable class
Complex' to represent the complex number. Develop a program to read NN>=2) complex
number S and to compute the addition of N complex numbers. (8Marks)
10.a) Code:-
class Complex:
# Constructor to accept
# real and imaginary part
def __init__(self, tempReal, tempImaginary):
self.real = tempReal;
self.imaginary = tempImaginary;
# Driver code
if __name__=='__main__':
Example
# A Sample class with init method
class Person:
# Sample Method
def say_hi(self):
print('Hello, my name is', self.name)
p = Person('Nikhil')
p.say_hi()
Output:
Hello, my name is Nikhil
The __str__ method in Python represents the class objects as a string – it can be used for classes.
The __str__ method should be defined in a way that is easy to read and outputs all the members
of the class. This method is also used as a debugging tool when the members of a class need to
be checked.
The __str__ method is called when the following functions are invoked on the object and return a
string:
● print()
● str()
Example:-
class MyClass:
x=0
y = ""
Output:-
<__main__.MyClass object at 0x7f1d8d71d1f0>
<__main__.MyClass object at 0x7f1d8d71d1f0>
<__main__.MyClass object at 0x7f1d8d71d1f0>
Code:-
# Defining a class
class Test:
def __init__(self, a, b):
self.a = a
self.b = b
def __repr__(self):
return "Test a:% s b:% s" % (self.a, self.b)
def __str__(self):
return "From str method of Test: a is % s, " \
"b is % s" % (self.a, self.b)
# Driver Code
t = Test(1234, 5678)
Output:-
From str method of Test: a is 1234, b is 5678
[Test a:1234 b:5678]