Python Solution Model Papers
Python Solution Model Papers
MODULE 1
1 Explain the math operators in Python from highest to lowest Precedence with an example for each. Write 6
the steps how Python is evaluating the expression (5 - 1) * ((7 + 1) / (3 - 1)) and reduces it to a single
value.
✓ The operator is a symbol which tells the compiler to do specific mathematical or logical function.
✓ In python, a single value with no operators is also considered an expression, though it evaluates
only to itself.
✓ The order of operations (also called precedence) of Python math operators is similar to that of
mathematics i.e., **, *, /, //, %, +, -
✓ The associativity is also similar and followed from left to right.
2 Define a Python function with suitable parameters to generate prime numbers between two integer 8
values. Write a Python program which accepts two integer values m and n (note: m>0, n>0 and m < n)
as inputs and pass these values to the function. Suitable error messages should be displayed if the
conditions for input values are not followed.
3 Explain Local and Global Scope in Python programs. What are local and global variables? How can you 6
force a variable in a function to refer to the global variable?
✓ 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 scope is called a global variable.
✓ Scopes matter for several reasons:
1. Code in the global scope cannot use any local variables.
2. However, a local scope can access global variables.
3. Code in a function‟s local scope cannot use variables in any other local scope.
4. We can use the same name for different variables if they are in different scopes. That is, there
can be a local variable named spam and a global variable also named spam.
✓ We can force a variable in a function to refer to the global variable using global statement as
shown below:
Program Output
✓ Because eggs is declared global at the top of spam() ❶, when eggs is set to 'spam' ❷, this
assignment is done to the globally scoped eggs. No local eggs variable is created.
4 What are Comparison and Boolean operators? List all the Comparison and Boolean operators in Python 6
and explain the use of these operators with suitable examples.
✓ Comparison operators: These are used to compare two values and evaluate down to a single
Boolean value.
✓ Boolean Operators: The three Boolean operators (and, or, and not) are used to compare Boolean
values.
i. and operator: The and operator evaluates an expression to True if both Boolean values
are True; otherwise, it evaluates to False.
ii. or operator: The or operator valuates an expression to True if either of the two Boolean
values is True. If both are False, it evaluates to False.
iii. not operator: The not operator operates on only one Boolean value (or expression). The
not operator simply evaluates to the opposite Boolean value. Much like using double
negatives in speech and writing, you can nest not operators ❶, though there‟s never not
no reason to do this in real programs.
5 Define a Python function with suitable parameters to generate first N Fibonacci numbers. The first two 8
Fibonacci numbers are 0 and 1 and the Fibonacci sequence is defined as a function F as Fn = Fn-1 + Fn-2.
Write a Python program which accepts a value for N (where N >0) as input and pass this value to the
function. Display suitable error message if the condition for input value is not followed.
def fibonacci(n):
if n < 0:
print("incorrect input")
elif n == 1:
return 0
elif n == 2:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2)
6 What is Exception Handling? How exceptions are handled in Python? Write a Python program with 6
exception handling code to solve divide-by-zero error situation.
✓ Exception Handling: If we don‟t want to crash the program due to errors instead we want the
program to detect errors, handle them, and then continue to run is called exception handling.
✓ Exceptions 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.
✓ Program:
✓ In the above program if the second number given by the user as input is 0 then, it catches the error
and the exception statement will be printed.
7 Write a python program to find the area of square, rectangle and circle. Print the results. Take input 6
from user.
8 List and explain the syntax of all flow control statements with example. 8
➢ An if statement‟s clause (that is, the block following the if statement) will execute if the
statement‟s condition is True. The clause is skipped if the condition is False.
➢ In plain English, an if statement could be read as, “If this condition is true, execute the code in the
clause.”
➢ In Python, an if statement consists of the following:
1. The if keyword
2. A condition (that is, an expression that evaluates to True or False)
3. A colon
4. Starting on the next line, an indented block of code (called the if clause)
➢ Example:
➢ Flowchart:
2. else Statements:
➢ An if clause can optionally be followed by an else statement. The else clause is executed only
when the if statement‟s condition is False.
➢ In plain English, an else statement could be read as, “If this condition is true, execute this code.
Or else, execute that code.”
➢ An else statement doesn‟t have a condition, and in code, an else statement always consists of the
following:
1. The else keyword
2. A colon
3. Starting on the next line, an indented block of code (called the else clause)
➢ Example:
➢ Flowchart:
3. elif Statements:
➢ Flowchart:
➢ Example:
break Statement
✓
✓ The first line ❶ creates an infinite loop; it is a while loop whose condition is always True.
✓ The program execution will always enter the loop and will exit it only when a break statement is
executed.
✓ The program asks the user to type name ❷.
✓ While the execution is still inside the while loop, an if statement gets executed ❸ to check
whether name is equal to entered name.
✓ If this condition is True, the break statement is run ❹, and the execution moves out of the loop
to print('Thank you!') ❺.
continue Statement
✓ The continue statement is used to immediately jump back to the start of the loop and reevaluate
the loop‟s condition.
✓ A continue statement simply contains continue keyword.
✓ If the user enters any name besides Joe ❶, the continue statement ❷ causes the program
execution to jump back to the start of the loop.
✓ When it reevaluates the condition, the execution will always enter the loop, since the condition is
simply the value True. Once they make it past that if statement, the user is asked for a password
❸.
✓ If the password entered is swordfish, then the break statement ❹ is run, and the execution jumps
out of the while loop to print Access granted ❺.
10 What are user defined functions? How can we pass parameters in user defined functions? Explain with 7
suitable example.
✓ User defined functions are the mini-programs written by the user to do some specific task.
✓ The functions always start with the keyword “def”.
✓ We can pass parameters to the user defined functions as shown below:
✓ The definition of the hello() function in this program has a parameter called name ❶.
✓ A parameter is a variable that an argument is stored in when a function is called. The first time
the hello() function is called, it‟s with the argument 'Alice' ❸.
✓ The program execution enters the function, and the variable name is automatically set to 'Alice',
which is what gets printed by the print() statement ❷.
✓ If we need to modify a global variable from within a function, use the global statement.
✓ If we have a line such as global eggs at the top of a function, it tells Python, “In this
function, eggs refers to the global variable, so don‟t create a local variable with this name.”
✓ For example:
Program Output
✓ Because eggs is declared global at the top of spam() ❶, when eggs is set to 'spam' ❷, this
assignment is done to the globally scoped eggs. No local eggs variable is created.
✓ There are four rules to tell whether a variable is in a local scope or global scope:
1. If a variable is being used in the global scope (that is, outside of all functions), then it is always
a global variable.
2. If there is a global statement for that variable in a function, it is a global variable.
3. Otherwise, if the variable is used in an assignment statement in the function, it is a local
variable.
4. But if the variable is not used in an assignment statement, it is a global variable.
12 Write a function that computes and returns addition, subtraction, multiplication, division of two 5
integers. Take input from user.
MODULE 2
1 What is Dictionary in Python? How is it different from List data type? Explain how a for loop 6
can be used to traverse the keys of the Dictionary with an example.
Dictionary: A dictionary is a collection of many values. Indexes for dictionaries can use many
different data types, not just integers. Indexes for dictionaries are called keys, and a key with its
associated value is called a key-value pair. A dictionary is typed with braces, {}.
2 Explain the methods of List data type in Python for the following operations with suitable code 8
snippets for each.
(i) Adding values to a list ii) Removing values from a list
(iii) Finding a value in a list iv) Sorting the values in a list
i) Adding values to a list:
✓ To add new values to a list, the append() and insert() methods can be used.
✓ The append() method adds the argument to the end of the list.
✓ Attempting to delete a value that does not exist in the list will result in a ValueError error.
✓ If the value appears multiple times in the list, only the first instance of the value will be removed.
✓ Lists of number values or lists of strings can be sorted with the sort() method.
3 Write a Python program that accepts a sentence and find the number of words, digits, uppercase 6
letters and lowercase letters.
def Count(str):
up, low, num, special = 0, 0, 0, 0
for i in range(len(str)):
if str[i] >= 'A' and str[i] <= 'Z':
up += 1
elif str[i] >= 'a' and str[i] <= 'z':
low += 1
elif str[i] >= '0' and str[i] <= '9':
num += 1
else:
special += 1
print("LETTERS :",up+low,"DIGITS :",num,"UPPERCASE :",up,"LOWERCASE :",low)
print("Enter a sentence")
str = input()
Count(str)
4 What is the difference between copy.copy( ) and copy.deepcopy( ) functions applicable to a List 6
or Dictionary in Python? Give suitable examples for each.
Copy module must be imported and can be used to make a duplicate copy of a mutable value like a
list or dictionary, not just a copy of a reference.
copy.copy( ): A shallow copy creates a new object which stores the reference of the original
elements.So, a shallow copy doesn't create a copy of nested objects, instead it just copies the reference
of nested objects. This means, a copy process does not create copies of nested objects itself.
Example:
import copy
old_list = [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
new_list = copy.copy(old_list)
old_list[1][1] = 'AA'
print("Old list:", old_list)
print("New list:", new_list)
Output:
copy.deepcopy( ): A deep copy creates a new object and recursively adds the copies of nested objects
present in the original elements.
Example:
import copy
old_list = [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
new_list = copy.deepcopy(old_list)
old_list[1][0] = 'BB'
print("Old list:", old_list)
print("New list:", new_list)
Output:
(i) get( ): Dictionaries have a get() method that takes two arguments:
➢ The key of the value to retrieve
➢ A fallback value to return if that key does not exist.
(ii) items( ): This method returns the dictionary values and keys in the form of tuples.
Ex: spam = {„color‟ : „red‟ , „age‟ : 27}
for i in spam.items( ):
print(i)
Output: („color‟, „red‟)
(„age‟, 27)
6 Explain the various string methods for the following operations with examples. 6
(i) Removing whitespace characters from the beginning, end or both sides of a string.
(ii) To right-justify, left-justify, and center a string.
i) Removing whitespace characters from the beginning, end or both sides of a string.
✓ The strip() string method will return a new string without any whitespace characters at the
beginning or end.
✓ The lstrip() and rstrip() methods will remove whitespace characters from the left and right ends,
respectively.
✓ The rjust() and ljust() string methods return a padded version of the string they are called on, with
spaces inserted to justify the text.
✓ The first argument to both methods is an integer length for the justified string.
✓ An optional second argument to rjust() and ljust() will specify a fill character other than a space
character.
✓ The center() string method works like ljust() and rjust() but centers the text rather than justifying
it to the left or right.
✓ Reference: A reference is a value that points to some bit of data, and a list reference is a value
that points to a list.
✓ Here, the list is created, and assigned reference to it in the spam variable.
✓ In the next line copies only the list reference in spam to cheese, not the list value itself. This means
the values stored in spam and cheese now both refer to the same list.
✓ When a function is called, the values of the arguments are copied to the parameter variables.
✓ when eggs() is called, a return value is not used to assign a new value to spam.
✓ Even though spam and someParameter contain separate references, they both refer to the same
list.
✓ This is why the append('Hello') method call inside the function affects the list even after the
function call has returned.
9 What is dictionary? How it is different from list? Write a program to count the number of 7
occurrences of character in a string.
import pprint
x = input("Enter a String")
count = {}
for character in x:
count.setdefault(character, 0)
count[character] = count[character] + 1
pprint.pprint(count)
10 You are creating a fantasy video game. The data structure to model the player‟s inventory 7
will be a dictionary where the keys are string values describing the item in the inventory and
the value is an integer value detailing how many of that item the player has. For example, the
dictionary value {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12} means the
player has 1 rope, 6 torches, 42 gold coins, and so on. Write a function named
displayInventory() that would take any possible “inventory” and display it like the following:
Inventory:
12 arrow
42 gold coin
1 rope
6 torch
1 dagger
Total number of items: 63
11 List any six methods associated with string and explain each of them with example. 8
i) upper( ): This method is used to convert lower case characters into upper case characters.
Ex: x = „Python‟
x = x.upper( )
PYTHON
ii) lower( ): This method is used to convert upper case characters into lower case characters.
Ex: x = „Python‟
x = x.lower( )
python
iii) isupper( ): This method is used to check whether a string has at least one letter or complete
string is upper or not. It returns Boolean value.
Ex: x = „Python‟
x = x.isupper( )
TRUE
Ex: y = „python‟
y = y.isupper( )
FALSE
iv) islower( ): This method is used to check whether a string has at least one letter or complete
string is lower or not. It returns Boolean value.
Ex: x = „Python‟
x = x.islower( )
TRUE
Ex: y = „PYTHON‟
y = y.isupper( )
FALSE
v) isspace( ): Returns True if the string consists only of spaces, tabs, and newlines and is not
blank.
Ex: „ „.isspace( )
TRUE
vi) isalnum( ): Returns True if the string consists only of letters and numbers and is not blank.
Ex: „hello123‟.isalnum( )
TRUE
Ex: „ „.isalnum( )
FALSE
print("Enter a String")
string = input()
print(string.swapcase())
def swapcase(string):
result_str = ""
for item in string:
if item.isupper():
result_str += item.lower()
else:
result_str += item.upper()
return result_str
string = input("Enter a String")
print(swapcase(string))
MODULE 4
1 Write a Python Program to find an American phone number (example: 415-555-4242) in a given 6
string using Regular Expressions.
import re
print("Enter a string")
x = input()
phoneRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')
phoneRegex.findall(x)
2 Describe the difference between Python os and os.path modules. Also, discuss the following 7
methods of os module
a) chdir() b) rmdir() c) walk() d) listdir() e) getcwd()
os module →It is from the standard library and it provides a portable way of accessing and using
operating system dependent functionality.
os.path module → It is used to manipulate the file and directory paths and path names.
a) chdir( ) → This method is used to change from current working directory to the required
directory.
Ex: import os
os.chdir(“C:\\Windows\\System”)
b) rmdir( ) → This method is used to delete the folder at path. This folder must not contain any
files or folders.
c) walk( ) → This method is used to access or do any operation on each file in a folder.
Ex: import os
for foldername, subfolder, filenames in os.walk(“C:\\Windows\\System”)
print(“The current folder is “+foldername)
d) listdir( ) → This method returns a list containing the names of the entries in the directory
given by path.
Ex: import os
os.getcwd( )
3 Demonstrate the copy, move, rename and delete functions of shutil module with Python code 7
snippet.
Copy: shutil.copy(source, destination) will copy the file from source path to destination path.
Move: shutil.move(source, destination) will move the file or folder from source path to the destination
path and will return a string of the absolute path of the new location.
Delete: We 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, we use the shutil module.
1. Calling os.unlink(path) will delete the file at path.
2. Calling os.rmdir(path) will delete the folder at path. This folder must be empty of any files or
folders.
3. Calling shutil.rmtree(path) will remove the folder at path, and all files and folders it contains
will also be deleted.
Ex: import os
for filename in in os.listdir( ):
if filename.endswith(„.txt‟):
os.unlink(filename)
✓ Greedy pattern matching means matching with the longest possible string. By default, in python
greedy matching is followed.
Ex:
18
✓ Non-greedy pattern matching means matching with the shortest possible string. It should be
represented explicitly using a question mark after the curly brackets.
✓ Ex:
✓ search() method will return a Match object of the first matched text in the searched string.
✓ findall() method will return the strings of every match in the searched string in the form of list of
strings—as long as there are no groups in the regular expression.
✓ Ex:
Reading File: read( ) and readlines( ) methods are used to read the contents of a file. read( ) method
reads the contents of a file as a single string value whereas readlines( ) method reads each line as a
string value.
Ex:
Writing File: The file must be opened in order to write the contents to a file. It can be done in two
ways: wither in write mode or append mode. In write mode the contents of the existing file will be
overwritten whereas in append mode the contents will be added at the end of existing file.
Ex: In the below example bacon.txt file is opened in write mode hence, all the contents will be
deleted and Hello world! Will be written.
Ex: In the below example bacon.txt file is opened in append mode hence, the contents will be added
after Hello world!
6 Define assertions. What does an assert statement in python consists of? Explain how assertions 7
can be used in traffic light simulation with Python code snippet.
19
✓ Assertion: An assertion is a sanity check to make sure the code isn‟t doing something obviously
wrong.
✓ If the sanity check fails, then an AssertionError exception is raised.
✓ In python, an assert statement consists of the following:
1. The assert keyword
2. A condition (that is, an expression that evaluates to True or False)
3. A comma
4. A string to display when the condition is False
✓ In plain English, an assert statement meaning is, “I assert that this condition holds true, and if not,
there is a bug somewhere in the program.”
✓ Traffic Light Simulation: The data structure representing the stoplights at an intersection is a
dictionary with keys 'ns' and 'ew', for the stoplights facing north-south and east-west, respectively.
The values at these keys will be one of the strings 'green', ' yellow', or 'red'.
➢ These two variables will be for the intersections of Market Street and 2nd Street, and Mission
Street and 16th Street. The switchLights() function, will take an intersection dictionary as an
argument and switch the lights.
➢ But, while writing switchLights() we add an assertion to check that at least one of the lights is
always red.
✓ If neither direction of traffic has a red light then assertion error occurs.
7 List and explain Shorthand code for common character classes .Illustrate how do you define 7
your own character class?
Character classes are used for shortening regular expression. The following are few of the shorthand
code for common character classes:
20
Defining own character class: The own character class can be defined using square brackets [ ] and
the necessary conditions can be given. Negative character class can also be defined using the symbol
^.
Ex:
[0-5] → Will match the numbers from 0 to 5
[0-5.] → Will match the number from 0 to 5 and a period
[a-zA-Z] → Will match all the upper case and lower case letters.
[^a-zA-Z] → Will match all the characters apart from upper case and lower case letters.
8 Explain the usage of Caret and dollar sign characters in regular expression. 6
✓ The caret symbol (^) at the start of a regex is used to indicate that a match must occur at
the beginning of the searched text.
✓ The dollar sign ($) at the end of the regex is used to indicate that a match must occur at the end of
the searched text.
✓ Both the symbols can be used ^ and $ together to indicate that the entire string must match the
regex.
✓ Ex: It checks whether the string starts with Hello.
x = re.compile(r‟^Hello‟)
x.search(„Hello world!‟)
✓ Ex: It checks whether the string starts and ends with Hello.
x = re.compile(r‟^Hello$‟)
x.search(„Hello Hello‟)
9 Write a python program to extract phone numbers and email addresses using regex. 7
import pyperclip, re
phoneRegex = re.compile(r'''(
(\d{3}|\(\d{3}\))? # area code
(\s|-|\.)? # separator
(\d{3}) # first 3 digits
(\s|-|\.) # separator
(\d{4}) # last 4 digits
(\s*(ext|x|ext.)\s*(\d{2,5}))? # extension
)''', re.VERBOSE)
21
(\.[a-zA-Z]{2,4}){1,2} # dot-something
)''', re.VERBOSE)
matches = []
for groups in phoneRegex.findall(text):
phoneNum = '-'.join([groups[1], groups[3], groups[5]])
if groups[8] != '':
phoneNum += ' x' + groups[8]
matches.append(phoneNum)
for groups in emailRegex.findall(text):
matches.append(groups[0])
o
✓ Since C:\Python34 was the working directory when os.path.abspath() was called, the “single-dot”
folder represents the absolute path 'C:\\Python34'.
22
✓ Calling os.path.dirname(path) will return a string of everything that comes before the last slash in
the path argument.
✓ Calling os.path.basename(path) will return a string of everything that comes after the last slash in
the path argument.
➢ Example:
✓ The variables can be saved in Python programs to binary shelf files using the shelve module.
✓ This helps the program to restore data to variables from the hard drive.
✓ The shelve module will let us add Save and Open features to your program.
✓ Example:
12 With code snippet, explain reading, extracting and creating ZIP files. 6
23
Creating ZIP Files:
✓ To create our own compressed ZIP files, must open the ZipFile object in write mode by
passing 'w' as the second argument.
✓ The write() method‟s first argument is a string of the filename to add.
✓ The second argument is the compression type parameter, which tells the computer what algorithm
it should use to compress the files; we can always just set this value to zipfile.ZIP_DEFLATED
✓ The extractall() method for ZipFile objects extracts all the files and folders from a ZIP file into the
current working directory.
✓ After running the below code, the contents of example.zip will be extracted to C:\.
✓ The extract() method for ZipFile objects will extract a single file from the ZIP file.
MODULE 5
1 Define classes and objects in Python. Create a class called Employee and initialize it with 8
employee id and name. Design methods to:
i) setAge_to assign age to employee.
ii) setSalary_to assign salary to the employee.
iii) Display_to display all information of the employee.
class student( ):
def display(self):
print(self.name)
print(self.roll)
24
def setAge(self, age):
self.age = age
Ex: In the below example the object start has been passed as parameters and it has been changed by
adding seconds to it. Hence, it is a modifier.
init : The init method (short for “initialization”) is a special method that gets invoked when an
object is instantiated. The parameters of init to have the same names as the attributes.
Ex:
25
If function is called with no If function is called with one If function is called with two
arguments then, default values arguments then, it overrides arguments then, it overrides
will be printed. hour. hour, minutes.
>>> time = Time() >>> time = Time (9) >>> time = Time(9, 45)
>>> time.print_time() >>> time.print_time() >>> time.print_time()
00:00:00 09:00:00 09:45:00
If function is called with three arguments then, all the values will be overridden.
Ex:
Polymorphism: Functions that work with several types are called polymorphic. Polymorphism can
facilitate code reuse.
Ex:
This function also works for lists, tuples, and
even dictionaries, as long as the elements of s
are hashable, so they can be used as keys in
d:
26
Program: To count the frequency Output
Pure Function: It does not modify any of the objects passed to it as arguments and it has no effect,
like displaying a value or getting user input, other than returning a value.
Ex: In the below example the two objects start and duration have been passed as parameters to
function add_time and it doesn‟t modify the objects received. Hence, it is a pure function.
27
28
*6 Define Class Diagram. Discuss the need for representing class relationships using Class 7
Diagram with suitable example.
Stack diagram represents the state of a program, object diagram represents the attributes and their
values and both are very detailed. Whereas, Class diagram represents the abstract representation of
structure of program. There are several kinds of relationships between classes:
1. Objects in one class might contain references to objects in another class. For example, each
Rectangle contains a reference to a Point, and each Deck contains references to many Cards. This
kind of relationship is called HAS-A, as in, “a Rectangle has a Point.”
2. One class might inherit from another. This relationship is called IS-A, as in, “a Hand is a kind of
a Deck.”
3. One class might depend on another in the sense that changes in one class would require changes
in the other.
➢ IS-A relationship → Arrow with a hallow triangle head → Hand inherits from Deck
➢ HAS-A relationship → Standard Arrow → Deck has reference to card objects.
➢ Star(*) → Multiplicity → Indicates how many cards a deck has.
7 What is class? How do we define a class in python? How to instantiate the class and how class 8
members are accessed?
✓ Class is a abstract data type which can be defined as a template or blueprint that describes the
behavior / state that the object of its type support.
✓ The header indicates that the new class is called Point.
✓ The body is a docstring that explains what the class is for. You can define variables and methods
inside a class definition.
✓ The process of creating this object is called instantiation
✓ Class can be used to create new object instances (instantiation) of that class.
✓ The class members are accessed using dot operator as shown below:
class Point:
“ “ “ Represents a point in 2-D space “ “ “
blank = Point( )
blank.x = 10
blank.y =20
8 Write a python program that uses datetime module within a class , takes a birthday as input 7
and prints user‟s age and the number of days, hours ,minutes and seconds until their next
birthday.
import datetime
def get_user_birthday():
year = int(input('When is your birthday? [YY] '))
month = int(input('When is your birthday? [MM] '))
day = int(input('When is your birthday? [DD] '))
birthday = datetime.datetime(year,month,day)
return birthday
def show_info(self):
pass
bd = get_user_birthday()
now = datetime.datetime.now()
c = calculate_dates(bd,now)
print(c)
Program: Output:
class A: 3
def init (self, a):
self.a = a -1
ob1 = A(1)
ob2 = A(2)
ob3 = A("Python")
ob4 = A("Applications")
print(ob1 + ob2)
print(ob1 - ob2)
print(ob1 * ob2)
print(ob3 + ob4)
Inheritance: The ability to define a new class that is a modified version of a previously defined
class. The class from which a child class inherits is called as Parent Class. A new class created by
inheriting from an existing class is called as Child class or Sub Class. The parent class will be
represented in parenthesis while defining child class. Inheritance can facilitate code reuse and also
behavior of parent classes can be customized without having to modify them.
Ex:
In the above example deck is parent class and hand is child class and the hand class can use add_card
and pop_card.