Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
0 ratings
0% found this document useful (0 votes)
40 views
Print Python
Uploaded by
[CO - 174] Shubham Mourya
AI-enhanced title
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save print python For Later
Download
Save
Save print python For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
0 ratings
0% found this document useful (0 votes)
40 views
Print Python
Uploaded by
[CO - 174] Shubham Mourya
AI-enhanced title
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save print python For Later
Carousel Previous
Carousel Next
Save
Save print python For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
Download now
Download
You are on page 1
/ 22
Search
Fullscreen
Subject Name: Programming with Python — Model Answer Important Instructions to examiners: 1, The answers should be examined by key words and not as word-to-word a5 & 2 6 the model answer scheme. The model answer and the answer written by candidate may vary but the © may try to assess the understanding level of the candidate. The language errors such as grammatical, spelling errors should not be givel Subject Code: #£6"" iven in aminer »n more Importance (Not applicable for subject English and Communication Skills. - While assessing figures, examiner may give credit for princi indicated in the figure. The figures drawn by candidate and model The examiner may give credit for any equivalent figure drawn. Credits may be given step wise for numerical problems. In some C constant values may vary and there may be some difference in answers and model answer. In case of some questions credit may be given by judgement on part of exam relevant answer based on candidate’s understanding. For programming language papers, credit may be given to any other Progra! on equivalent concept. As per the policy deci ion of Mal jovernment, English/Marathi and Bilingual (Galen eee a is introducet of AICTE diploma Programme from academic year 2021-2022. Henc in first year (first and second semesters) write answers in Mara! language (English +Marathi), the Examiner shall consider the same and ase: answer based on matching of concepts with model answer. jpal_ components answer may Vary- ases, the assumed the candidate’s jiner of m based teaching in d at first year -e if the students ‘thi or bilingual ss the Pe Sub ‘Answer ‘Marking Scheme No. | Q.N. 1_| Attempt Any FIVE of the following 10 a) _ | Name different modes of Python 2M (1m each) Python has two basic modes: Script (Normal Mode) Interactive Mode b) _| Listidentity operators in python 2M (1m each) Identity operators in Python are «is © isnot, ¢) | Give two differences between list and tuple 2M (im for each List Tuple difference, any 2 Lists are mutable Tuples are immutable difference) Lists consume more memory | Tuple consume less memory as compared to the list Lists have several built-in methods Tuple does not have many built-in methods. The unexpected changes and [errors are more likely to occur In tuple, it is hard to take place.has the variable fength List operations are mor prone. ists can be used to store homogeneous and | heterogeneot heterogeneous elements. Tiat is useful for insertion and deletion operations. re error operations like elements. Tuple iteration is faster. [ist iteration is slower and is time consuming. ‘Explain Local and Global variable Local Variables: Local variables are those which are initialized ede a function and belongs only to that particular function. It cannot be accessed anywhere outside the function Example: def £0)? # local variable 3 = "E lov ‘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) 4 Global scope 5="I ove Python Programming” fl) print("Outside Function", s) Output: Inside Function | love Python Programming Outside Function | love Python Programming @ | Define class and object in python 2M i Class: A class is a user-defined blueprint or prototype from which eee eee objects are created. Classes provide a means of bundling data | Each) and functionality together. Object: An object is an instance of a class that has some attributes and behavior. Objects can be used attributes of the class. eeeitonomons) (SOMEC - 27001 -2013 Certified) MAHARASHT, 'RA STATE BOARD OF TECHNICAL EDUCATION f) How to give single and multili it Single line comment: ine comment in Python ted i Example: by the end of line, # print is a statement print(‘Hello Python’) enclosed i Example: “"" Multiline comment used fint("Python Comments") """ a delimiter (""") Triple quotation marks. pri or To add a multiline comment you could insert a # for each line: Example: #This is a comment #written in #more than just one line print("Hello, World!") Single-line comr chs z iments are created simply by Binning a line with the hash (Hi) character, and they are automatically terminat ; ‘Multiline comment: Python multi-line comment is a piece of text 2M (im each), g) _| List different modes of opening file in Python Modes for opening file: | er: open an existing file for a read operation. already contains some data then it will be overridden. override existing data. data in the file will be overridden. override existing data. «wz open an existing file for a write operation. If the file a: open an existing file for append operation. It won't © r#: To read and write data into the file. The previous w+: To write and read data. It will override existing data. «at: To append and read data from the file. It won't 2M (Any 2 names 2M) ‘Attempt any THREE of the following 2) _ | Write a program to print following 1 12 123 1234 for iin range(1,5): for jin range(1,i+1): print(j,end="") print() 12 4M (for correct program and logic) B) _| Explain four Buit-in tuple functions in python with example 4M (4M for each function with example)Description roe of ath hn >>> tupea(123) ee ; Lass farmer — fo ee aaa pat me al ee >>> maxfupt) ap eo ‘vale 0.23) ae = eT value ocous in a tiple 1,2,.3,.24), ee i cae of tuples. >>> tupd=(A,8,C), pee 1.99.29). Cy ae) Searches te pe ora pace >>> wot sndreumsthepostonct where Rwas (1.2.3) found 39> uptindere) 2 upto) Comets aia no woke ©) _| 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 acolon: | / * An indented block of statements follows the function [ name and arguments which contains the body of the | function. Syntax: def function_name(): statements print(“User defined fun fun() output: User defined function Parameterized function: The function may take arguments(s) also called parameters as input within the opening and closing Parentheses, just after the function name followed by a colon. Syntax: def function_name(argumenti, argument2, Page 4 of 23MAHARASHTRA STA (Autonomous) SOMEC -27001 -2013 Certified) TE BOARD OF TECHNICAL EDUCATION statements Example: def square( x): print("Squa # Driver code square(2) Output: a) Write a program to create class EMPLOYEE with ID and NAME and display its contents. class employee ideo name: def getdata(selt,id,name}: self.id=id self.name=name def showdata(self = employee() e-getdata(11,"Vijay") e-showdatal) Output: ID: 41 Name : Vijay Square= 4 4M (for correct program and logic) Attem} it any THREE of the following 12 a) 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). 1. Integers (int Data Type): An integer is a whole number that can be positive (+) or negative (-). Integers can be of any List data types used in Python. Explain any two with | 4M (2m for list, and 2m for two Data types in Python programming includes: example) length, it is only limited by the memory available. Page 5 of 23—T Example: For m | »>>eq10 10 ; 7b ne tne type fa variable >>>typela) >>>
pel) function 1 used: build-in type 10 jalues False das Land | 2. Boolean (Boo! Data Type: The simplest pathon is the bool type, It represents the truth v snd True. Internally the true value is represent false is 0 | For example pooa=18>5 >>>print(a) True b=2>3 print(b) False 43. Floating-Point/Float Numbers (Float Data Type): Floating point number or Float is a positive or negative number with a fractional part. A floating point number is accurate up to 15 decimal places. integer and floating points are separated by decimal points. 1is integer, 1.0 is floating point number. Example: Floating point number. 10.1 type(x)
4. Complex Numbers (Complex Data Type): Complex numbers are written in the form, x + yj, where x is the real part and yis the imaginary part. Example: Complex number. >on = 3+4j >>>print(x.real) 3.0 >>>print(x.imag) 40 5. String Data Type: String is a collecti characters. Strings are identified as a characters enclosed in single quotes (' "), Any letter, a number or a symbol string. Strings are unchangeable (im is created, it cannot be modified, Example: For string data type. ion of group of 2 contiguous set of ) oF double quotes (* could be a part of the mutable). Once a stringMAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISOMEC - 27001 - 2013 Certified) >>> s1="Hello” dstring in double quotes >>>s2='Hi' —_fistring in single quotes >>> s3="Don't open the door" single quote string in double | quotes | | >>> s4="lsaid "yipee" #tdouble quote string in single quotes >>>type(s1) |
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] >>> secon list >>> first [10, 20, 30} >>> second [One’, 'Two!, ‘Three'] >>> first+ second —_# prints the concatenated lists [10, 20, 30, 'One', 'Two', 'Three'] # homogenous values in list ","Three"] # homogenous values in 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',143)) >>>a (10, ‘abc’, (1+3))) >>> a[0] 10 >>> a[0]=20 Traceback (most recent call last): File "
", line 1, in
=BOARD OF TECHNICAL EDUCAT) ‘utonomous) MAHARASHTRA STATE ‘ 1013 Certified) 71s an unordered collection of key- —13-pictionary: Dictionary is an unordered c Je aereni is the same as the hash table type. The order irs, It is th (povere tale ry is undefined, but we can iterate | of elements in a dictionar over the following: Jo The key | o The value | 0 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. >>> dicl=(1:"First","Second”:2) | >> diel 41; 'Frst’, ‘Second’: 2) >>> type(dict)
>>> dict{3}="Third" >>> dict {A First’ Second’: 2, 3: Third’) >>> dict keys) keys({2, ‘Second’, 3)) >>> dicL.valuest) | dict_values({ First’, 2, Third’)) | >>> | ION (asOMEC -27001 | Explain membership and assignment operators with | aM: | example Used to find the existence of a particular element in the sequence, | 2m, and used only with sequences lice string, tuple, lst, dictionary etc. | assignment 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. 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. St. ] Operator | Deseription Example No 1 fin True “if value _is | >>> x="Hello found in list or in} World" Sequence, and false | >>> print('H in x) it Rem is not in tst | True oF in sequence 2 notin | True if value ts not | >>> s"Hello found iin list or in| World" Sequence, and false | membership |_| serbersipOperstor: The membership apertorsin Python are | “rersecns operators and | forBOARD OF TECHNICAL EDUCATION ‘(Autonomoas) ~27001 - 2013 Certified) ititem isin list orin Sequence, ss So Meme WE dsonec >>> print("Hello™ not in x) False | Assignment t ‘ Raine ao (Augmented Assignment Operators): Values toe patators are used in Python programming to assign Value on tran atles. The assignment operator is used to store the le right-hand side of the expression on the left-hand side Variable in the expression. For example, a =5 is a simple assignment operator that assigns the pie 5.on the right to the variable a on the left. ere are various compound operators in Python like a += 5 that Adds to the variable and later assigns the same. It is equivalent to +5. Following table shows assignment operators in Python programming: | Sr. | Operator | Description Example No. | 1 | Assigns values from right [c=a+b I] | side operands to | assigns value ] | | ofa+b | | left side operand. | intoc | Tadd right operandto | c+=ais | the left operand and equivalent to assign the resulttoleft_ | c=c+a ‘operand. = = it subtracts right operand | c-=ais from the left equivalent to operand andassignthe | c=c-a result to left operand. 4 it multiplies right operand | operand and with the left assign the result to left ‘operand and assign the operand. result to left operand. c*=ais equivalent to =c*a 5 itdivides left operand | c/=ais with the right operand | equivalent to and assign the result to 7 left operand. catia 6 = It takes modulus using ch ais two operands and assign | equivalent to the result to left operand.Farms epost feelin? oo od [eSectsteom Performs ex (power) calculati ‘operators and assign Value to the left operand. jonon ‘and slicing in list with example Mjual item in the list can be referenced by | ning an index, which is an integer number that indicates the felative position of the item in the list. | rere 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, alist having 5 elements will have index from 0 to 4. ‘Example: For list index in list. >>> list1=[10,20,30,40,50] >>> list {0} “ 10 >>> list index to last index | [40, 50] | ppplist1[:4] # listl. .n} will return elements indexed from first | | index to n-ath index | (29,20, 30 40) \ | >>> fist2[1:3] # list{m:n] will return elements indexed from m | ton-1. | (20, 30] >>> list1{5] Traceback (most recent call last): File "
", line 1, in
lista{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. ‘or negative indexing in list. | Expin iene | indexing: An indi ff list{m:) will return elements indexed from mth >>> list2{-1] >> list2[-6] >>> list2{-3:] am: (2m for indexing and 2m for slicing) Page 10 of 23MAHARAs: TRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) GSOMEC - 27001 -2013 Certified) 2 a moh 3 x SO foal | >>> tist2p-7) | | | Traceback File "
", line 1, in
index out of range Ust Slicing: Sicing isan operation that allows us to extract Clements from units. The slicing feature used by Python to obtain a specific subset or element of the data structure Using the colon (:) operator. 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] This will return the subset of the list starting from star to one index less than that of the endind Example: For slicing list. '=([10,20,30,40,50]) dex | | >>>1212:5] | | | [30,40,50) meee a program for importing module for addition and 4M (for correct @) [wr 1 subtraction of two numbers logic and calculation.py: program) def add(x,y): return (x+y) + def sub(xy): return (x-y) operation.py: import calculation print(calculation.add(1,2)) print(calculation.sub(4,2)) Output: 3 2 12 llowin 4 | Attempt any THREE of the following 4M (2m for i), Write a program to create dictionary of student the les their ROLL NO and NAME aaa three students in above dictionary 1m for ii) and 1m for ili) i Update name="Shreyas’ of ROLL NO=2 iii) Delete information of ROLL NO=1 Pace 11 of 23MAHARASHTRA STATE BOARD OF TEI nomen) qsomec -27001 - 2013 Certified) N y >>> dictl={1! >p>print(dict1) {1: ‘Vijay’, 2:'Santosh’, jay" 2:tsantosh’,3:"Yoetta") “Yogita’) ii) >padicti[2]="Shreyas" >>print(dict) {1:'Vijay’, 2: Shreyas’, 3: itl) >>odict1 pop() (CHNICAL EDUCATION vijay’ >>oprint(dict1) {2:'Shreyas', 3: 'Yogita’} by | Explain decision making statements if-else, iFelif-else with | 4M (2m for if- example else and 2m for The ielse statement: if statements executes when the | if-elif-lse) conditions following if is true and it does nothing when the condition is false. The if-else statement takes care of a true If_Block i | else: II | else_Block Example: is20 iffic15): print(" less than 15") else: print("greater than 15") ‘output: [pesiertun is teed com eal ‘Concept Diagram: Page 12 of 23MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION au) tonooes) (ISOMEC - 27001 -2013 Certified) 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 itfin= 10) print ("tis 10") elif (i== 15): print (135%) elif (i== 20); print ("1s 20") else: Print (isnot present") output: 1is20 Concept Diagram: Statement 1 statement 3 Page 13 of 23,p or THEM TE BOAR! MAHARASHTRA STATE 1G poe ec - 37001 -2013 Core ith example a Value(s) and insert Explain use The format() method formats" js placeholder, them inside the string’ P ’ ‘The placeholder i dined Une ‘curly b suet Tre format() method rerum Ne formatte ) value? syntax ‘string. format(valuel, example: finamed indexes soobath = ("My name abe", age =36)) >opprint( txt) My name is abo 'm 36 format(fname * ne), tm (a | numbered indexes pootat2 ("My name I (0) >eoprint(bet2) ‘My name is xyz, 'm 36 ny (1)"forman("xy2".36)) empty placeholders: setts = My name i Q, fm {)"format("Par"36)) >opprint(tat3) ‘name is fm 36, sana eS ter | ‘examples. he | [ characterSe Eaniph | betters: Upper case and ALae Vi | sees seh fo | |e — a 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: )keywords 2jidentifiers 3)literals String literals b)Numerictterals Boolean Literals 4)Special literal None Tokens Example Keywords: Words that are | False, True,ifelif,else,for, already defined and convey a | while,pass,continue,lambda, ICAL EDUCATION AIA (200 FOF ion and am example) Page 14 of 29STATE Boar OF TECHNICAL EDUCATION | (utoaomous) [specie eR 3700-2013 Corte lan eaning to the | ret guage ‘urn finally,import,det Higeneuetdinterpreter ntifiers: ater pre Bivento | def square,num=20, ie rogram | a Ist=[1,2,3); aes functions, here square,num and a_Ist are : lass, names given to | identifiers. Ciierent datatypes, jterals/Constants: Data | String: ‘Mayank’/abe’anish’; "ms that have fixed values | Numeric: 1,1.2,4,-3.95; y Boolean: True, False | Special literal None; meaning nothing Write a program illustrating use of user defined package in python Apackage isa hierarchical file directory structure that defines a single Python application environment that consists of modules and subpackages and sub-subpackages, and so on. Packages allow for a hierarchical structuring of the module 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 By def m1(): print("first module") mod2.py def m2(): print("second module”) Ifthe pkg directory resides ina location where it can be found, you can refer to the two modules with dot notation(pkg.mod1, pkg.mod2) and import them with the syntax: Syntax-1. import
[,
..] Example: >>>import pkg.mod1, pkg.mod2 >>> pkg.mod1.m1() first module | 4M (2m__ for | defining | | package and 2m | for package | program) import | in |cc cnabdormaeicinan's peo 0 heen ingest mat mu (Gutosomous) (ISOMEC - 27001 - 2013 Certified) aclass Method overloading is a concept in which a method | 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 ito calculate area of square | def area(siz calc= size * size print calc area(3) | area(4,5) } ourput: |? pe€rror: area() takes exactly 1 argument (2 given) thon 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. Thisis because method arguments in python do not have a type. Amethod 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= Demol) 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. Itis 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 23MAHAR sone hon that make it P svailable in pYt be 19 a eel put with different number of arf iment st an method but wil ¢ t wt ee ram to open a file in write mode and appe > F write 2 Prot ‘ome content at the end of file ooo = open("myfile.txt", "W") 4 zs erin pel", “This is Paris \n", "This is London"] file1. writelines(L) file1.close() # Append-adds at last # append mode file = open("myfile.tet", “a") # writing newline character file1.write("\n") file1.write("Today") # without newline character fileL.write("Tomorrow") let = open("myfile.txt", "r") print("Output of Readlines after appending") printifile1.read()) print() file1.close() | | Output: | Output of Readlines after appending | | This is Delhi | | This is Paris | This is London | TodayTomorrow ‘Attempt any TWO of the following a) | Explain package Numpy with example computing with Python, NumPy stands for “Numerical Python". It provides a high-performance multidimensional array object, and tools for working with these arrays. + Anarray isa 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 6M for any program — with | suitable logic | « 12 6M (3m for] NumpPy is the fundamental package for scientific | explanation and 3m for example)STATE BOARD OF TECHNICAL EDUCATION \utonomous) GSOMEC -27001 - 2013 Certified) same type. Arra Rimensions be made up of any number of In a ae oe are called axes. Each Rare ey. has a length which is the total a er of elements in that direction. pea a fn ara isthe total cuimberof elements 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. * Aone dimensional array has one axis indicated by -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-O and all | columns are indicated by Axis-1. If Axis-O 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: 5 python -m pip install numpy To use NumPy you need to import Numpy: import numpy as np # alias np Using NumPy, 2 developer can perform the following operations: 1. Mathematical and logical operations on arrays. 2 Fourier transforms and routines for shape manipulation. 3, Operations related to linear algebra. 4. NumPy has in-built functions for linear algebra and random number generation Exampl For NumPy with array object. >>> import numpy as NP >>> a=np.array({1,2,3]) # one dimensional array >>> print(a) (123) >>> arrenp.array({{1,2,3],{4,5,6]]) # two dimensional array >>> print(arr) (123) (45 6] Page 19 of 23EDUCATION rma STATE BOARD OF TECHNICAL MAHARASH an ae qsonec-27001 -2013 Certifies ) ues, ete Spe typelart) oe | calass ‘numpy.ndarray | Soe print("No, of dimension: *, arr.ndim) | | No. of dimension: 2 |e. print(*Shape of array: ",arr-shape) feat Shape of array: (2, 3) >> »print( "size of array: | >>> print("Type of elements in array: ", arr.dtype) | | Type of elements in array: int32 ,arr-size) >>> print("No of bytes:", arr.nbytes) No of bytes: 24 ib) | Write a program to implement the concept of inheritance |6M for any in python. suitable yin heritance objects of one class procure the example of Inheritance properties of objects of another class. «Inheritance provide code usability, which means that some of the new features can be added to the code ‘while using the existing code. Sites . wna i a etre eee ee -” fromother classesis 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. | + Ininheritance, 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 Example 1: Inheritance without using constructor. class Vehicle: Hparent class name="Maruti" def display(self): print("Name= ",self.name) class Category(Vehicle}: derived class price=2000 def disp_price(se! print("Price: carl=Category() carl.display() "self.price)a a) {(SoMEC -27001 -2013 Certified) MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION ‘utonomos ‘cari.disp_price() Output: Name= Maruti Price=$ 2000 Example 2: Inheritance using constructor, class Vehicle: Hiparent class def _init_(self;name)}: ‘elf.name=name def display(self): print(*Name=",self.name) class Categoryvehicle) derived class def _init_(selfyname,price): Vehicle.__Init__(self,name) st passing data to base cass constructor self.price=price def disp_price(self) print("Price=$ ",self.price) carleCategory("Maruti",2000) carl.display() | cart.disp_price() car2=Category("BMW",5000) | car2.display() car2.disp_pricel) Output: Name= Maruti Price=$ 2000 Name= BMW Price=$ 5000 C} Explain Try-except block used in exception handling in | 6M statement. A try block consisting of one or more statements is used by programmers to partition code that might be affected by an exception. «A critical operation which can raise exception is placed inside the try clause and the 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. (Gm for python with example explanation and + in Python, exceptions can be handled using a try | 3m for program) Page 21 of 23There can be on ‘except blocks with different excel chained together Be e The except blocks are evaluated from ‘top to bot jin the code, but only on& except black is executed for teach exception that is thrown the ae block that specifies the exact exception name of the thrown exception Is executed. if ne except block specifies @ matching exception ¥ re ahen an except block that does AOE HN rception 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 | ced in the exception handling process, namely, tr¥, except and finally. A.try Block: A set of statements that may cause error during runtime are to be written in the try block. 2. except Block: Its 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 fren exception occurs in the execution of statements written in | the try block. 3. finally Block: This is the last block written while writing an exception handler in the program which indicates the set o! statements that many use to clean up to resources used the program. | syntax: | | ty: | | Othe operations here | except Exception: | Ifthere is Exceptiont, then execute this block. except Exception2: If there is Exception2, then execute this block. else: If there is no exception then execute this block. Example: For try-except clause/statement. try: fh = open("testfile", “w") fh.write("This is my test file for exception handling!!")BOARD OF TECHNICAL EDUCATION s) MAHARASHTRA STATE “yr001 - 2013 Certified) (SOmEC except |OError: print ("Error: can\'t find file or read data") \e file successfully") else: print ("Written content in th th.closel
You might also like
s22
PDF
No ratings yet
s22
12 pages
Question Bank's
PDF
No ratings yet
Question Bank's
89 pages
22616-Model- -Answer-Summer- 202222616
PDF
No ratings yet
22616-Model- -Answer-Summer- 202222616
29 pages
PWP Model Answer Summer 2022
PDF
100% (9)
PWP Model Answer Summer 2022
23 pages
ALL IN ONE PWP (S22,W22,S23,W23) MAPS-output
PDF
No ratings yet
ALL IN ONE PWP (S22,W22,S23,W23) MAPS-output
90 pages
py1_py2_py3_py4_merged
PDF
No ratings yet
py1_py2_py3_py4_merged
88 pages
(22616) PWP SUMMER-2022 ANSWER PAPER
PDF
No ratings yet
(22616) PWP SUMMER-2022 ANSWER PAPER
23 pages
Python Notes
PDF
No ratings yet
Python Notes
3 pages
12cs-Study Material Cs 2023-24
PDF
No ratings yet
12cs-Study Material Cs 2023-24
121 pages
Python Winterr
PDF
No ratings yet
Python Winterr
11 pages
12th Phython Unit-1 PDF
PDF
No ratings yet
12th Phython Unit-1 PDF
86 pages
Unit 1
PDF
No ratings yet
Unit 1
86 pages
Paython
PDF
No ratings yet
Paython
66 pages
Python Solved QP
PDF
No ratings yet
Python Solved QP
17 pages
Winter-23 Python Model Answer
PDF
No ratings yet
Winter-23 Python Model Answer
20 pages
Python Introduction
PDF
No ratings yet
Python Introduction
53 pages
Study Matriel For Class12 Cs
PDF
No ratings yet
Study Matriel For Class12 Cs
120 pages
A Powerpoint Presentation On Python: by Durga Prasad Kopanathi
PDF
No ratings yet
A Powerpoint Presentation On Python: by Durga Prasad Kopanathi
33 pages
Python QB
PDF
No ratings yet
Python QB
3 pages
CT1 Q-Bank
PDF
No ratings yet
CT1 Q-Bank
34 pages
SYBSc(CS) Electronics Practical Sem IV Introduction to Python
PDF
No ratings yet
SYBSc(CS) Electronics Practical Sem IV Introduction to Python
23 pages
Python
PDF
No ratings yet
Python
10 pages
Python W22
PDF
No ratings yet
Python W22
11 pages
PWP Question Paper Answer Sheet - Compress
PDF
No ratings yet
PWP Question Paper Answer Sheet - Compress
17 pages
W-22 22616 PWP
PDF
No ratings yet
W-22 22616 PWP
21 pages
m1 Python Notes
PDF
No ratings yet
m1 Python Notes
51 pages
Class-11-Preview of Python Notes
PDF
No ratings yet
Class-11-Preview of Python Notes
25 pages
Python Important Questions For Mid Term Exam..
PDF
No ratings yet
Python Important Questions For Mid Term Exam..
10 pages
22616
PDF
No ratings yet
22616
23 pages
Programming With Python Solution W22
PDF
No ratings yet
Programming With Python Solution W22
21 pages
Python 2
PDF
No ratings yet
Python 2
23 pages
PWP Notes (Chapter Wise)
PDF
100% (1)
PWP Notes (Chapter Wise)
123 pages
Introduction To Python
PDF
No ratings yet
Introduction To Python
46 pages
SSSSKKKKKK
PDF
No ratings yet
SSSSKKKKKK
20 pages
note by kk 1
PDF
No ratings yet
note by kk 1
11 pages
Python
PDF
No ratings yet
Python
42 pages
Introduction To Python
PDF
No ratings yet
Introduction To Python
56 pages
CHAPTER PYTHON FUNDAMENTAL
PDF
No ratings yet
CHAPTER PYTHON FUNDAMENTAL
16 pages
Unit 2
PDF
No ratings yet
Unit 2
16 pages
Cca62-Python Programming
PDF
No ratings yet
Cca62-Python Programming
53 pages
Python Notes
PDF
No ratings yet
Python Notes
141 pages
class xi AI-chinhat
PDF
No ratings yet
class xi AI-chinhat
16 pages
1)intro
PDF
No ratings yet
1)intro
5 pages
Python 3 Introduction
PDF
No ratings yet
Python 3 Introduction
59 pages
Python.notes
PDF
No ratings yet
Python.notes
13 pages
Viva Question Ans
PDF
No ratings yet
Viva Question Ans
8 pages
Paper Solution
PDF
No ratings yet
Paper Solution
11 pages
Basic Python
PDF
No ratings yet
Basic Python
101 pages
Python QB ans
PDF
No ratings yet
Python QB ans
3 pages
01_Python_I_All_Master_13_02_2025
PDF
No ratings yet
01_Python_I_All_Master_13_02_2025
258 pages
Module 5 Programming Foundation and Exploratory Data Analysis
PDF
No ratings yet
Module 5 Programming Foundation and Exploratory Data Analysis
152 pages
Python
PDF
No ratings yet
Python
90 pages
chap 1 notes
PDF
No ratings yet
chap 1 notes
8 pages
Pushkar 6 Weeks Industrial Training Report
PDF
No ratings yet
Pushkar 6 Weeks Industrial Training Report
82 pages
PythonTraining MD Saiful Azad UMP
PDF
No ratings yet
PythonTraining MD Saiful Azad UMP
54 pages
Python Identifiers
PDF
No ratings yet
Python Identifiers
32 pages
Skewness - Definition, Examples & Formula
PDF
No ratings yet
Skewness - Definition, Examples & Formula
10 pages
Concurrency Control
PDF
No ratings yet
Concurrency Control
31 pages
DBMS Ese
PDF
No ratings yet
DBMS Ese
96 pages
DBMS 1-4
PDF
No ratings yet
DBMS 1-4
36 pages
Advance Java Chapter 1 Full Notes - Ur Engineering Friend-1
PDF
100% (1)
Advance Java Chapter 1 Full Notes - Ur Engineering Friend-1
33 pages
Live Seminar: Subject - Operating System Date - 07 Dec, 2022
PDF
No ratings yet
Live Seminar: Subject - Operating System Date - 07 Dec, 2022
89 pages
Advance Java - Exam Sutra MCQ Book by Ur Engineering Friend
PDF
100% (1)
Advance Java - Exam Sutra MCQ Book by Ur Engineering Friend
66 pages
How Does ChatGPT Work
PDF
No ratings yet
How Does ChatGPT Work
8 pages
Exam Sutra: EST EST
PDF
No ratings yet
Exam Sutra: EST EST
133 pages
ETI Chapter 1. Artificial Intelligence
PDF
No ratings yet
ETI Chapter 1. Artificial Intelligence
45 pages
MAD EXP6 Prog
PDF
No ratings yet
MAD EXP6 Prog
5 pages
MGT - CO3 - All Assessment (5 Files Merged)
PDF
No ratings yet
MGT - CO3 - All Assessment (5 Files Merged)
18 pages
Assessment Type: Summative: End of CO: in LMS
PDF
No ratings yet
Assessment Type: Summative: End of CO: in LMS
9 pages
Crowd Coin PPT
PDF
No ratings yet
Crowd Coin PPT
5 pages
STE (22518) - 1st Class Test Question Bank
PDF
No ratings yet
STE (22518) - 1st Class Test Question Bank
1 page
Related titles
Click to expand Related Titles
Carousel Previous
Carousel Next
s22
PDF
s22
Question Bank's
PDF
Question Bank's
22616-Model- -Answer-Summer- 202222616
PDF
22616-Model- -Answer-Summer- 202222616
PWP Model Answer Summer 2022
PDF
PWP Model Answer Summer 2022
ALL IN ONE PWP (S22,W22,S23,W23) MAPS-output
PDF
ALL IN ONE PWP (S22,W22,S23,W23) MAPS-output
py1_py2_py3_py4_merged
PDF
py1_py2_py3_py4_merged
(22616) PWP SUMMER-2022 ANSWER PAPER
PDF
(22616) PWP SUMMER-2022 ANSWER PAPER
Python Notes
PDF
Python Notes
12cs-Study Material Cs 2023-24
PDF
12cs-Study Material Cs 2023-24
Python Winterr
PDF
Python Winterr
12th Phython Unit-1 PDF
PDF
12th Phython Unit-1 PDF
Unit 1
PDF
Unit 1
Paython
PDF
Paython
Python Solved QP
PDF
Python Solved QP
Winter-23 Python Model Answer
PDF
Winter-23 Python Model Answer
Python Introduction
PDF
Python Introduction
Study Matriel For Class12 Cs
PDF
Study Matriel For Class12 Cs
A Powerpoint Presentation On Python: by Durga Prasad Kopanathi
PDF
A Powerpoint Presentation On Python: by Durga Prasad Kopanathi
Python QB
PDF
Python QB
CT1 Q-Bank
PDF
CT1 Q-Bank
SYBSc(CS) Electronics Practical Sem IV Introduction to Python
PDF
SYBSc(CS) Electronics Practical Sem IV Introduction to Python
Python
PDF
Python
Python W22
PDF
Python W22
PWP Question Paper Answer Sheet - Compress
PDF
PWP Question Paper Answer Sheet - Compress
W-22 22616 PWP
PDF
W-22 22616 PWP
m1 Python Notes
PDF
m1 Python Notes
Class-11-Preview of Python Notes
PDF
Class-11-Preview of Python Notes
Python Important Questions For Mid Term Exam..
PDF
Python Important Questions For Mid Term Exam..
22616
PDF
22616
Programming With Python Solution W22
PDF
Programming With Python Solution W22
Python 2
PDF
Python 2
PWP Notes (Chapter Wise)
PDF
PWP Notes (Chapter Wise)
Introduction To Python
PDF
Introduction To Python
SSSSKKKKKK
PDF
SSSSKKKKKK
note by kk 1
PDF
note by kk 1
Python
PDF
Python
Introduction To Python
PDF
Introduction To Python
CHAPTER PYTHON FUNDAMENTAL
PDF
CHAPTER PYTHON FUNDAMENTAL
Unit 2
PDF
Unit 2
Cca62-Python Programming
PDF
Cca62-Python Programming
Python Notes
PDF
Python Notes
class xi AI-chinhat
PDF
class xi AI-chinhat
1)intro
PDF
1)intro
Python 3 Introduction
PDF
Python 3 Introduction
Python.notes
PDF
Python.notes
Viva Question Ans
PDF
Viva Question Ans
Paper Solution
PDF
Paper Solution
Basic Python
PDF
Basic Python
Python QB ans
PDF
Python QB ans
01_Python_I_All_Master_13_02_2025
PDF
01_Python_I_All_Master_13_02_2025
Module 5 Programming Foundation and Exploratory Data Analysis
PDF
Module 5 Programming Foundation and Exploratory Data Analysis
Python
PDF
Python
chap 1 notes
PDF
chap 1 notes
Pushkar 6 Weeks Industrial Training Report
PDF
Pushkar 6 Weeks Industrial Training Report
PythonTraining MD Saiful Azad UMP
PDF
PythonTraining MD Saiful Azad UMP
Python Identifiers
PDF
Python Identifiers
Skewness - Definition, Examples & Formula
PDF
Skewness - Definition, Examples & Formula
Concurrency Control
PDF
Concurrency Control
DBMS Ese
PDF
DBMS Ese
DBMS 1-4
PDF
DBMS 1-4
Advance Java Chapter 1 Full Notes - Ur Engineering Friend-1
PDF
Advance Java Chapter 1 Full Notes - Ur Engineering Friend-1
Live Seminar: Subject - Operating System Date - 07 Dec, 2022
PDF
Live Seminar: Subject - Operating System Date - 07 Dec, 2022
Advance Java - Exam Sutra MCQ Book by Ur Engineering Friend
PDF
Advance Java - Exam Sutra MCQ Book by Ur Engineering Friend
How Does ChatGPT Work
PDF
How Does ChatGPT Work
Exam Sutra: EST EST
PDF
Exam Sutra: EST EST
ETI Chapter 1. Artificial Intelligence
PDF
ETI Chapter 1. Artificial Intelligence
MAD EXP6 Prog
PDF
MAD EXP6 Prog
MGT - CO3 - All Assessment (5 Files Merged)
PDF
MGT - CO3 - All Assessment (5 Files Merged)
Assessment Type: Summative: End of CO: in LMS
PDF
Assessment Type: Summative: End of CO: in LMS
Crowd Coin PPT
PDF
Crowd Coin PPT
STE (22518) - 1st Class Test Question Bank
PDF
STE (22518) - 1st Class Test Question Bank