Summer 2024 Examination Model Answer Only For The Use of RAC Assessors Subject Name: Programming With Python Subject Code
Summer 2024 Examination Model Answer Only For The Use of RAC Assessors Subject Name: Programming With Python Subject Code
(Autonomous)
                                                 (ISO/IEC - 27001 - 2013 Certified)
              _________
                                            SUMMER – 2024 EXAMINATION
                                    Model Answer – Only for the Use of RAC Assessors
                                                                                                           Page No: 1 | 19
                         MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                  (Autonomous)
                                        (ISO/IEC - 27001 - 2013 Certified)
      _________
        reverse (Optional): for reverse=True, it will sort the list descending. Default is
        reverse=False
        key (Optional): A function to specify the sorting criteria.
d)      Write use of matplotlib package in python.                                                        2M
Ans     Data abstraction: Data Abstraction is used to hide the internal functionality of the             1M
        function from the users. The users only interact with the basic implementation of the
        function, but inner working is hidden. User is familiar with that "what function                  (for
        does" but they don't know "how it does."                                                     definition of
                                                                                                         data
        Data hiding: Data hiding is a concept which underlines the hiding of data or information      abstraction
        from the user. Data hiding is a software development technique specifically used in            and data
        Object-Oriented Programming (OOP) to hide internal object details (data members).               hiding)
        Data hiding includes a process of combining the data and functions into a single unit to
        conceal data within a class by restricting direct access to the data from outside the class.
g) What is dictionary? 2M
                                                                                                Page No: 2 | 19
                              MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                      (Autonomous)
                                            (ISO/IEC - 27001 - 2013 Certified)
           _________
2.           Attempt any THREE of the following:                                                           12 M
                                                     Figure of Indentation
                       • Example:
                                if True:
                                   print "True"
                                else:
                                   print "False"
                     • Thus, in Python all the continuous lines indented with same number of spaces
                        would form a block.
                 ii) Variables:
                     • Python Variable is containers that store values.
                     • We do not need to declare variables before using them or declare their type.
                     • A variable is created the moment we first assign a value to it.
                     • A Python variable is a name given to a memory location.
                     • It is the basic unit of storage in a program.
                     • Variable Naming Rules in Python
                        1) Variable name should start with letter(a-z ,A-Z) or underscore (_).
                            Example: age, _age, Age
                        2) In variable name, no special characters allowed other than underscore (_).
                            Example: age_, _age
                        3) Variables are case sensitive.
                            Example: age and Age are different, since variable names are case
                            sensitive.
                        4) Variable name can have numbers but not at the beginning.
                            Example: Age1
                        5) Variable name should not be a Python reserved keyword.
                     • Example:
                                                                                                 Page No: 3 | 19
                         MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                       (Autonomous)
                                          (ISO/IEC - 27001 - 2013 Certified)
      _________
                          x = 5 # x is of type integer
                          y = "John" # y is of type string
b)      Print the following pattern using loop:                                         4M
                                              1010101
                                               10101
                                                 101
                                                   1
Ans                  p = '1'                                                             4M
                     q = '0'                                                          (for any
                     j=0                                                               correct
                     k=4                                                              program
                     while k >= 1:                                                   with proper
                       print(" "*j + (k-1)*(p+q) +p+ " "*j)                             logic)
                       k = k-1
                       j=j+1
c)      Write python program to perform following operations on set.                    4M
i) Numpy
ii) Pandas
Ans         i) Numpy                                                                     2M
                                                                                      (for each
                                                                               Page No: 4 | 19
                     MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                             (Autonomous)
                                   (ISO/IEC - 27001 - 2013 Certified)
_________
            •   NumPy is the fundamental package for scientific computing with Python.            correct
                NumPy stands for "Numerical Python". It provides a high-performance             explanation)
                multidimensional array object, and tools for working with these arrays.
            •   An array is a table of elements (usually numbers), all of the same type,
                indexed by a tuple of positive integers and represented by a single variable.
                NumPy's array class is called ndarray. It is also known by the alias array.
            •   In NumPy arrays, the individual data items are called elements. All elements
                of an array should be of the same type. Arrays can be made up of any
                number of dimensions.
            •   In NumPy, dimensions are called axes. Each dimension of an array has a
                length which is the total number of elements in that direction.
            •   The size of an array is the total number of elements contained in an array in
                all the dimension. The size of NumPy arrays are fixed; once created it cannot
                be changed again.
            •   Numpy arrays are great alternatives to Python Lists. Some of the key
                advantages of Numpy arrays are that they are fast, easy to work with, and
                give users the opportunity to perform calculations across entire arrays.
            Figure shows the axes (or dimensions) and lengths of two example arrays;
            (a) is a one-dimensional array and (b) is a two-dimensional array.
      ii) Panda
          • Pandas is a powerful and versatile library that simplifies the tasks of data
             manipulation in Python.
          • Pandas is well-suited for working with tabular data, such as spreadsheets or
             SQL tables.
          • The Pandas library is an essential tool for data analysts, scientists, and
             engineers working with structured data in Python.
          • It is built on top of the NumPy library which means that a lot of the
             structures of NumPy are used or replicated in Pandas.
          • The data produced by Pandas is often used as input for plotting functions in
             Matplotlib, statistical analysis in SciPy, and machine learning algorithms in
             Scikit-learn.
                                                                                          Page No: 5 | 19
                                  MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                       (Autonomous)
                                             (ISO/IEC - 27001 - 2013 Certified)
           _________
3.           Attempt any THREE of the following:                                              12 M
dict1.update(dict2);
                                                                                     Page No: 6 | 19
                          MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                  (Autonomous)
                                        (ISO/IEC - 27001 - 2013 Certified)
      _________
        Output: 12321 is a palindrome.
c)      Write a python program to create a user defined module that will ask your                         4M
        program name and display the name of the program.
d) List data types used in python. Explain any two with example. 4M
Ans     Python has various standard data types that are used to define the operations possible on       2 M for
        them and the storage method for each of them. Data types in Python programming                   types,
        includes:
                                                                                                       2 M for two
        1. Numbers: Represents numeric data to perform mathematical operations.
                                                                                                         proper
        2. String: Represents text characters, special symbols or alphanumeric data.                    examples
        3. List: Represents sequential data that the programmer wishes to sort, merge etc.
        4. Tuple: Represents sequential data with a little difference from list.
        5. Dictionary: Represents a collection of data that associate a unique key with each value.
        6. Boolean: Represents truth values (true or false).
        Example1: Tuple Data Type
        • Tuple is an ordered sequence of items same as list. The only difference is that tuples are
        immutable. Tuples once created cannot be modified.
        • Tuples are used to write-protect data and are usually faster than list as it cannot change
        dynamically. It is defined within parentheses ( ) where items are separated by commas ( ,
        ).
                                                                                                Page No: 7 | 19
                                  MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                          (Autonomous)
                                                (ISO/IEC - 27001 - 2013 Certified)
           _________
                 •      A tuple data type in python programming is similar to a list data type, which also
                        contains heterogeneous items/elements.
             Example: For tuple.
             a=(10,'abc',1+3j)
             print(a)
             (10, 'abc', (1+3j))
             Example 2:List Data Type
             List is an ordered sequence of items. It is one of the most used datatype in Python and is
             very flexible.
             • List can contain heterogeneous values such as integers, floats, strings, tuples, lists and
             dictionaries but they are commonly used to store collections of homogeneous objects.
             • The list datatype in Python programming is just like an array that can store a group of
             elements and we can refer to these elements using a single name.
             • Declaring a list is pretty straight forward. Items separated by commas ( , ) are enclosed
             within brackets [ ].
             Example:
             For list.
             first=[10, 20, 30]
             # homogenous values in list
             second=["One","Two","Three"]
             Print(first)
             [10, 20, 30]
             Print(second)
             ['One', 'Two', 'Three']
                                                                                                      Page No: 8 | 19
                          MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                     (Autonomous)
                                          (ISO/IEC - 27001 - 2013 Certified)
      _________
                  The implication of iterations is            The implication of iterations is               correct
           2
                  Time-consuming                              comparatively Faster                           points.
                  Unexpected changes and errors are           Because tuples don’t change they are
           6
                  more likely to occur                        far less error-prone.
b)      Write a python program takes in a number and find the sum of digits in a                              4M
        number.
c)      Write a program function that accepts a string and calculate the number of                            4M
        uppercase letters and lower case letters.
upperlower(Str)
        Output -
        Enter a String -: Welcome to Python programing
        The number of lowercase characters is: 23
        The number of uppercase characters is: 2
or
print('Lower case characters = %s' %lower, '\nUpper case characters = %s' %upper)
upperlower(string)
        Output-
        Enter a String -: Welcome to Python programming
        Lower case characters = 24
        Upper case characters = 2
d)      Write a python program to create class student with roll-no. and display its                      4M
        contents.
                                                                                                 Page No: 10 | 19
                           MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                   (Autonomous)
                                         (ISO/IEC - 27001 - 2013 Certified)
      _________
          def display_data(self):
             print(f"Roll No: {self.rollno}")
        student1 = Student(10)
        student1.display_data()
        Output:
        Rollno = 10
        In addition you can specify if the file should be handled as binary or text mode
        "t" - Text - Default value. Text mode
        "b" - Binary - Binary mode (e.g. images)
                                                                                                 Page No: 11 | 19
                               MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                       (Autonomous)
                                             (ISO/IEC - 27001 - 2013 Certified)
          _________
            Example:
            f = open("demofile.txt", "r")
            print(f.read())
Where the specified text will be inserted depends on the file mode and stream position.
            "a": The text will be inserted at the current file stream position, default at the end of the
            file.
            "w": The file will be emptied before the text will be inserted at the current file stream
            position, default 0.
            Syntax:
            file.write(byte)
            byte: The text or byte object that will be inserted.
            Example:
            Open the file with "a" for appending, then add some text to the file:
            f = open("demofile2.txt", "a")
            f.write("Hi!")
            f.close()
a) Write the output for the following if the variable course = "Python" 6M
>>> course [ : 3 ]
>>> course [ 3 : ]
>>> course [ 2 : 2 ]
                                                                                                      Page No: 12 | 19
                          MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                  (Autonomous)
                                        (ISO/IEC - 27001 - 2013 Certified)
      _________
        >>> course [-1]
course[3:]
Ans: hon
>>>course[2:2]
        Ans: a slice starting and ending at the same index, which results in an empty string. Slicing
        in this way doesn't include any characters between the specified indices.
>>>course[:]
Ans: Python
>>>course[-1]
Ans: n
>>> course[1]
Ans: y
# If you want to generate an array of random integers, you can specify the size
                                                                                                 Page No: 13 | 19
                              MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                        (Autonomous)
                                              (ISO/IEC - 27001 - 2013 Certified)
           _________
             CO diploma" and "I am with IF diploma' respectively. Call the method by
             creating an object of each of the three classes.
class CO(Diploma):
def getdiploma(self):
class IF(Diploma):
def getdiploma(self):
diploma_obj = Diploma()
co_obj = CO()
if_obj = IF()
                                                                                        Page No: 14 | 19
                           MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                      (Autonomous)
                                            (ISO/IEC - 27001 - 2013 Certified)
      _________
Ans     Multiple inheritance is a feature in object-oriented programming where a class can               2 M-
        inherit attributes and methods from more than one parent class. This allows a class to        Explanation,
        combine and reuse code from multiple classes, promoting code reuse and modular                 4 M-any
                                                                                                        suitable
        design.
                                                                                                       example
        In Python, you can achieve multiple inheritance by specifying multiple parent classes in
        the definition of a child class.
Program:
class Person:
self.name = name
self.age = age
def display_person(self):
class Employee:
self.employee_id = employee_id
self.position = position
def display_employee(self):
                                                                                                 Page No: 15 | 19
                          MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                  (Autonomous)
                                        (ISO/IEC - 27001 - 2013 Certified)
      _________
             self.department = department
def display_manager(self):
self.display_person()
self.display_employee()
print(f"Department: {self.department}")
manager.display_manager()
b)      Write a Python program to create user defined exception that will check                   6M
        whether the password is correct or not.
self.message = message
def check_password(input_password):
if input_password != correct_password:
else:
                                                                                        Page No: 16 | 19
                            MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                      (Autonomous)
                                            (ISO/IEC - 27001 - 2013 Certified)
      _________
                print("Password is correct. Access granted.")
try:
check_password(user_password)
except InvalidPasswordException as e:
print(e)
                      •   When opened in this mode, attempting to write to the file will raise a
                          UnsupportedOperation error.
                      •   Example: open('file.txt', 'r')
               2. Write Mode ('w'):
                      •   Opens the file for writing. If the file doesn't exist, it creates a new file.
                      •   If the file already exists, it truncates the file to zero length.
                      •   Example: open('file.txt', 'w')
               3. Append Mode ('a'):
                      •   Opens the file for writing. If the file doesn't exist, it creates a new file.
                      •   If the file already exists, it appends data to the end of the file.
                      •   Example: open('file.txt', 'a')
               4. Binary Mode ('b'):
                      •   Opens the file in binary mode. It's used in conjunction with other modes
                          like read ('rb'), write ('wb'), or append ('ab') to deal with binary files like
                          images, executables, etc.
                      •   Example: open('image.jpg', 'rb')
               5. Text Mode ('t'):
                                                                                                          Page No: 17 | 19
                  MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                            (Autonomous)
                                  (ISO/IEC - 27001 - 2013 Certified)
_________
            •   This is the default mode for text files (although you don't explicitly specify
                it). It's used to handle text files and performs encoding/decoding of text
                automatically.
            •   Example: open('file.txt', 'rt')
      6. Read and Write Mode ('r+'):
            •   Opens the file for both reading and writing.
            •   The file pointer is at the beginning of the file.
            •   Example: open('file.txt', 'r+')
      7. Write and Read Mode ('w+'):
            •   Opens the file for both reading and writing.
            •   If the file doesn't exist, it creates a new file.
            •   If the file exists, it truncates the file to zero length.
            •   Example: open('file.txt', 'w+')
  Detailed Explanation of Three Modes:
                                                                                          Page No: 18 | 19
                  MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                          (Autonomous)
                                (ISO/IEC - 27001 - 2013 Certified)
_________
            •   It's useful when you want to add data to an existing file without overwriting
                its contents.
            •   Common use cases include logging, adding new entries to a file, or
                maintaining a history of operations.
                                                                                         Page No: 19 | 19
              MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                   (Autonomous)
                      (ISO/IEC - 27001 - 2013 Certified)
                                                                                     Page 1 / 23
             MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                  (Autonomous)
                     (ISO/IEC - 27001 - 2013 Certified)
                                                                                        Page 2 / 23
             MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                  (Autonomous)
                     (ISO/IEC - 27001 - 2013 Certified)
                                                                                     Page 3 / 23
             MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                  (Autonomous)
                     (ISO/IEC - 27001 - 2013 Certified)
             if-else Statement
             The if-else statement is used to test a condition. If the condition is
             True, the code inside the if block is executed. If the condition is
             False, the code inside the else block is executed.
             Syntax:
             if condition:
                # Code block to execute if the condition is True
             else:
                # Code block to execute if the condition is False
             Example:
             age = 16
             if age >= 18:
             print("You are eligible to vote.")
             else:
             print("You are not eligible to vote.")
             if-elif-else Statement
             The if-elif-else statement is used when there are multiple conditions
             to check. Python evaluates each if or elif condition in sequence. If
             one of the conditions evaluates to True, the corresponding block of
             code is executed, and the rest are skipped. If none of the if or elif
             conditions are True, the code inside the else block is executed.
                                                                                      Page 4 / 23
             MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                  (Autonomous)
                     (ISO/IEC - 27001 - 2013 Certified)
             Syntax:
             if condition1:
                # Code block to execute if condition1 is True
             elif condition2:
                # Code block to execute if condition1 is False and condition2 is
             True
             else:
                # Code block to execute if both condition1 and condition2 are
             False
             Example:
             age = 25
             if age < 13:
             print("You are a child.")
             elif 13 <= age <= 19:
             print("You are a teenager.")
             elif 20 <= age <= 59:
             print("You are an adult.")
             else:
             print("You are a senior.")
                                                                                    Page 5 / 23
             MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                  (Autonomous)
                     (ISO/IEC - 27001 - 2013 Certified)
             Example:
             fruits = ['apple', 'banana', 'cherry', 'banana']
             fruits.remove('banana') # Removes the first occurrence of 'banana'
             print(fruits)
                                                                                           Page 6 / 23
             MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                  (Autonomous)
                     (ISO/IEC - 27001 - 2013 Certified)
                                                                                     Page 7 / 23
                 MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                      (Autonomous)
                         (ISO/IEC - 27001 - 2013 Certified)
                                                                                             Page 8 / 23
                 MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                      (Autonomous)
                         (ISO/IEC - 27001 - 2013 Certified)
                                                                                             Page 9 / 23
            MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                 (Autonomous)
                    (ISO/IEC - 27001 - 2013 Certified)
Method Description
                                                                                     Page 10 / 23
             MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                  (Autonomous)
                     (ISO/IEC - 27001 - 2013 Certified)
                                                                                   Page 11 / 23
             MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                  (Autonomous)
                     (ISO/IEC - 27001 - 2013 Certified)
             Example:
             def square( x ):
             print("Square=",x*x)
             # Driver code
             square(2)
             Output:
             Square= 4
                                                                                    Page 12 / 23
            MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                 (Autonomous)
                    (ISO/IEC - 27001 - 2013 Certified)
             def disp_price(self):
             print("Price=$",self.price)
             car1=Category()
             car1.display()
             car1.disp_price()
             Output:
             Name= Maruti
             Price=$ 2000
                                                                         Page 13 / 23
             MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                  (Autonomous)
                     (ISO/IEC - 27001 - 2013 Certified)
             2) Continue statement
             This command skips the current iteration of the loop. The statements
             following the continue statement are not executed once the Python
             interpreter reaches the continue statement.
             Example :
             for letter in 'python program':
                if letter == 'y' or letter == 'm':
                    continue
                print('Current Letter :', letter)
              Current Letter : p
              Current Letter : t
              Current Letter : h
              Current Letter : o
              Current Letter : n
              Current Letter : p
              Current Letter : r
              Current Letter : o
              Current Letter : g
              Current Letter : r
              Current Letter : a
                                                                                    Page 14 / 23
             MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                  (Autonomous)
                     (ISO/IEC - 27001 - 2013 Certified)
             3) Pass statement
             The pass statement is used when a statement is syntactically
             necessary, but no code is to be executed.
             Last Letter : n
       b)    Illustrate with example Method overloading                                 4M
      Ans.   It is the ability to define the method with the same name but with a
                                                                                       2M for
             different number of arguments and data types. With this ability one     explanation
             method can perform different tasks, depending on the number of
             arguments or the types of the arguments given.                            2M for
                                                                                      example
             Method overloading is a concept in which a method in a class
             performs operations according to the parameters passed to it. As in
             other languages we can write a program having two methods with
             same name but with different number of arguments or order of
             arguments but in python if we will try to do the same we will get the
             following issue with method overloading in Python:
             # to calculate area of rectangle
             def area(length, breadth):
             calc = length * breadth
             print calc
             #to calculate area of square
             def area(size):
             calc = size * size
             print calc
             area(3)
             area(4,5)
             Output:
             9
             TypeError: area() takes exactly 1 argument (2 given)
                                                                                 Page 15 / 23
             MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                  (Autonomous)
                     (ISO/IEC - 27001 - 2013 Certified)
             Python does not support method overloading, that is, it is not possible
             to define more than one method with the same name in a class in
             Python.
             This is because method arguments in python do not have a type. A
             method accepting one argument can be called with an integer value, a
             string or a double as shown in next
             example.
             class Demo:
             def method(self, a):
             print(a)
             obj= Demo()
             obj.method(50)
             obj.method('Meenakshi')
             obj.method(100.2)
             Output:
             50
             Meenakshi
             100.2
             Same method works for three different data types. Thus, we cannot
             define two methods with the same name and same number of
             arguments but having different type as shown in the above example.
             They will be treated as the same method. It is clear that method
             overloading is not supported in python but that does not mean that we
             cannot call a method with different number of arguments. There are a
             couple of alternatives available in python that make it possible to call
             the same method but with different number of arguments.erample
             method overloading
                                                                                    Page 16 / 23
             MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                  (Autonomous)
                     (ISO/IEC - 27001 - 2013 Certified)
             try:
                ans=a/b
             print("ANS :",ans)
             except ZeroDivisionError:
             print("Division by Zero........")
             output :
             Enter the value of a : 10
             Enter the value of b : 0
             Division by Zero..........
       d)    Write the output for the following if the variable fruit : .banana              4M
      Ans.   >> fruit [:3]                                                                  Each
             Output : ban                                                                  correct
                                                                                          output 1M
             >> fruit [3:]
             Output : ana
             >> fruit [3:3]
             Output :
             >> fruit [:]
             Output : banana
       e)    Write a Python program to read contents from "a.txt" and write                  4M
             same contents in "b.txt".                                                   Any suitable
      Ans.   with open("a.txt", "r") as read_file, open("b.txt", "w") as write_file:       program
                                                                                         with correct
               content = read_file.read()                                                 syntax 4M
               write_file.write(content)
5.           Attempt any TWO of the following:                                          12M
       a)    Explain basic operation performed on set with suitable example.             6M
      Ans.   In Python, sets are a built-in data structure that allows you to perform 2M for each
             a variety of operations. Python provides methods and operators to operation
             perform the basic set operations, such as union, intersection,
             difference, symmetric difference
             1. Union ( | or union() )
             The union of two sets combines all elements from both sets,
             removing duplicates.
             A = {1, 2, 3}
             B = {3, 4, 5}
             print( A | B) # Output: {1, 2, 3, 4, 5}
             print( A.union(B)) # Output: {1, 2, 3, 4, 5}
                                                                                       Page 17 / 23
             MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                  (Autonomous)
                     (ISO/IEC - 27001 - 2013 Certified)
             3. Difference ( - or difference() )
             The difference of two sets returns a set containing elements present in
             the first set but not in the second.
             A = {1, 2, 3}
             B = {3, 4, 5}
             print( A– B) # Output: {1, 2}
             print(A.difference(B))# Output: {1, 2}
                                                                                       Page 18 / 23
             MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                  (Autonomous)
                     (ISO/IEC - 27001 - 2013 Certified)
             defprint_details(self):
             print("Student Details:")
             print(f"Name: {self.name}")
             print(f"Roll No: {self.roll_no}")
             print(f"Address: {self.address}")
                                                                             Page 19 / 23
             MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                  (Autonomous)
                     (ISO/IEC - 27001 - 2013 Certified)
student.print_details()
             OUTPUT:
             Enter the student's name:
             Alice
             Enter the student's roll number:101
             Enterthestudent'saddress:123MainSt
             Student Details:
             Name:Alice
             Roll No:101
             Address:123MainSt
6.           Attempt any TWO of the following:                                           12M
       a)    Determine various data types available in Python with example.               6M
      Ans.   Python provides a variety of built-in data types, which can be
             classified into several categories based on their characteristics. Here's 2M for each
             a detailed description of the most common data types in Python with        category
             examples:
             1. Numeric Types
             Numeric types are used to store numbers.
             a. Integer (int)
             An integer is a whole number without a decimal point.
             x = 10 # Integer
             y = -25 # Negative integer
             print(x, type(x))
              # Output: 10 <class 'int'>
             b. Floating-Point (float)
             A float is a number that has a decimal point or is in exponential form.
             x = 3.14 # Float
             y = -2.71 # Negative float
             print(x, type(x))
             # Output: 3.14 <class 'float'>
                                                                                       Page 20 / 23
            MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                 (Autonomous)
                    (ISO/IEC - 27001 - 2013 Certified)
             2. Sequence Types
             Sequence types store an ordered collection of items.
             a. String (str)
             A string is a sequence of characters enclosed within single (') or
             double (") quotes.
             name = "John" # String
             message = 'Hello, World!'
             print(name, type(name)) # Output: John <class 'str'>
             . List (list)
             A list is an ordered, mutable collection that can contain elements of
             any data type, including other lists.
             fruits = ['apple', 'banana', 'cherry'] # List
             print(fruits, type(fruits)) # Output: ['apple', 'banana', 'cherry'] <class
             'list'>
             3. Mapping Type
             Mapping types store key-value pairs.
             a. Dictionary (dict)
             A dictionary is an unordered, mutable collection of key-value pairs,
             where each key is unique.
             person = {'name': 'Alice', 'age': 25, 'city': 'New York'}
             print(person, type(person)) # Output: {'name': 'Alice', 'age': 25, 'city':
             'New York'} <class 'dict'>
             4. Set Types
             Set types are used to store unordered collections of unique elements.
             a. Set (set)
             A set is an unordered collection of unique elements, and it is mutable
             (you can add or remove items).
             fruits = {'apple', 'banana', 'cherry'} # Set
             print(fruits, type(fruits)) # Output: {'banana', 'apple', 'cherry'} <class
             'set'>
                                                                                          Page 21 / 23
             MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                  (Autonomous)
                     (ISO/IEC - 27001 - 2013 Certified)
             Explanation:
             Opening first.txt:
             The open() function is used with the 'r' mode to open first.txt in read
             mode.
             with open() is used to ensure the file is properly closed after the
             operation is complete.
             Reading the contents:
             file1.read() reads the entire content of first.txt into the variable
             content.
             Opening second.txt:
             The open() function is used with the 'w' mode to open second.txt in
             write mode.
             If second.txt does not exist, it will be created automatically.
             Writing the contents:
             file2.write(content) writes the content read from first.txt into
             second.txt.
       c)    Explain Try-except-else-finally block used in exception handling                   6M
             in Python with example.
      Ans.   The try-except-else-finally block is a comprehensive way to handle                Each
             exceptions in Python. It allows you to test a block of code for errors         explanatio
             (try), handle the errors if they occur (except), execute code if no             n ,syntax
             errors occur (else), and execute cleanup code regardless of whether an             and
             error occurred or not (finally).                                                example
                                                                                                2M
             try:
                # Code that might raise an exceptionexcept ExceptionType:
                # Code to handle the exception
             else:
                                                                                        Page 22 / 23
            MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                 (Autonomous)
                    (ISO/IEC - 27001 - 2013 Certified)
             Explanation of Components
             try Block: Contains the code that might raise an exception.
             except Block: Catches and handles the exception.
             else Block: Executes if the try block succeeds without any exceptions.
             finally Block: Executes regardless of whether an exception was raised
             or not. Typically used for cleanup tasks.
Example:
             try:
                # Try to open and read a file
                file = open("example.txt", "r")
                content = file.read()
                print(content)
             except FileNotFoundError:
                # Handle the specific exception if the file doesn't exist
             print("Error: The file was not found.")
             except IOError:
                # Handle other I/O errors
             print("Error: An IOError occurred.")
             else:
                # Executes if no exceptions were raised
             print("File was read successfully!")
             finally:
                # Always executes, used to clean up resources
                try:
             file.close()
             print("File has been closed.")
                except NameError:
                   print("File object does not exist.")
                                                                                  Page 23 / 23
                                  MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                           (Autonomous)
                                                 (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
                                               WINTER – 2023 EXAMINATION
                                  Model Answer – Only for the Use of RAC Assessors
Subject Name: Programming with Python                                                   Subject Code: 22616  22616
Important Instructions to examiners:
   1) The answers should be examined by key words and not as word-to-word as given in the model answer scheme.
   2) The model answer and the answer written by candidate may vary but the examiner may try to assess the understanding
      level of the candidate.
   3) The language errors such as grammatical, spelling errors should not be given more Importance (Not applicable for
      subject English and Communication Skills.
   4) While assessing figures, examiner may give credit for principal components indicated in the figure. The figures drawn
      by candidate and model answer may vary. The examiner may give credit for any equivalent figure drawn.
   5) Credits may be given step wise for numerical problems. In some cases, the assumed constant values may vary and
      there may be some difference in the candidate’s answers and model answer.
   6) In case of some questions credit may be given by judgement on part of examiner of relevant answer based on
      candidate’s understanding.
   7) For programming language papers, credit may be given to any other program based on equivalent concept.
   8) As per the policy decision of Maharashtra State Government, teaching in English/Marathi and Bilingual (English +
      Marathi) medium is introduced at first year of AICTE diploma Programme from academic year 2021-2022. Hence if
      the students in first year (first and second semesters) write answers in Marathi or bilingual language (English
      +Marathi), the Examiner shall consider the same and assess the answer based on matching of concepts with model
      answer.
        Ans            Google's App Engine web development framework uses Python as an application              Any two
                        language.                                                                               application,
                       Maya, a powerful integrated 3D modeling and animation system, provides a Python       One application
                        scripting API.                                                                         for 1 M each
                       Linux Weekly News, published by using a web application written in Python.
                       Google makes extensive use of Python in its Web Search Systems.
                       The popular YouTube video sharing service is largely written in Python
                        programming.
                       The NSA uses Python for cryptography and intelligence analysis.
                       iRobot uses Python programming to develop commercial and military robotic devices.
                       The Raspberry Pi single-board computer promotes Python programming as its
                        educational language.
                       Nextflix and Yelp have both documented the role of Python in their software
                        infrastructures.
                       Industrial Light and Magic, Pixar and others uses Python in the production of
                        animated movies.
                       Desktop GUI Applications
                       Image Processing Applications
                       Scientific and Numeric Applications
                       Audio and Video Based Applications
                       3D CAD Applications
                                                                                                             Page No: 1 | 20
                                 MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                           (Autonomous)
                                                 (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
                     Software Development
                     Web Applications
       b)     Write the use of elif keyword in python.                                                                 2M
       Ans    elif' stands for 'else if' and is used in Python programming to test multiple conditions.               Correct
              The if statements are executed from the top down. As soon as one of the conditions controlling       explanation 2
              the if is true, the statement associated with that if is executed, and the rest of the ladder is          M
              bypassed. If none of the conditions is true, then the final else statement will be executed.
       Ans             Indentation refers to the spaces at the beginning of a code line.                         Correct Role 2
                       Generally, four whitespaces are used for indentation and is preferred over tabs.                M
                       Where in other programming languages the indentation in code is for readability only,
                        the indentation in Python is very important.
                    Indentation helps to convey a better structure of a program to the readers. It is used to
                        clarify the link between control flow constructs such as conditions or loops, and code
                        contained within and outside of them.
                    Python uses indentation to indicate a block of code.
              Example:
              if 5 > 2:
                   print("Five is greater than two!")
       d)     Define Data Hiding concept? Write two advantages of Data Hiding.                                         2M
       Ans           Data hiding is a concept which underlines the hiding of data or information from the         Any relevant
                      user.                                                                                       Definition 1 M,
                     Data hiding is a software development technique specifically used in Object-Oriented
                                                                                                                     any two
                      Programming (OOP) to hide internal object details (data members).
                     Data hiding includes a process of combining the data and functions into a single unit        Advantages 1
                      to conceal data within a class by restricting direct access to the data from outside the          M
                      class.
       Ans           Namespaces bring you three advantages: they group names into logical Correct/relevant
                      containers, they prevent clashes between duplicate names, and third, they use 2 M
                      provide context to names.
                                                                                                                 Page No: 2 | 20
                                MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                        (Autonomous)
                                              (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
                    Namespaces prevent conflicts between classes, methods and objects with the
                     same name that might have been written by different people.
                  A namespace is a system to have a unique name for each and every object in
                     Python. An object might be a variable or a method. Python itself maintains a
                     namespace in the form of a Python dictionary.
                  A namespace in python is a collection of names. So, a namespace is essentially
                     a mapping of names to corresponding objects.
       f)     State the use of read() and readline () functions in python file handling.                        2M
              2. readline([n]) Method:
              The readline() method just output the entire line whereas readline(n) outputs at most
              n bytes of a single line of a file. It does not read more than one line. Once, the end of
              file is reached, we get empty string on further reading.
              Example: For readline ( ) method.
              f=open("sample.txt","r")
              print(f.readline()) # read first line followed by\n
              print(f.readline(3))
              print(f.readline())
       g)     Explain two ways to add objects / elements to list.                                               2M
       Ans    1)append method: The append() method adds an element to the end of a list. We can insert     1 Method for 1
              a single item in the list data time with the append().                                         M (any two
              Example: For append() method.
              >>> list1=[10,20,30]                                                                            methods)
              >>> list1
              [10, 20, 30]
              >>> list1.append(40)         # add element at the end of list
              >>> list1                                                                                    (example is not
              [10, 20, 30, 40]                                                                               mandatory)
              2. extend() Method: The extend() method extends a list by appending items. We can add
              several items using extend() method.
              Example: Program for extend() method.
              >>>list1=[10, 20, 30, 40]
              >>>list1
              [10, 20, 30, 40]
              >>> list1.extend([60,70])     #add elements at the end of list
              >>> list1
              [10, 20, 30, 40, 60, 70]
                                                                                                          Page No: 3 | 20
                                MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                          (Autonomous)
                                                (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
              3. insert() Method: We can insert one single item at a desired location by using the method
              insert() or insert multiple items by squeezing it into an empty slice of a list.
              Example: Program for insert() method.
              >>> list1=[10, 20]
              >>>list1
              [10,20]
              >>> list1.insert(1,30)
              >>> list1
              [10, 30, 20]
                                                                                                             Page No: 4 | 20
                                  MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                            (Autonomous)
                                                  (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
              2
              4 6 8
              10 12 14 16 18
       Ans    a=2                                                                                                        Correct or any
              for i in range(1,5):                                                                                       relevant Logic/
                for j in range(i):                                                                                          any other
                   print(a,end="\t")                                                                                         suitable
                   a+=2                                                                                                   Program 4 M
                print()
              import p1
              print(p1.add(10,20))
              print(p1.sub(20,10))
              Output:
              30
              10
                                                                                                        Page No: 6 | 20
                                  MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                         (Autonomous)
                                               (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
       Ans    Like, C, C++, and Java, a file in Python programming can be opened in various modes           Listing of
              depending upon the purpose. For that, the programmer needs to specify the mode               modes- 1 M
              whether read 'r', write 'w', or append 'a' mode. Apart from this, two other modes exist,    and explain ant
              which specify to open the file in text mode or binary mode.                                     2- 3 M
              1. The text mode returns strings while reading from the file. The default is reading in
              text mode.
              2. The binary mode returns bytes and this is the mode to be used when dealing with
              non-text files like image or executable files.
              The text and binary modes are used in conjunction with the r, w, and a modes. The list
              of all the modes used in Python are given in following table:
                   Sr. No. Mode Description
                                                                                                         Page No: 7 | 20
                                   MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                          (Autonomous)
                                                (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
                                         That is, the file is in the append mode. If the file does
                                         not exist, it creates a new file for writing.
b) Explain use of Pass and Else keyword with for loops in python. 4M
       Ans    Pass Statement: It is used when a statement is required syntactically but we do not                 Pass for 2 M
              want any command or code to execute. A pass statement in Python also refers to as a                and Else for 2
              will statement. The pass statement is a null operation; nothing happens when it executes.                M
              The pass is also useful in places where your code will eventually go, but has not been written
              yet.
              Syntax: pass
              Example: For pass statement.
              for i in range(1,11):
                   if i%2==0:          # check if the number is even
                    pass                # (No operation)
              else:
              print("Odd Numbers: ",i)
              Output:
              Odd Numbers: 1
              Odd Numbers: 3
              Odd Numbers: 5
              Odd Numbers: 9
              Odd Numbers: 7
                                                                                                               Page No: 8 | 20
                                 MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                          (Autonomous)
                                                (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
              Else Statement: The else block just after for/while is executed only when the loop is NOT
              terminated by a break statement. The else keyword in a for loop specifies a block of code to
              be executed when the loop is finished:
              Example:
              for i in range(1, 4):
                 print(i)
              else:                 # Executed because no break in for
                 print("Finally Exit”)
              Output:
              1
              2
              3
              Finally Exit
       c)     T = ('spam, Spam', SPAM!', 'SaPm')                                                                    4M
              print (T [2])
              print (T[-2])
              print (T[2:])
              print (List (T))
       Ans    Input                                                                                              Each Print
              T = ('spam’, ‘Spam', ‘SPAM!', 'SaPm')                                                              Statement/
                                                                                                               output for 1 M
               Python statement             Output
               print (T [2])                SPAM!
               print (T[-2])                SPAM!
               print (T[2:])                [‘SPAM!', 'SaPm']
               print (list (T))             ['spam', 'Spam', 'SPAM!', 'SaPm']
       Ans    Method Overloading: Method overloading is the ability to define the method with the same            Method
              name but with a different number of arguments and data types. With this ability one method        Overloading
              can perform different tasks, depending on the number of arguments or the types of the
              arguments given. Method overloading is a concept in which a method in a class performs                2M
              operations according to the parameters passed to it. Python does not support method              and Overriding
              overloading, that is, it is not possible to define more than one method with the same name in         2M
              a class in Python. This is because method arguments in python do not have a type. A method
              accepting one argument can be called with an integer value, a string or a double as shown in
              next example.
                       class Demo:
                       def method(self, a):
                           print(a)
                       obj= Demo( )
                       obj.method(50)
                       obj.method('Meenakshi')
                       obj.method(100.2)
              Output:
              50
              Meenakshi
              100.2
                                                                                                              Page No: 9 | 20
                               MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                        (Autonomous)
                                              (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
              It is clear that method overloading is not supported in python but that does not mean
              that we cannot call a method with different number of arguments. There are a couple
              of alternatives available in python that make it possible to call the same method but
              with different number of arguments.
       Ans    pop(): We can remove a particular item in a dictionary by using the method pop().            Any two
              This method removes as item with the provided key and returns the value.                   functions, 2m
              Example:                                                                                       each
              >>> squares
              {1: 1, 2: 4, 3: 9, 4: 16}
              >>> squares.pop(2)        # remove a particular item
              4
              >>> squares
              {1: 1, 3: 9, 4: 16}
              Popitem(): The method, popitem() can be used to remove and return an arbitrary item
              (key, value) form the dictionary.
              Example:
              >>> squares={1:1,2:4,3:9,4:16,5:25}
              >>> squares
              {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
                                                                                                      Page No: 10 | 20
                               MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                       (Autonomous)
                                             (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
              >>> print(squares.popitem())    # remove an arbitrary item
              (5, 25)
              >>> squares
              {1: 1, 2: 4, 3: 9, 4: 16}
              Clear(): All the items can be removed at once using the clear() method.
              Example:
              >>> squares
              {1: 1, 4: 16}
              >>> squares.clear() # removes all items
              >>> squares
              {}
              Del(): We can also use the del keyword to remove individual items or the entire
              dictionary itself.
              Example:
              >>> squares
              {1: 1, 3: 9, 4: 16}
              >>> del squares[3] # delete a particular item
              >>> squares
              {1: 1, 4: 16}
       Ans          NumPy is the fundamental package for scientific computing with Python.                Suitable
                     NumPy stands for "Numerical Python". It provides a high-performance                 explanation 4
                     multidimensional array object, and tools for working with these arrays.                  M
                    An array is a table of elements (usually numbers), all of the same type, indexed
                     by a tuple of positive integers and represented by a single variable. NumPy's
                     array class is called ndarray. It is also known by the alias array.
                    In NumPy arrays, the individual data items are called elements. All elements
                     of an array should be of the same type. Arrays can be made up of any number
                     of dimensions.
                    In NumPy, dimensions are called axes. Each dimension of an array has a length
                     which is the total number of elements in that direction.
                    The size of an array is the total number of elements contained in an array in all
                     the dimension. The size of NumPy arrays are fixed; once created it cannot be
                     changed again.
                    Numpy arrays are great alternatives to Python Lists. Some of the key
                     advantages of Numpy arrays are that they are fast, easy to work with, and give
                     users the opportunity to perform calculations across entire arrays.
                    Fig. shows the axes (or dimensions) and lengths of two example arrays; (a) is
                     a one-dimensional array and (b) is a two-dimensional array.
                                                                                                     Page No: 11 | 20
                                  MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                             (Autonomous)
                                                  (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
                     A one dimensional array has one axis indicated by Axis-0. That axis has five
                      elements in it, so we say it has length of five.
                     A two dimensional array is made up of rows and columns. All rows are
                      indicated by Axis-0 and all columns are indicated by Axis-1. If Axis-0 in two
                      dimensional array has three elements, so its length it three and Axis-1 has six
                      elements, so its length is six.
Execute Following command to install numpy in window, Linux and MAC OS:
       Ans    seek(): In python programming, within file handling concept seek() function is used to                 For seek()
              shift/change the position of file object to required position. By file object we mean a cursor.      method: 2 M
              And it’s cursor, who decides from where data has to be read or write in a file.                      and for Tell()
              Syntax:                                                                                               method 2 M
              f.seek(offset, fromwhere)
              where offset represents how many bytes to move fromwhere, represents the position from
              where the bytes are moving.
              Example:
              f = open("demofile.txt", "r")
              f.seek(4)         #sets Reference point to fourth index position from the beginning
              print(f.readline())
              tell(): tell() returns the current position of the file pointer from the beginning of the file.
              Syntax: file.tell()
              Example:
              f = open("demofile.txt", "r")
              # points at the start
              print(f.tell())
                                                                                                                Page No: 12 | 20
                                    MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                             (Autonomous)
                                                   (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
       d)     WAP to read contents of first.txt file and write same content in second.txt                                   4M
              file.
       Ans    with open('first.txt', 'r') as f:          # Open the first file for reading                              Correct logic
               contents = f.read()                       # Read the contents of the file                                program/any
                                                                                                                          suitable
              with open('second.txt', 'w') as f:         # Open the second file for writing                             program 4 M
                f.write(contents)                        # Write the contents of the first file to the second file
              2. Set Intersection: The intersection of two sets is the set of all the common elements of
              both the sets. You can use the ‘&’ operator to find the intersection of a Python set.
                       >>> first_set = {1, 2, 3, 4, 5, 6}
                       >>> second_set = {4, 5, 6, 7, 8, 9}
                       >>> first_set.intersection(second_set)
                       {4, 5, 6}
                        >>> first_set & second_set # using the ‘&’ operator
                       {4, 5, 6}
              3. Set Difference
              The difference between two sets is the set of all the elements in first set that are not present
              in the second set. You would use the ‘–‘ operator to achieve this in Python.
                       >>> first_set = {1, 2, 3, 4, 5, 6}
                       >>> second_set = {4, 5, 6, 7, 8, 9}
                        >>> first_set.difference(second_set)
                       {1, 2, 3}
                       >>> first_set - second_set         # using the ‘-‘ operator
                       {1, 2, 3}
                       >>> second_set - first_set
                       {8, 9, 7}
              4. Set Symmetric Difference: The symmetric difference between two sets is the set of all
              the elements that are either in the first set or the second set but not in both. You have the
              choice of using either the symmetric_difference() method or the ^ operator to do this in
              Python.
                      >>> first_set = {1, 2, 3, 4, 5, 6}
                       >>> second_set = {4, 5, 6, 7, 8, 9}
                      >>> first_set.symmetric_difference(second_set)
                      {1, 2, 3, 7, 8, 9}
                                                                                                                     Page No: 13 | 20
                                 MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                          (Autonomous)
                                                (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
                       >>> first_set ^ second_set      # using the `^` operator
                       {1, 2, 3, 7, 8, 9}
       b)     Explain building blocks of python.                                                                    6M
              2) Reserved Words
              The following list shows the Python keywords. These are reserved words and cannot use
              them as constant or variable or any other identifier names. All the Python keywords contain
              lowercase letters only.
              3) Indentation: Python provides no braces to indicate blocks of code for class and function
              definitions or flow control. Blocks of code are denoted by line indentation, which is
              compulsory.
              The number of spaces in the indentation is variable, but all statements within the block
              must be indented the same amount. For example –
              if True:
                 print "True"
              else:
                 print "False"
              Thus, in Python all the continuous lines indented with same number of spaces would form
              a block.
              4) Python Types: The basic types in Python are String (str), Integer (int), Float
              (float), and Boolean (bool). There are also built in data structures to know when you
              learn Python. These data structures are made up of the basic types, you can think of
              them like Legos, the data structures are made out of these basic types. The core data
                                                                                                             Page No: 14 | 20
                                MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                          (Autonomous)
                                                (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
              structures to learn in Python are List (list), Dictionary (dict), Tuple (tuple), and Set
              (set).
                      Strings
                      Strings in Python are assigned with single or double quotations. As in many
                      other programming languages, characters in strings may be accessed as if
                      accessing an array. In the example below we’ll assign a string to a variable,
                      access the first element, check for a
                      substring, and check the length of the string.
                      x = 'abcd'
                     Numbers: Integers and Floats in Python are both Number types. They can
                     interact with each other, they can be used in all four operations. In the
                     example code we’ll explore how these numbers can interact.
                     x = 2.5
                     y=2
                     Boolean: Boolean variables in Python are either True or False. They will also
                     return True for 1 and False for 0. The example shows how to assign either
                     True or False to a variable in Python
                     x = True
                     y = False
                     Lists: Lists in Python are represented with brackets. Like characters in a string,
                     the elements in a list can be accessed with brackets. Lists can also be
                     enumerate‘d on to return both the index and the element. We’ll go over
                     enumerate when we cover for loops in Python. The example code shows how
                     to declare lists, print elements in them, add to them, and remove from them.
                     x = [10, 25, 63, 104]
                     y = ['a', 'q', 'blah']
                     Tuples: Tuples is an immutable sequence in Python. Unlike lists, you can’t move
                     objects out of order in a Tuple. Tuples are declared with parenthesis and must
                     contain a comma (even if it is a tuple of 1). The example below shows how to add
                     tuples, get a tuple from a list, and return information about it.
                     x = (a, b)
                                                                                                         Page No: 15 | 20
                                MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                         (Autonomous)
                                               (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
                      Sets: Sets in Python are the non-duplicative data structure. That means they
                      can only store one of an element. Sets are declared with curly braces like
                      dictionaries, but do not contain ‘:’ in them. The example code shows how to
                      turn a list into a set, access set elements by index, add to a set, and remove
                      from a set.
                      # we can turn a list into a set
                      x = ['a', 'a', 'b', 'c', 'c']
                      x = set(x)
              5) Control structures: Control structures are used to determine the flow of execution
              of a Python program. Examples of control structures in Python include if-else
              statements, for and while loops, and try-except blocks.
              6) Functions: Functions are reusable blocks of code that perform specific tasks. In
              Python, functions are defined using the def keyword.
              7) Modules: Python modules are files that contain Python code and can be imported
              into other Python programs to reuse code and simplify development.
              8) Packages: Packages are collections of related Python modules that can be installed
              and imported together. Packages are commonly used in Python for organizing and
              distributing libraries and tools.
       c)     Write a program illustrating use of user defined package in python.                            6M
                def get_faculty_details(self):
                  return f"Name: {self.name}\nSubject: {self.subject}"
              # testing.py
              # importing the Student and Faculty classes from respective files
              from student import Student
              from faculty import Faculty
                                                                                                      Page No: 16 | 20
                                MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                         (Autonomous)
                                               (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
              Output :
              Name: ABC
              Gender: Male
              Year: 3
              Name: XYZ
              Subject: Programming
       a)     Write a program to create class student with Roll no. and Name and                         6M
              display its contents
              s1 = Student("ABC", 32)
              print(s1)
              Output:
              ABC 32
                                                                                                Page No: 17 | 20
                                MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                        (Autonomous)
                                              (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
       Ans    class Animal:        #super class                                                        Any other
                                                                                                        suitable
                # attribute and method of the parent class                                            program can
                name = ""                                                                               consider
                def eat(self):
                   print("I can eat")
                                                                                                Page No: 18 | 20
                                   MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                              (Autonomous)
                                                    (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
              add():
              Adds an element to the set. If an element is already exist in the set, then it does not
              add that element.
              Example:
                     s = {'g', 'e', 'k', 's'}
                     # adding f into set s
                     s.add('f')
                     print('Set after updating:', s)
              output:
              Set after updating: {'s', 'f', 'e', 'g', 'k'}
              discard():
              Removes the element from the set
              Example:
                     s = {'g', 'e', 'k', 's'}
                     print('Set before discard:', s)
                     s.discard('g')
                     print('\nSet after discard g:', s)
              Output:
              Set before discard: {'s', 'e', 'k', 'g'}
              Set after discard g: {'s', 'e', 'k'}
              remove():
              Removes the specified element from the set. If the specified element not found, raise
              an error.
              Example:
                      s = {'g', 'e', 'k', 's'}
                      print('Set before remove:', s)
                      s.remove('e')
                      print('\nSet after remove e:', s)
              Output:
              Set before remove: {'s', 'k', 'e', 'g'}
              Set after remove e: {'s', 'k', 'g'}
              clear():
              Removes all elements from the set
              Example:
                      s = {'g', 'e', 'k', 's'}
                      print('Set before clear:', s)
                      s.clear()
                      print('\nSet after clear:', s)
              Output:
              Set before clear: {'g', 'k', 's', 'e'}
              Set after clear: set()
                                                                                                        Page No: 19 | 20
                                   MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                             (Autonomous)
                                                   (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
              copy(): Returns a shallow copy of the set
              Example:
                     s = {'g', 'e', 'k', 's'}
                     p=s.copy()
                     print("original set:",s)
                     print("Copied set:",p)
              Output:
              original set: {'k', 's', 'g', 'e'}
              Copied set: {'k', 's', 'g', 'e'}
              Union():The set.union() method returns a new set with distinct elements from all the
              given sets.
              Example:
                     nums1 = {1, 2, 2, 3, 4, 5}
                     nums2 = {4, 5, 6, 7, 7, 8}
                     distinct_nums = nums1.union(nums2)
                     print("The union of two sets is: ", distinct_nums)
              Output:
              The union of two sets is: {1, 2, 3, 4, 5, 6, 7, 8}
              Difference():The set.difference() method returns the new set with the unique elements
              that are not in the other set passed as a parameter.
              Example:
                      nums1 = {1, 2, 2, 3, 4, 5}
                      nums2 = {4, 5, 6, 7, 8, 8}
                      nums3 = nums1.difference(nums2)
                      nums4 = nums2.difference(nums1)
                      print("nums1 - nums2: ", nums3)
                      print("nums2 - nums1: ", nums4)
              Output:
              nums1 - nums2: {1, 2, 3}
              nums2 - nums1: {8, 6, 7}
              Intersection():The set.intersection() method returns a new set with the elements that
              are common in the given sets.
              Example:
                     x = {"apple", "banana", "cherry"}
                     y = {"google", "microsoft", "apple"}
                     z = x.intersection(y)
                     print(z)
              Output:
              apple
                                                                                                      Page No: 20 | 20
                                 MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                         (Autonomous)
                                               (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
                                          SUMMER – 2023 EXAMINATION
                                  Model Answer – Only for the Use of RAC Assessors
       Ans        •   The membership operators in Python are used to find the existence of a particular         2 M for
                      element in the sequence, and used only with sequences like string, tuple, list,           proper
                      dictionary etc.                                                                         explanation
                  •   Membership operators are used to check an item or an element that is part of a
                      string, a list or a tuple. A membership operator reduces the effort of searching an
                      element in the list.
                                                                                                        Page No: 1 | 24
                               MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                       (Autonomous)
                                             (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
                 •   Python provides ‘in’ and ‘not in’ operators which are called membership
                     operators and used to test whether a value or variable is in a sequence.
      c)     Write down the output of the following Python code                                                 2M
             >>>indices-['zero','one','two',' three,' four, five']
                i)     >>>indices[:4]
                ii)    >>>indices[:-2]
      Ans      Output as follows:                                                                             1 M for
                    i) >>>indices[:4]                                                                          each
                        [zero, one, two, three]                                                               correct
                    ii) >>>indices[:-2]                                                                       output
                        [zero, one, two, three]
      Ans               •   int(x [,base]): Converts x to an integer. base specifies the base if x is a        Any 2
                            string.                                                                          Conversion
                            Example: x=int('1100',base=2)=12                                                  function
                        •   long(x [,base]): Converts x to a long integer. base specifies the base if x is      2M
                            a string.
                            Example: x=long(‘123’base=8)=83L
                        •   float(x): Converts x to a floating point number.
                            Example: x=float('123.45')=123.45
                        •   complex(real[,imag]) : Creates a complex number.
                            Example: x=complex(1,2) = (1+2j)
                        •   str(x): Converts object x to a string representation.
                            Example: x=str(10) = ‘10’
                        •   repr(x): Converts object x to an expression string
                            Example: x=repr(3) = 3
                        •   repr(x): Evaluates a string and returns an object.
                            Example: x=eval('1+2') = 3
                        •   tuple(s): Converts s to a tuple
                            Example:
                            x=tuple('123') = ('1', '2', '3')
                            x=tuple([123]) = (123,)
                        •   list(s): Converts s to a list
                            Example:
                            x=list('123') = ['1', '2', '3']
                            x=list(['12'] = ['12']
                        •   set(s): Converts s to a set
                            Example:
                            x=set('Python')
                               = {'y', 't', 'o', 'P', 'n', 'h'}
                        •   dict(d): Creates a dictionary. d must be a sequence of (key, value) tuples.
                                                                                                       Page No: 2 | 24
                                  MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                           (Autonomous)
                                                 (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
                               Example:
                               dict={'id':'11','name':'vijay'}
                               print(dict)
                               ={'id': '11', 'name': 'vijay'}
                           •   chr(x): Converts an integer to a character.
                               Example: x=chr(65) = ‘A’
                           •   unichr(x): Converts an integer to a Unicode character
                               Example: x=unichr(65) =u’A’
                           •   ord(x): Converts a single character to its integer value.
                               Example: x=ord('A')= 65
                           •   hex(x): Converts an integer to a hexadecimal string.
                               Example: x=hex(12) = 0xc
                           •   oct(x): Converts an integer to an octal string.
                               Example: x=oct(8) = 0o10
      Ans    The default constructor is simple constructor which does not accept any arguments. It’s            Explanation
             definition has only one argument which is a reference to the instance being constructed.              1 M,
                                                                                                                 Example
             Example 1: Display Hello message using default constructor.                                           1M
class Student:
def show(self,name):
print("Hello",name)
s1 = Student()
s1.show("Student1")
Output:
      Ans        •     We can make a new directory using the mkdir() method.                                    Explanation
                 •     This method takes in the path of the new directory. If the full path is not specified,      2M
                       the new directory is created in the current working directory.
                                                                                                          Page No: 3 | 24
                                    MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                          (Autonomous)
                                                (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
             Syntax: os.mkdir(“newdir”)
Example:
>>> import os
>>> os.mkdir("testdir")
      Ans          •    In some situations, multiline documentation is required for a program. If we have        2 M for
                        comments that extend multiple lines, one way of doing it is to use hash (#) in the       proper
                        beginning of each line. Another way of doing this is to use quotation marks, either    explanation
                        ''' or """.
                   •    Similarly, when it sees the triple quotation marks ''' it scans for the next ''' and
                        ignores any text in between the triple quotation marks.
             Example: For multiline comment.
Print is a statement'''
      Ans          •    The continue statement in Python returns the control to the beginning of the while     Explanation
                        loop.                                                                                      2M,
                   •    The continue statement rejects all the remaining statements in the current iteration    Example
                        of the loop and moves the control back to the top of the loop.                             2M
Syntax: continue
i=0
while i<10:
i=i+1
if i==5:
continue
print("i= ",i)
                                                                                                         Page No: 4 | 24
                               MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                       (Autonomous)
                                             (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
              Output:
             i=1
              i=2
              i=3
              i=4
              i=6
              i=7
              i=8
             i=9
              i=10
      b)     Explain creating Dictionary and accessing Dictionary Elements with                             4M
             example.
      Ans    Creating Dictionary                                                                          Creating
                                                                                                         Dictionary
                    The simplest method to create dictionary is to simply assign the pair of key:values explanation
                    to the dictionary using operator (=).                                               with example
                    • There are two ways for creation of dictionary in python.                              2 M,
                    1. We can create a dictionary by placing a comma-separated list of key:value         Accessing
                    pairs in curly braces{}. Each key is separated from its associated value by a Dictionary
                    colon:                                                                              Element with
                            Example: For creating a dictionary using { }.                               example 2 M
                            >>> dict1={} #Empty dictionary
                            >>> dict1
                            {}
                            >>> dict2={1:"Orange", 2:"Mango", 3:"Banana"} #Dictionary with
                            integer keys
                            >>> dict2
                            {1: 'Orange', 2: 'Mango', 3: 'Banana'}
                            >>> dict3={"name":"vijay", 1:[10,20]} #Dictionary with mixed keys
                            >>> dict3
                            {'name': 'vijay', 1: [10, 20]}
                                                                                                   Page No: 5 | 24
                              MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                       (Autonomous)
                                             (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
             Accessing Values in a Dictionary
                    • We can access the items of a dictionary by following ways:
                      1. Referring to its key name, inside square brackets([]).
                           Example: For accessing dictionary items [ ] using.
                           >>> dict1={'name':'vijay','age':40}
                           >>> dict1['name']
                           'vijay'
                           >>> dict1['adr']
                           Traceback (most recent call last):
                            File "<pyshell#79>", line 1, in <module>
                                dict1['adr']
                           KeyError: 'adr'
                            >>>
                           Here, if we refer to a key that is not in the dictionary, you’ll get an
                           exception. This error can be avoided by using get() method.
                        2. Using get() method returns the value for key if key is in the dictionary, else
                           None, so that this method never raises a KeyError.
                            Example: For accessing dictionary elements by get().
                            >>> dict1={'name':'vijay','age':40}
                            >>> dict1.get('name')
                            'vijay'
                        •   sum(list)
                            Calculates sum of all the elements of list.
                            Example:
                                   >>>list1
                                   [1, 2, 3, 4, 5]
                                   >>>sum(list1)
                                                                                                       Page No: 6 | 24
                               MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                         (Autonomous)
                                               (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
                                    15
                        •   min(list)
                            It returns the item that has the minimum value in a list.
                            Example:
                                     >>> list1
                                     [1, 2, 3, 4, 5]
                                     >>> min(list1)
                                     1
                        •   list(seq)
                            It converts a tuple into a list.
                            Example:
                                    >>> list1
                                    [1, 2, 3, 4, 5]
                                    >>> list(list1)
                                    [1, 2, 3, 4, 5]
                        •   abs(n)
                            It returns the absolute value of a number.
                            Example:
                                     >>> abs(10)
                                     10
                        •   all()
                            The all() function returns True if all items in an iterable are true, otherwise it
                            returns False.
                            Example:
                                     >>> x=[True, True, True]
                                     >>> all(x)
                                     True
                        •   any()
                            The any() function returns True if any item in an iterable are true, otherwise it
                            returns False. If the iterable object is empty, the any() function will return False.
                            Example:
                                    >>> x=[True, False, True]
                                    >>> any(x)
                                    True
                        •   bin()
                            The bin() function returns the binary version of a specified integer. The result
                            will always start >>> bin(10)
                            Example:
                                                                                                                 Page No: 7 | 24
                               MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                          (Autonomous)
                                                (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
                                    '0b1010'
                                    with the prefix 0b.
                        •   bool()
                            The bool() function returns the boolean value of a specified object.
                            Example:
                                   >>> bool(1)
                                   True
                        •   exp()
                            The method exp() returns returns exponential of x: ex.
                            x: This is a numeric expression.
                            Example:
                            >>> math.exp(1)
                            2.718281828459045
                            >>>
                    Output:
                    Enter Number: 5
                    The factorial of 5 is 120
      a)     Write a python program to input any two tuples and interchange the tuple                       4M
             variables.
                                                                                                   Page No: 8 | 24
                                  MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                          (Autonomous)
                                                (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
                new_tup1 = tup2                                                                        logic 4 M
                new_tup2 = tup1
                return new_tup1, new_tup2
             # Input two tuples
             tuple1 = tuple(input("Enter the elements of the first tuple (separated by commas):
             ").split(","))
             tuple2 = tuple(input("Enter the elements of the second tuple (separated by commas):
             ").split(","))
                                                                                                 Page No: 9 | 24
                               MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                        (Autonomous)
                                              (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
                     result = a & b
                     print(result) # Output: 2 (binary: 0010)
                 2) Bitwise OR (|): Performs a bitwise OR operation on the corresponding bits of two
                    numbers. Each bit of the output is 0 if the corresponding bits of both operands are
                    0; otherwise, it is 1.
                    Example:
                    a = 10 # binary: 1010
                    b = 6 # binary: 0110
                    result = a | b
                    print(result) # Output: 14 (binary: 1110)
                 3) Bitwise XOR (^): Performs a bitwise XOR (exclusive OR) operation on the
                    corresponding bits of two numbers. Each bit of the output is 1 if the
                    corresponding bits of the operands are different; otherwise, it is 0.
                    Example:
                    a = 10 # binary: 1010
                    b = 6 # binary: 0110
                    result = a ^ b
                    print(result) # Output: 12 (binary: 1100)
                 4) Bitwise NOT (~): Performs a bitwise NOT operation on a single operand, which
                    inverts all the bits. It returns the complement of the given number.
                    Example:
                    a = 10 # binary: 1010
                    result = ~a
                    print(result) # Output: -11 (binary: -1011)
                 5) Bitwise left shift (<<): Shifts the bits of the left operand to the left by a specified
                    number of positions. Zeros are shifted in from the right side.
                    Example:
                     a = 10 # binary: 1010
                    result = a << 2
                    print(result) # Output: 40 (binary: 101000)
                 6) Bitwise right shift (>>): Shifts the bits of the left operand to the right by a
                                                                                                       Page No: 10 | 24
                                MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                         (Autonomous)
                                               (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
                     specified number of positions. Zeros are shifted in from the left side.
                     Example:
                     a = 10 # binary: 1010
                     result = a >> 2
      Ans    readline(): This method reads a single line from the file and returns it as a string. It moves       readline()
             the file pointer to the next line after reading. If called again, it will read the subsequent       explanation
             line.                                                                                               for 1 M and
                                                                                                                 Example for
             # Open the file in read mode                                                                            1M
             file = open("example.txt", "r")                                                                         and
                                                                                                                  readlines()
             # Read the first line
                                                                                                                 explanation
             line1 = file.readline()                                                                             for 1 M and
                                                                                                                 Example for
             print(line1)                                                                                            1M
                                                                                                         Page No: 11 | 24
                                  MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                         (Autonomous)
                                             (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
             lines = file.readlines()
      Ans    In Python, the self parameter is a convention used in object-oriented programming (OOP) Explanation
             to refer to the instance of a class within the class itself. It allows you to access the 2 M and
             attributes and methods of the class from within its own methods. The name self is not a
                                                                                                      example 2
             keyword in Python, but it is widely adopted and recommended as a convention.
                                                                                                      M
             Example:
             class Car:
                def __init__(self, make, model, year):
                  self.make = make
                  self.model = model
                  self.year = year
                def get_info(self):
                  info = f"Make: {self.make}, Model: {self.model}, Year: {self.year}"
                  return info
                def start_engine(self):
                  print("Engine started!")
                                                                                                Page No: 12 | 24
                               MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                        (Autonomous)
                                              (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
             # Access the attributes using the self parameter
             print(my_car.make) # Output: Toyota
             print(my_car.model) # Output: Corolla
             print(my_car.year) # Output: 2022
             # Call the method that does not require any additional parameters
             my_car.start_engine() # Output: Engine started!
      Ans                                                                                                 Any 4
                                                                                                       correct point
               List                                            Tuple                                       4M
               Lists are mutable                               Tuples are immutable
               The list is better for performing               A Tuple data type is appropriate for
               operations, such as insertion and deletion.     accessing the elements
               Lists have several built-in methods             Tuple does not have many built-in
                                                               methods.
               Unexpected changes and errors are more          In a tuple, it is hard to take place.
               likely to occur
                                                                                                     Page No: 14 | 24
                                MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                        (Autonomous)
                                              (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
                if b == 0:
                    raise MyException("Division by zero is not allowed!")
                return a / b
             # Main program
             try:
                num1 = int(input("Enter the numerator: "))
                num2 = int(input("Enter the denominator: "))
             except MyException as e:
                print("Exception:", e.message)
             Note: Any correct program of user defined exception can be considered.
             Output:
             Enter the numerator: 10
             Enter the denominator: 0
             Exception: Division by zero is not allowed!
             Enter the numerator: 10
             Enter the denominator: 5
             Result: 2.0
      Ans    Modules are primarily the (.py) files which contain Python programming code defining      Explanation
             functions, class, variables, etc. with a suffix .py appended in its file name.            2 M and use
                                                                                                          2M
             • A file containing .py python code is called a module.
             • If we want to write a longer program, we can use file where we can do editing,
             correction. This is known as creating a script. As the program gets longer, we may want
             to split it into several files for easier maintenance.
             • We may also want to use a function that you’ve written in several programs without
                                                                                                Page No: 15 | 24
                                    MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                           (Autonomous)
                                                 (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
             copying its definition into each program.
             • In Python we can put definitions in a file and use them in a script or in an interactive
             instance of the interpreter. Such a file is called a module.
             Use of module in python :
             Code organization: Modules allow you to organize related code into separate files,
             making it easier to navigate and maintain large projects.
             Code reusability: Modules can be imported and reused in multiple programs, enabling
             code reuse and reducing duplication.
             Encapsulation: Modules provide a way to encapsulate code and hide the implementation
             details, allowing users to focus on the functionality provided by the module.
             Name spacing: Modules help avoid naming conflicts by providing a separate namespace
             for the names defined within the module.
                                                                                                   Page No: 16 | 24
                                 MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                          (Autonomous)
                                                (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
                print("The string is not a palindrome.")
             output:
             Enter a string: madam
             The string is a palindrome.
             Enter a string: abc
             The string is not a palindrome.
      c)     Write a Python Program to accept values from user in a list and find the                    6M
             largest number and smallest number in a list.
for n in range(num):
list.append(numbers)
             print("Maximum element in the list is :", max(list), "\nMinimum element in the list is :",
             min(list))
output:
Enter number 10
Enter number 20
Enter number 30
Enter number 40
Enter number 50
      Ans        1) union():Return a new set containing the union of two or more sets                       1 function
                                                                                                          for 1 M each
                    Example:
                    set1 = {1, 2, 3}
                    set2 = {3, 4, 5}
                    union_set = set1.union(set2)
                    print(union_set) # Output: {1, 2, 3, 4, 5}
                 2) Intersection:
                    Intersection operation performed on two sets returns all the elements which are
                    common or in both the sets.
                    Example:
                                                                                                    Page No: 18 | 24
                                MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                          (Autonomous)
                                                (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
                    set1 = {1, 2, 3}
                    set2 = {2, 3, 4}
                    intersection_set = set1.intersection(set2)
                    print(intersection_set) # Output: {2, 3}
                 3) Difference:
                    Difference operation on two sets set1 and set2 returns all the elements which are
                    present on set1 but not in set2.
                    Example:
                    set1 = {1, 2, 3, 4, 5}
                    set2 = {3, 4}
                    difference_set = set1.difference(set2)
                    print(difference_set) # Output: {1, 2, 5}
                 4) add(element):
                    This function adds an element to a set.
                    Example:
                    fruits = {"apple", "banana", "cherry"}
                    fruits.add("orange")
                    print(fruits) # Output: {'apple', 'banana', 'cherry', 'orange'}
                 5) remove(element):
                    This function removes an element from a set.
                    Example:
                    numbers = {1, 2, 3, 4, 5}
                    numbers.remove(3)
                    print(numbers) # Output: {1, 2, 4, 5}
                 6) clear():
                    This function removes all elements from a set, making it an empty set.
                    Example:
                    numbers = {1, 2, 3, 4, 5}
                                                                                                 Page No: 19 | 24
                               MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                       (Autonomous)
                                             (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
                    numbers.clear()
                    print(numbers) # Output: set()
                 7) isdisjoint():
                    The isdisjoint() method in Python's set class is used to check whether two sets
                    have any common elements. It returns True if the sets are disjoint (i.e., they have
                    no common elements), and False otherwise.
                    Example:
                    # Example 1
                    set1 = {1, 2, 3, 4}
                    set2 = {5, 6, 7}
                    set3 = {3, 4, 5}
                    # Example 2
                    fruits = {"apple", "banana", "orange"}
                    colors = {"red", "green", "blue"}
                    # Example 3
                    setA = {1, 2, 3}
                    setB = {4, 5, 6}
                                                                                                    Page No: 20 | 24
                                MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                          (Autonomous)
                                                (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
                     set1.update(set2)
      b)     Design a class student with data members : name, roll no., department,                       6M
             mobile no. Create suitable methods for reading and printing student
             information.
                def read_student_info(self):
                  self.name = input("Enter student name: ")
                  self.roll_no = input("Enter roll number: ")
                  self.department = input("Enter department: ")
                  self.mobile_no = input("Enter mobile number: ")
                def print_student_info(self):
                  print("Student Information:")
                  print("Name:", self.name)
                  print("Roll Number:", self.roll_no)
                  print("Department:", self.department)
                  print("Mobile Number:", self.mobile_no)
                                                                                                Page No: 21 | 24
                               MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                         (Autonomous)
                                              (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
             # Read and set student information
             student.read_student_info()
      Ans    In inheritance objects of one class procure the properties of objects of another class. Explanation
             Inheritance provide code usability, which means that some of the new features can be      3 M and
             added to the code while using the existing code. The mechanism of designing or            Correct
             constructing classes from other classes is called inheritance.                          example 3 M
             • The new class is called derived class or child class and the class from which this
             derived class has been inherited is the base class or parent class.
             • In inheritance, the child class acquires the properties and can access all the data
             members and functions defined in the parent class. A child class can also provide its
             specific implementation to the functions of the parent class.
             Syntax:
              class A:
              # properties of class A
              class B(A):
              # class B inheriting property of class A
              # more properties of class B
                                                                                                Page No: 22 | 24
                               MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                       (Autonomous)
                                             (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
             Example:
             # Base class
             class Animal:
                def __init__(self, name):
                  self.name = name
                def speak(self):
                  print("Animal speaks")
                                                                                                Page No: 23 | 24
                              MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                      (Autonomous)
                                            (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
                                                                                                Page No: 24 | 24
                                 MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                         (Autonomous)
                                               (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
                                      WINTER – 2022 EXAMINATION
Subject Name: Programming with Python          Model Answer                           Subject Code:        22616
Important Instructions to examiners:                                                                   XXXXX
   1) The answers should be examined by key words and not as word-to-word as given in the model answer scheme.
   2) The model answer and the answer written by candidate may vary but the examiner may try to assess the
       understanding level of the candidate.
   3) The language errors such as grammatical, spelling errors should not be given more Importance (Not applicable for
       subject English and Communication Skills.
   4) While assessing figures, examiner may give credit for principal components indicated in the figure. The figures
       drawn by candidate and model answer may vary. The examiner may give credit for any equivalent figure drawn.
   5) Credits may be given step wise for numerical problems. In some cases, the assumed constant values may vary and
       there may be some difference in the candidate’s answers and model answer.
   6) In case of some questions credit may be given by judgement on part of examiner of relevant answer based on
       candidate’s understanding.
   7) For programming language papers, credit may be given to any other program based on equivalent concept.
   8) As per the policy decision of Maharashtra State Government, teaching in English/Marathi and Bilingual (English +
       Marathi) medium is introduced at first year of AICTE diploma Programme from academic year 2021-2022. Hence if
       the students in first year (first and second semesters) write answers in Marathi or bilingual language (English
       +Marathi), the Examiner shall consider the same and assess the answer based on matching of concepts with
       model answer.
                                       Operator                         Meaning
                                         ==                             Equal to
                                                                                                        Page No: 1 | 21
                               MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                         (Autonomous)
                                               (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
                                      !=                           Not Equal to
                                       <                             Less than
                                       >                           Greater than
                                     <=                       Less than and Equal to
                                     >=                      Greater than and Equal to
      c)     Describe Tuples in Python.                                                                      2M
      Ans    The lambda function, which is also called anonymous function. A lambda function can          2M for use
             take any number of arguments, but can only have one expression.
             Syntax: lambda arguments : expression
             Example: x= lambda a,b : a*b
                       Print(x(10,5)
             Output: 50
      e)     Write syntax of defining class in Python.                                                       2M
      Ans    Indentation refers to the spaces at the beginning of a code line. Python indentation            2M
             refers to adding white space before a statement to a particular block of code. In another
             word, all the statements with the same space to the right, belong to the same code
             block.
                                                                                                     Page No: 2 | 21
                              MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                      (Autonomous)
                                            (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
      Ans    Bitwise operators acts on bits and performs bit by bit operation. Assume a=10 (1010)      4M (for any
             and b=4 (0100)                                                                          four, 1M each)
                          Operator      Meaning           Description        Example
                              &       Binary AND This           operation a &b =
                                                      performs       AND 1010 &
                                                      operation             0100 =
                                                      between               0000 =0
                                                      operands.
                                                      Operator copies a
                                                      bit, to the result,
                                                      if it exists in both
                                                      operands
                               |      Binary OR       This      operation a|b = 1010 |
                                                      performs         OR 0100 =
                                                      operation             1110 = 14
                                                      between
                                                      operands.          It
                                                      copies a bit, if it
                                                      exists in either
                                                      operand.
                               ^      Binary XOR This           operation a^b=1010 ^
                                                      performs       XOR 0100 =
                                                      operations            1110 =14
                                                      between
                                                      operands.          It
                                                      copies the bit, if it
                                                      is set in one
                                                      operand but not
                                                      both.
                               ~      Binary Ones It         is      unary ~a= ~ 1010
                                      Complement operator and has = 0101
                                                      the     effect    of
                                                      'flipping' bits i.e.
                                                      opposite the bits
                                                      of operand.
                              <<      Binary Left The left operand's a<<2 =
                                                                                                 Page No: 3 | 21
                              MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                        (Autonomous)
                                              (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
                                      Shift        value is moved                  1010 << 2
                                                   left    by     the              =101000 =
                                                   number of bits                  40
                                                   specified by the
                                                   right operand.
                            >>      Binary Right The left operand's                a>>2 =
                                    Shift          value is moved                  1010 >> 2
                                                   right    by    the              =0010 = 2
                                                   number of bits
                                                   specified by the
                                                   right operand.
      b)     Write any four methods of dictionary.                                                       4M
                                                                                                 Page No: 4 | 21
                              MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                      (Autonomous)
                                            (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
      Ans         Global variables: global variables can be accessed throughout the program         4M (2M for
                   body by all functions.                                                            explanation
                 Local variables: local variables can be accessed only inside the function in       and 2M for
                   which they are declared                                                            example)
             Concept Diagram:
             A global variable (x) can be reached and modified anywhere in the code, local
             variable (z) exists only in block 3.
             Example:
             g=10                 #global variable g
             def test():
               l=20                 #local variable l
               print("local variable=",l)
                                     # accessing global variable
               print("Global variable=",g)
                                                                                                 Page No: 5 | 21
                                 MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                         (Autonomous)
                                               (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
             test()
             print("global variable=",g)
             output:
             local variable= 20
             Global variable= 10
             global variable= 10
             output:
             i is 20
             (Similar type of program can consider)
                                                                                                     Page No: 6 | 21
                              MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                      (Autonomous)
                                            (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
             2) Deleting Values in List
             The pop() method in Python is used to remove a particular item/element from the given
             index in the list. The pop() method removes and returns the last item if index is not
             provided. This helps us implement lists as stacks (first in, last out data structure).
             >>> list= [10, 20, 30, 40]
             >>> list
             [10, 20, 30, 40]
             30
             >>> list
             [10, 20, 40]
             >>> list.pop()
             40
             >>> list
              [10, 30]
             We can delete one or more items from a list using the keyword del. It can even delete
             the list entirely. But it does not store the value for further use
             >>> list= [10, 20, 30, 40]
             >>> list
             [10, 20, 30, 40]
             >>> del (list[1]) # del() with index
             >>> list
             [10, 30, 40]
             >>> del list[2] # del with index
             >>> list
             [10, 30]
             The remove() method in Python issued to remove a particular element from the list. We
             use the remove() method if we know the item that we want to remove or delete from the
             list (but not the index).
             >>> list=[10,"one",20,"two"]
             >>> list.remove(20)
             >>> list
             [10, 'one', 'two']
             >>> list.remove("one")
             >>> list
             [10, 'two']
             >>>
             3. Updating Lists:
             • List are mutable, meaning their elements can be changed or updated unlike string or
             tuple.
             • Mutability is the ability for certain types of data to be changed without entirely
             recreating it. Using
             mutable data types can allow programs to operate quickly and efficiently.
                                                                                                  Page No: 7 | 21
                                MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                         (Autonomous)
                                               (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
             • Multiple values can be added into list. We can use assignment operator (=) to change
             an item or a
             range of items.
             • We can update items of the list by simply assigning the value at the particular index
             position. We
             can also remove the items from the list using remove() or pop() or del statement.
             4 Indexing
             There are various ways in which we can access the elements of a list.
             List Index: We can use the index operator [] to access an item in a list. Index starts
             from 0. So, a list having 5 elements will have index from 0 to 4.
             Example:
             >>> list1=[10,20,30,40,50]
             >>> list1[0]
             10
             >>> list1[4]
             50
             >>> list1[1:3]
             [20, 30]
             5. List Slicing
             The slicing operator returns a subset of a list called slice by specifying two indices, i.e.
             start and end.
             Syntax:
             List_variable[start_index:end_index]
             Example:
             >>> l1=([10,20,30,40,50])
             >>> l1[1:4]
             [20, 30, 40]
                                                                                                            Page No: 8 | 21
                               MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                       (Autonomous)
                                             (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
      Ans    • Method overloading is the ability to define the method with the same name but with a Explanation
             different number of arguments and data types.                                            1 M and
             • With this ability one method can perform different tasks, depending on the number of Example 3 M
             arguments or the types of the arguments given.
             • Method overloading is a concept in which a method in a class performs operations
             according to the parameters passed to it.
             Example: With a method to perform different operations using method overloading.
             class operation:
             def add(self,a,b):
              return a+b
             op1=operation()
             # To add two integer numbers
             print("Addition of integer numbers=",op1.add(10,20))
             # To add two floting point numbers
             print("Addition of integer numbers=",op1.add(11.12,12.13))
             # To add two strings
             print("Addition of integer numbers=",op1.add("Hello","Python"))
             Output:
             Addition of integer numbers= 30
             Addition of integer numbers= 23.25
              Addition of integer numbers= HelloPython
             Python does not support method overloading, that is, it is not possible to define more
             than one method with the same name in a class in Python.
             • This is because method arguments in python do not have a type. A method accepting
             one argument can be called with an integer value, a string or a double as shown in next
             example.
                                                                                                    Page No: 9 | 21
                               MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                      (Autonomous)
                                            (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
             class Demo:
             def method(self, a):
             print(a)
             obj= Demo()
             obj.method(50)
             obj.method('Meenakshi')
              obj.method(100.2)
             Output:
             50
             Meenakshi
             100.2
      d)     Explain how try-catch block is used for exception handling in python.                       4M
      Ans    • In Python, exceptions can be handled using a try statement. A try block Proper
             consisting of one or more statements is used by programmers to partition code explanation
             that might be affected by an exception.
             • A critical operation which can raise exception is placed inside the try clause and the 4 M
             code that handles exception is written in except clause.
             • The associated except blocks are used to handle any resulting exceptions thrown in
             the try block. That is we want the try block to succeed and if it does not succeed, we
             want to control to pass to the catch block.
             • If any statement within the try block throws an exception, control immediately shifts
             to the catch block. If no exception is thrown in the try block, the catch block is skipped.
             • There can be one or more except blocks. Multiple except blocks with different
             exception names can be chained together.
             • The except blocks are evaluated from top to bottom in the code, but only one except
             block is executed for each exception that is thrown.
             • The first except block that specifies the exact exception name of the thrown exception
             is executed. If no except block specifies a matching exception name then an except
             block that does not have an exception name is selected, if one is present in the code.
             • For handling exception in Python, the exception handler block needs to be written
             which consists of set of statements that need to be executed according to raised
             exception. There are three blocks that are used in the exception handling process,
             namely, try, except and finally.
             1. try Block: A set of statements that may cause error during runtime are to be written
             in the try
             block.
             2. except Block: It is written to display the execution details to the user when certain
             exception occurs in the program. The except block executed only when a certain type as
             exception occurs in the execution of statements written in the try block.
             Syntax:
             try:
              D the operations here
              ......................
                                                                                                Page No: 10 | 21
                                MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                        (Autonomous)
                                              (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
             except Exception1:
              If there is Exception1, then execute this block.
             except Exception2:
              If there is Exception2, then execute this block.
              ......................
             else:
              If there is no exception then execute this block.
                List is a collection of index values pairs      Dictionary is a hashed structure of       1 M for 1 point
                as that of array in c++.                        key and value pairs.
                The indices of list are integers starting       The keys of dictionary can be of any
                from 0.                                         data type.
                The elements are accessed via indices.          The elements are accessed via key-
                                                                values.
                                                                                                       Page No: 11 | 21
                                 MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                           (Autonomous)
                                                 (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
      Ans    Python Command line arguments are input parameters passed to the script when            1 M for
             executing them. Almost all programming language provide support for command line        definition and
             arguments. Then we also have command line options to set some specific options for      3 M for
             the program.                                                                            program
             There are many options to read python command line arguments. The three most
             common ones are:
             Python sys.argv
             Python getopt module
             Python argparse module
             Program:
             import sys
             x=int(sys.argv[1])
             y=int(sys.argv[2])
             sum=x+y
             print("The addition is :",sum)
             Output:
             C:\Python34\python sum.py 6 4
             The addition is : 10
      c)     Write python code to count frequency of each characters in a given file.                     4M
             1. Integers (int Data Type): An integer is a whole number that can be positive (+) or
             negative (−). Integers can be of any length, it is only limited by the memory available.
             Example: For number data types are integers.
             >>>a=10
             >>>b -10
             To determine the type of a variable type() function is used.
             >>>type(a)
             >>> <class 'int'>
             2. Boolean (Bool Data Type: The simplest build-in type in Python is the bool type, it
             represents the truth-values False and True. Internally the true value is represented as
             1 and false is 0.
             For example
             >>>a = 18 > 5
             >>>print(a)
             True
             b=2>3
             print(b)
             False
             4. Complex Numbers (Complex Data Type): Complex numbers are written in the form,
             x + yj, where x is the real part and y is the imaginary part.
             Example:
             Complex number.
             >>>x = 3+4j
              >>>print(x.real)
              3.0
              >>>print(x.imag)
             4.0
                                                                                                   Page No: 13 | 21
                               MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                       (Autonomous)
                                             (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
             5. String Data Type: String is a collection of group of characters. Strings are identified
             as a contiguous set of characters enclosed in single quotes (' ') or double quotes (" ").
             Any letter, a number or a symbol could be a part of the string. Strings are
             unchangeable (immutable). Once a string is created, it cannot be modified.
             Example: For string data type.
             >>> s1="Hello" #string in double quotes
             >>> s2='Hi'      #string in single quotes
             >>> s3="Don't open the door" #single quote string in double quotes
             >>> s4='I said "yipee"' #double quote string in single quotes
             >>>type(s1)
             <class 'str'>
             6. List Data Type: List is an ordered sequence of items. It is one of the most used
             datatype in Python and is very flexible.
             List can contain heterogeneous values such as integers, floats, strings, tuples, lists and
             dictionaries but they are commonly used to store collections of homogeneous objects.
             The list datatype in Python programming is just like an array that can store a group of
             elements and we can refer to these elements using a single name. Declaring a list is
             pretty straight forward. Items separated by commas ( , ) are enclosed within brackets [
             ].
             Example: For list.
             >>> first=[10, 20, 30]         # homogenous values in list
             >>> second=["One","Two","Three"] # homogenous values in list
             >>> first
             [10, 20, 30]
             >>> second
             ['One', 'Two', 'Three']
             >>> first + second      # prints the concatenated lists
              [10, 20, 30, 'One', 'Two', 'Three']
             7. Tuple Data Type: Tuple is an ordered sequence of items same as list. The only
             difference is that tuples are immutable.
             Tuples once created cannot be modified. It is defined within parentheses ( ) where
             items are separated by commas ( , ).
             A tuple data type in python programming is similar to a list data type, which also
             contains heterogeneous items/elements.
             Example: For tuple.
             >>> a=(10,'abc',1+3j)
             >>> a
             (10, 'abc', (1+3j))
             >>> a[0]
             10
             >>> a[0]=20
             Traceback (most recent call last):
              File "<pyshell#12>", line 1, in <module>
                                                                                                     Page No: 14 | 21
                               MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                        (Autonomous)
                                              (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
             8. Dictionary: Dictionary is an unordered collection of key-value pairs. It is the same as
             the hash table type. The order of elements in a dictionary is undefined, but we can
             iterate over the following:
             o The key
             o The value
             o The items (key-value pairs) in a dictionary.
             When we have the large amount of data, the dictionary data type is used. Items in
             dictionaries are enclosed in curly braces { } and separated by the comma (,). A colon (:)
             is used to separate key from value. Values can be assigned and accessed using square
             braces ([]).
             Example: For dictionary data type.
             >>> dic1={1:"First","Second":2}
             >>> dic1
             {1: 'First', 'Second': 2}
             >>> type(dic1)
             <class 'dict'>
             >>> dic1[3]="Third"
             >>> dic1
             {1: 'First', 'Second': 2, 3: 'Third'}
             >>> dic1.keys()
             dict_keys([1, 'Second', 3])
             >>> dic1.values()
             dict_values(['First', 2, 'Third'])
             >>>
      Ans    A module allows you to logically organize your Python code. Grouping related code              2 M for
             into a module makes the code easier to understand and use. A module is a Python                module
             object with arbitrarily named attributes that you can bind and reference.                    explanation
             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.
             Example
             The Python code for a module named aname normally resides in a file named
             aname.py. Here's an example of a simple module, support.py                                     2 M for
                                                                                                            creating
             def print_func( par ):                                                                         module
               print "Hello : ", par
               return
             To create a module just save the code you want in a file with the file extension .py:
             Example
             Save this code in a file named mymodule.py
             def greeting(name):
              print("Hello, " + name)
             Now we can use the module we just created, by using the import statement:                      2 M for
                                                                                                        accessing/using
                                                                                                     Page No: 15 | 21
                                MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                            (Autonomous)
                                                  (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
             Example                                                                                    module
             Import the module named mymodule, and call the greeting function:
             import mymodule
             mymodule.greeting("ABC")
      c)     Write python program to perform following operations on Set (Instead of                        6M
             Tuple)
                 i)      Create set
                 ii)     Access set Element
                 iii)    Update set
                 iv)     Delete set
             output:                                                                                 2M-delete
             {50, 20, 40, 10, 30}                                                                    Tuple)
             {50, 20, 40, 10, 60, 30}
             {'B', 50, 20, 'A', 40, 10, 60, 30}
             {'B', 50, 20, 'A', 40, 10, 60}
             {'B', 50, 20, 40, 10, 60}
             {50, 20, 40, 10, 60}
             output:
             (10, 20, 30, 40, 50)
             20
             (10, 20, 30)
             Traceback (most recent call last):
              File "C:\Users\Vijay Patil\AppData\Local\Programs\Python\Python310\temp.py", line
             9, in <module>
                print (tuple1)
             NameError: name 'tuple1' is not defined. Did you mean: 'tuple'?
      Ans    The data types in Python are divided in two categories:                                 3m for mutable
             Immutable data types – Values cannot be changed. Immutable data types in Python are      data structure
                    1. Numbers                                                                         and 3m for
                    2. String                                                                        immutable data
                    3. Tuple                                                                            structure
             Mutable data types – Values can be changed. Mutable data types in Python are:
                    1. List
                    2. Dictionaries
                    3. Sets
                    1. Numbers
             Python supports integers, floats and complex numbers.
             An integer is a number without decimal point for example 5, 6, 10 etc.
             A float is a number with decimal point for example 6.7, 6.0, 10.99 etc.
             A complex number has a real and imaginary part for example 7+8j, 8+11j etc.
                                                                                                Page No: 17 | 21
                                 MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                        (Autonomous)
                                              (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
             Example:
             # int
             num1 = 10
             num2 = 100
             # float
             a = 10.5
             b = 8.9
             # complex numbers
             x = 3 + 4j
             y = 9 + 8j
                     2. String
             A string is usually a bit of text (sequence of characters). In Python we use ” (double
             quotes) or ‘ (single quotes) to represent a string.
             There are several ways to create strings in Python:
             1. We can use ‘ (single quotes), see the string str in the following code.
             2. We can use ” (double quotes), see the string str2 in the source code below.
             3. Triple double quotes “”” and triple single quotes ”’ are used for creating multi-line
             strings in Python.
             Example:
             str = 'beginnersbook'
             str2 = "Chaitanya"
             # multi-line string
             str3 = """Welcome to
               Pythonsbook"""
             3. Tuple
             In Python, a tuple is similar to List except that the objects in tuple are immutable which
             means we cannot change the elements of a tuple once assigned. On the other hand, we
             can change the elements of a list.
             To create a tuple in Python, place all the elements in a () parenthesis, separated by
             commas. A tuple can have heterogeneous data items, a tuple can have string and list as
             data items as well.
             Example
             # tuple of strings
             my_data = ("hi", "hello", "bye")
                                                                                                     Page No: 18 | 21
                                MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                         (Autonomous)
                                               (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
             4. List
             A list is a data type that allows you to store various types data in it. List is a compound
             data type which means you can have different-2 data types under a list, for example we
             can have integer, float and string items in a same list.
             To create a list all you have to do is to place the items inside a square bracket []
             separated by comma ,.`
             Example:
             # list of floats
             num_list = [11.22, 9.9, 78.34, 12.0]
             # an empty list
             nodata_list = []
             5. Dictionaries
             Dictionary is a mutable data type in Python. A python dictionary is a collection of key
             and value pairs separated by a colon (:), enclosed in curly braces {}.
             Left side of the colon(:) is the key and right side of the : is the value.
             mydict = {'StuName': 'Ajeet', 'StuAge': 30, 'StuCity': 'Agra'}
             6. Sets
             Set is an unordered and unindexed collection of items in Python. Unordered means
             when we display the elements of a set, it will come out in a random order. Unindexed
             means, we cannot access the elements of a set using the indexes like we can do in list
             and tuples.
             The elements of a set are defined inside curly brackets and are separated by commas.
             For example –
             myset = {1, 2, 3, 4, "hello"}
b) Design a class student with data members; Name, roll number address. 6M
                                                                                                      Page No: 19 | 21
                               MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                        (Autonomous)
                                              (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
             Create suitable method for reading and printing students details.
      Ans    class Student:                                                                          2 M for class
                                                                                                       definition
               def getStudentDetails(self):
                  self.rollno=input("Enter Roll Number : ")
                  self.name = input("Enter Name : ")
             Output:                                                                                 2 M to create
                                                                                                        objects
             Enter Roll Number : 001
             Enter Name : ABC
             Enter Address : New York
             Student Details :
             001 ABC New York
             (Any suitable program can consider)
      c)     Create a parent class named Animals and a child class Herbivorous which will                6M
             extend the class Animal. In the child class Herbivorous over side the method feed (
             ). Create a object
      Ans    # parent class                                                                          2 M to create
             class Animal:                                                                            parent class
               # properties
                     multicellular = True
                     # Eukaryotic means Cells with Nucleus
                     eukaryotic = True
              # function feed
                    def feed(self):
                       print("I eat food.")
                                                                                                    2 M to create
             # child class                                                                          object and call
             class Herbivorous(Animal):                                                                function
                                                                                                Page No: 20 | 21
                               MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION
                                                        (Autonomous)
                                              (ISO/IEC - 27001 - 2013 Certified)
__________________________________________________________________________________________________
               # function feed
                    def feed(self):
                       print("I eat only plants. I am vegetarian.")
herbi = Herbivorous()
             herbi.feed()
             # calling some other function
             herbi.breathe()
             Output:
             I eat only plants. I am vegetarian.
             I breathe oxygen.
                                                                                                Page No: 21 | 21
                          SUMMER-2022 EXAMINATION
Subject Name: Programming with Python Model Answer                   Subject Code: 22616
                                                                               Page 1 of 23
      The List has the variable          The tuple has the fixed length
      length
      List operations are more error     Tuples operations are safe
      prone.
      Lists can be used to store         Tuples are used to store only
      homogeneous                  and   heterogeneous elements.
      heterogeneous elements.
      List is useful for insertion and Tuple is useful for readonly
      deletion operations.             operations like accessing
                                       elements.
       List iteration is slower and is Tuple iteration is faster.
       time consuming.
d)   Explain Local and Global variable                                  2M (1m each)
     Local Variables: Local variables are those which are initialized
     inside a function and belongs only to that particular function. It
     cannot be accessed anywhere outside the function
     Example:
     def f():
         # local variable
         s = "I love Python Programming"
         print(s)
     # Driver code
     f()
     Output
     I love Python Programming
     Global Variables: The global variables are those which are defined
     outside any function and which are accessible throughout the
     program i.e. inside and outside of every function.
     Example:
     # This function uses global variable s
     def f():
       print("Inside Function", s)
     # Global scope
     s = "I love Python Programming"
     f()
     print("Outside Function", s)
     Output:
     Inside Function I love Python Programming
     Outside Function I love Python Programming
e)   Define class and object in python                                    2M (Any suitable
     Class: A class is a user-defined blueprint or prototype from which   definition:  1M
     objects are created. Classes provide a means of bundling data        Each)
     and functionality together.
                                                                             Page 2 of 23
      f)    How to give single and multiline comment in Python              2M (1m each)
            Single line comment: Single-line comments are created simply by
            beginning a line with the hash (#) character, and they are
            automatically terminated by the end of line.
            Example:
            # print is a statement
            print(‘Hello Python’)
            for i in range(1,5):
              for j in range(1,i+1):
                  print(j,end=' ')
              print()
      b)    Explain four Buit-in tuple functions in python with example        4M ( 1M for each
                                                                               function    with
                                                                               example)
                                                                                    Page 3 of 23
c)   Explain how to use user defined function in python with example 4M     (2m   for
         • In Python, def keyword is used to declare user defined explanation and
             functions.                                              2m for example)
         • The function name with parentheses (), which may or may
             not include parameters and arguments and a colon:
         • An indented block of statements follows the function
             name and arguments which contains the body of the
             function.
     Syntax:
     def function_name():
       statements
       .
       .
     Example:
     def fun():
         print(“User defined function”)
     fun()
     output:
     User defined function
                                                                       Page 4 of 23
             statements
             .
             .
           Example:
           def square( x ):
             print("Square=",x*x)
           # Driver code
           square(2)
           Output:
           Square= 4
     d)    Write a program to create class EMPLOYEE with ID and NAME          4M (for correct
           and display its contents.                                          program    and
           class employee :                                                   logic)
              id=0
              name=""
              def getdata(self,id,name):
                self.id=id
                self.name=name
              def showdata(self):
                print("ID :", self.id)
                print("Name :", self.name)
           e = employee()
           e.getdata(11,"Vijay")
           e.showdata()
           Output:
           ID : 11
           Name : Vijay
3   Attempt any THREE of the following                                      12
      a)  List data types used in Python. Explain any two with 4M (2m for list,
          example                                                     and 2m for two
          Data types in Python programming includes:                  example)
             • Numbers: Represents numeric data to perform
                mathematical operations.
             • String: Represents text characters, special symbols or
                alphanumeric data.
             • List: Represents sequential data that the programmer
                wishes to sort, merge etc.
             • Tuple: Represents sequential data with a little
                difference from list.
             • Dictionary: Represents a collection of data that
                associate a unique key with each value.
             • Boolean: Represents truth values (true or false).
                                                                                Page 5 of 23
Example: For number data types are integers.
>>>a=10
>>>b -10
To determine the type of a variable type() function is used.
>>>type(a)
>>> <class 'int'>
                                                                  Page 6 of 23
>>> s1="Hello" #string in double quotes
>>> s2='Hi'      #string in single quotes
>>> s3="Don't open the door" #single quote string in double
quotes
>>> s4='I said "yipee"' #double quote string in single quotes
>>>type(s1)
<class 'str'>
                                                                  Page 7 of 23
     8. Dictionary: Dictionary is an unordered collection of key-
     value pairs. It is the same as the hash table type. The order
     of elements in a dictionary is undefined, but we can iterate
     over the following:
     o The key
     o The value
     o The items (key-value pairs) in a dictionary.
     When we have the large amount of data, the dictionary data
     type is used. Items in dictionaries are enclosed in curly braces
     { } and separated by the comma (,). A colon (:) is used to
     separate key from value. Values can be assigned and
     accessed using square braces ([]).
     Example: For dictionary data type.
     >>> dic1={1:"First","Second":2}
     >>> dic1
     {1: 'First', 'Second': 2}
     >>> type(dic1)
     <class 'dict'>
     >>> dic1[3]="Third"
     >>> dic1
     {1: 'First', 'Second': 2, 3: 'Third'}
     >>> dic1.keys()
     dict_keys([1, 'Second', 3])
     >>> dic1.values()
     dict_values(['First', 2, 'Third'])
     >>>
b)   Explain membership and assignment operators with 4M: 2m for
     example                                                                membership
     Membership Operators: The membership operators in Python are operators and
     used to find the existence of a particular element in the sequence, 2m            for
     and used only with sequences like string, tuple, list, dictionary etc. assignment
     Membership operators are used to check an item or an element operators
     that is part of a string, a list or a tuple. A membership operator
     reduces the effort of searching an element in the list. Python
     provides ‘in’ and ‘not in’ operators which are called membership
     operators and used to test whether a value or variable is in a
     sequence.
      Sr. Operator Description                    Example
      No
      1     in          True if value is         >>> x="Hello
                        found in list or in      World"
                        sequence, and false      >>> print('H' in x)
                        it item is not in list   True
                        or in sequence
      2     not in      True if value is not >>> x="Hello
                        found in list or in World"
                        sequence, and false
                                                                           Page 8 of 23
                    it item is in list or in >>> print("Hello"
                    sequence.                not in x)
                                             False
                                                                       Page 9 of 23
                                                    c=c%a
      7     **=        Performs exponential         c **= a is
                       (power) calculation on       equivalent to
                       operators and assign
                       value to the left operand.   c = c ** a
c)   Explain indexing and slicing in list with example                 4M: (2m for
     Indexing: An individual item in the list can be referenced by indexing and 2m
     using an index, which is an integer number that indicates the for slicing)
     relative position of the item in the list.
     There are various ways in which we can access the elements
     of a list some as them are given below:
     1. List Index: We can use the index operator [] to access an
     item in a list. Index starts from 0. So, a list having 5 elements
     will have index from 0 to 4.
     Example: For list index in list.
     >>> list1=[10,20,30,40,50]
     >>> list1[0]
     10
     >>> list1[3:] # list[m:] will return elements indexed from mth
     index to last index
     [40, 50]
     >>>list1[:4] # list[:n] will return elements indexed from first
     index to n-1th index
     [10, 20, 30, 40]
     >>> list1[1:3] # list[m:n] will return elements indexed from m
     to n-1.
     [20, 30]
     >>> list1[5]
     Traceback (most recent call last):
      File "<pyshell#71>", line 1, in <module>
      list1[5]
     IndexError: list index out of range
     2. Negative Indexing: Python allows negative indexing for its
     sequences. The index of −1 refers to the last item, −2 to the
     second last item and so on.
     Example: For negative indexing in list.
     >>> list2=['p','y','t','h','o','n']
     >>> list2[-1]
     'n'
     >>> list2[-6]
     'p'
     >>> list2[-3:]
                                                                    Page 10 of 23
          ['h', 'o', 'n']
          >>> list2[-7]
          Traceback (most recent call last):
           File "<pyshell#76>", line 1, in <module>
           list2[-7]
           IndexError: list index out of range
          operation.py:
          import calculation
          print(calculation.add(1,2))
          print(calculation.sub(4,2))
          Output:
          3
          2
                                                                         Page 11 of 23
     Ans:
     1)
     >>> dict1={1:"Vijay",2:"Santosh",3:"Yogita"}
     >>>print(dict1)
     {1: 'Vijay', 2: 'Santosh', 3: 'Yogita'}
     ii)
     >>>dict1[2]="Shreyas"
     >>>print(dict1)
     {1: 'Vijay', 2: 'Shreyas', 3: 'Yogita'}
     iii)
     >>>dict1.pop(1)
      ‘Vijay'
     >>>print(dict1)
     {2: 'Shreyas', 3: 'Yogita'}
b)   Explain decision making statements If-else, if-elif-else with 4M (2m for if-
     example                                                        else and 2m for
     The if-else statement: if statements executes when the if-elif-else)
     conditions following if is true and it does nothing when the
     condition is false. The if-else statement takes care of a true
     as well as false condition.
       Syntax-1:                     Or Syntax-2:
       If condition:                 If condition:
            Statement(s)                   If_Block
       else:                         else:
            Statement(s)                   else_Block
      Example:
      i=20
      if(i<15):
         print(" less than 15")
      else:
         print("greater than 15")
      output:
      greater than 15
      Concept Diagram:
                                                                    Page 12 of 23
if-elif-else (ladder) statements: Here, a user can decide among
multiple options. The if statements are executed from the top
down. As soon as one of the conditions controlling the if is true,
the statement associated with that if is executed, and the rest of
the ladder is bypassed. If none of the conditions is true, then the
final else statement will be executed.
Syntax:
if (condition-1):
          statement
elif (condition-2):
          statements
.
.
elif(condition-n):
          statements
else:
          statements
Example:
Example:
i = 20
if (i == 10):
    print ("i is 10")
elif (i == 15):
    print ("i is 15")
elif (i == 20):
    print ("i is 20")
else:
    print ("i is not present")
output:
i is 20
Concept Diagram:
                                                                      Page 13 of 23
c)   Explain use of format() method with example                         4M (2m for use
     The format() method formats the specified value(s) and insert       and 2m for
     them inside the string's placeholder.                               example)
     The placeholder is defined using curly brackets: {}.
     The format() method returns the formatted string.
     Syntax
     string.format(value1, value2...)
     Example:
     #named indexes:
     >>>txt1 = ("My name is {fname}, I'm {age}".format(fname =
     "abc", age = 36))
     >>>print(txt1)
     My name is abc, I'm 36
     #numbered indexes:
     >>>txt2 =( "My name is {0}, I'm {1}".format("xyz",36))
     >>>print(txt2)
     My name is xyz, I'm 36
     #empty placeholders:
     >>>txt3 = ("My name is {}, I'm {}".format("pqr",36))
     >>>print(txt3)
     My name is pqr, I'm 36
d)   Explain building blocks of python                                   4M
     Character set: All characters that python can recognize. The
     below table illustrates the Python character set along with
     examples.
      character Set                   Examples
      Letters: Upper case and         A-Z,a-z
      lower case english
      alphabets
      Digits: all digits              0-9
      Special symbols                 space,+,-,**,*,%,//,/,==,!=,>,<
      Whitespaces                     Blank space,tabs
      Other unicode characters        All ASCII and Unicode characters
     Tokens: Tokens in python are building blocks of the Python
     programming language. The role letters and words play for the
     English language, Similar to role token play for a python
     programming language.
     Python has the following tokens:
     1)keywords
     2)identifiers
     3)literals
       a)String literals
       b)Numeric literals
       c)Boolean Literals
       d)Special literal None
      Tokens                            Example
      Keywords: Words that are          False,True,if,elif,else,for,
      already defined and convey a while,pass,continue,lambda,
                                                                          Page 14 of 23
      special meaning to the           return,finally,import,def
      language
      compiler/interpreter
      Identifiers: names given to      def square,num=20,
      different parts of program       a_lst=[1,2,3];
      like variables, functions,       here square,num and a_lst are
      object, class, names given to    identifiers.
      different datatypes.
      Literals/Constants: Data         String: ‘Mayank‘,’abc‘,’anish‘;
      items that have fixed values     Numeric: 1,1.2,4,-3.95;
                                       Boolean: True,False
      Special literal                  None; meaning nothing
e)   Write a program illustrating use of user defined package in 4M (2m for
     python                                                              defining
     A package is a hierarchical file directory structure that defines a package and 2m
     single Python application environment that consists of modules      for      import
     and subpackages and sub-subpackages, and so on.                     package      in
     Packages allow for a hierarchical structuring of the module         program)
     namespace using dot notation.
     Creating a package is quite straightforward, since it makes use of
     the operating system’s inherent hierarchical file structure.
     Consider the following arrangement:
     mod2.py
     def m2():
       print("second module")
     Syntax-1
     import <module_name>[, <module_name> ...]
     Example:
     >>>import pkg.mod1, pkg.mod2
     >>> pkg.mod1.m1()
     first module
                                                                             Page 15 of 23
            Syntax-2:
            from <module_name> import <name(s)>
            Example:
            >>> from pkg.mod1 import m1
            >>> m1()
            First module
            >>>
            Syntax-3:
            from <module_name> import <name> as <alt_name>
            Example:
            >>> from pkg.mod1 import m1 as module
            >>> module()
            first module
                                                                         Page 16 of 23
Method overloading is a concept in which a method in a class
performs operations according to the parameters passed to
it.
As in other languages we can write a program having two
methods with same name but with different number of
arguments or order of arguments but in python if we will try
to do the same we will get the following issue with method
overloading in Python:
# to calculate area of rectangle
def area(length, breadth):
        calc = length * breadth
        print calc
#to calculate area of square
def area(size):
        calc = size * size
         print calc
area(3)
area(4,5)
Output:
9
TypeError: area() takes exactly 1 argument (2 given)
Python does not support method overloading, that is, it is
not possible to define more than one method with the
same name in a class in Python.
This is because method arguments in python do not have a
type. A method accepting one argument can be called with
an integer value, a string or a double as shown in next
example.
class Demo:
def method(self, a):
      print(a)
obj= Demo()
obj.method(50)
obj.method('Meenakshi')
 obj.method(100.2)
Output:
50
Meenakshi
 100.2
Same method works for three different data types. Thus, we
cannot define two methods with the same name and same
number of arguments but having different type as shown in
the above example. They will be treated as the same
method.
It is clear that method overloading is not supported in python
but that does not mean that we cannot call a method with
different number of arguments. There are a couple of
                                                                 Page 17 of 23
           alternatives available in python that make it possible to call
           the same method but with different number of arguments.
     c)    Write a program to open a file in write mode and append 6M for any
           some content at the end of file                                program with
           file1 = open("myfile.txt", "w")                                suitable logic
           L = ["This is Delhi \n", "This is Paris \n", "This is London"]
           file1.writelines(L)
           file1.close()
           # Append-adds at last
           # append mode
           file1 = open("myfile.txt", "a")
           Output:
           Output of Readlines after appending
           This is Delhi
           This is Paris
           This is London
           TodayTomorrow
                                                                            Page 18 of 23
       same type. Arrays can be made up of any number of
       dimensions.
   •   In NumPy, dimensions are called axes. Each
       dimension of an array has a length which is the total
       number of elements in that direction.
   •   The size of an array is the total number of elements
       contained in an array in all the dimension. The size of
       NumPy arrays are fixed; once created it cannot be
       changed again.
   •   Numpy arrays are great alternatives to Python Lists.
       Some of the key advantages of Numpy arrays are that
       they are fast, easy to work with, and give users the
       opportunity to perform calculations across entire
       arrays.
   •   A one dimensional array has one axis indicated by
       Axis-0. That axis has five elements in it, so we say it
       has length of five.
   •   A two dimensional array is made up of rows and
       columns. All rows are indicated by Axis-0 and all
       columns are indicated by Axis-1. If Axis-0 in two
       dimensional array has three elements, so its length it
       three and Axis-1 has six elements, so its length is six.
Example:
For NumPy with array object.
>>> import numpy as np
>>> a=np.array([1,2,3]) # one dimensional array
>>> print(a)
[1 2 3]
>>> arr=np.array([[1,2,3],[4,5,6]]) # two dimensional array
>>> print(arr)
[[1 2 3]
 [4 5 6]]
                                                                  Page 19 of 23
     >>> type(arr)
     <class 'numpy.ndarray'>
     >>> print("No. of dimension: ", arr.ndim)
     No. of dimension: 2
     >>> print("Shape of array: ", arr.shape)
     Shape of array: (2, 3)
     >> >print("size of array: ", arr.size)
     size of array: 6
     >>> print("Type of elements in array: ", arr.dtype)
     Type of elements in array: int32
     >>> print("No of bytes:", arr.nbytes)
     No of bytes: 24
b)   Write a program to implement the concept of inheritance           6M for any
     in python                                                         suitable
          • In inheritance objects of one class procure the            example     of
              properties of objects of another class.                  inheritance
          • Inheritance provide code usability, which means that
              some of the new features can be added to the code
              while using the existing code.
          • The mechanism of designing or constructing classes
              from other classes is called inheritance.
          • The new class is called derived class or child class and
              the class from which this derived class has been
              inherited is the base class or parent class.
          • In inheritance, the child class acquires the properties
              and can access all the data members and functions
              defined in the parent class. A child class can also
              provide its specific implementation to the functions
              of the parent class.
     Syntax:
      class A:
      # properties of class A
      class B(A):
      # class B inheriting property of class A
      # more properties of class B
                                                                        Page 20 of 23
     car1.disp_price()
     Output:
     Name= Maruti
     Price=$ 2000
                                                                    Page 21 of 23
   •   There can be one or more except blocks. Multiple
       except blocks with different exception names can be
       chained together.
   •   The except blocks are evaluated from top to bottom
       in the code, but only one except block is executed for
       each exception that is thrown.
   •   The first except block that specifies the exact
       exception name of the thrown exception is executed.
       If no except block specifies a matching exception
       name then an except block that does not have an
       exception name is selected, if one is present in the
       code.
   •   For handling exception in Python, the exception
       handler block needs to be written which consists of
       set of statements that need to be executed according
       to raised exception. There are three blocks that are
       used in the exception handling process, namely, try,
       except and finally.
Syntax:
try:
 D the operations here
 ......................
except Exception1:
 If there is Exception1, then execute this block.
except Exception2:
 If there is Exception2, then execute this block.
 ......................
else:
 If there is no exception then execute this block.
                                                                    Page 22 of 23
except IOError:
print ("Error: can\'t find file or read data")
else:
print ("Written content in the file successfully")
fh.close()
Page 23 of 23