0% found this document useful (0 votes)
11 views20 pages

PWP 2

The document outlines the assessment guidelines for the Programming with Python subject for the Winter 2023 examination by the Maharashtra State Board of Technical Education. It emphasizes the importance of understanding over exact wording in answers, allows for credit based on equivalent concepts, and includes instructions for assessing answers in both English and Marathi. Additionally, it provides sample questions and answers related to Python programming concepts such as data hiding, namespaces, and file handling methods.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
11 views20 pages

PWP 2

The document outlines the assessment guidelines for the Programming with Python subject for the Winter 2023 examination by the Maharashtra State Board of Technical Education. It emphasizes the importance of understanding over exact wording in answers, allows for credit based on equivalent concepts, and includes instructions for assessing answers in both English and Marathi. Additionally, it provides sample questions and answers related to Python programming concepts such as data hiding, namespaces, and file handling methods.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 20
ey MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION = asomec “27001 413 Cered) ‘Subject Name: Programming with Python Subject Code: | 22616 D 2 » 4 » ° n ® WINTER — 2023 EXAMINATION ‘Model Answer ~ Only for the Use of RAC Assessors “The answers should be examined by key words and not as word-to-word as given in the model answer scheme, ‘The model answer and the answer written by candidate may vary but the examiner may try to assess the understanding level of the candidate ‘The language errors such as grammatical, spelling errors should not be given more Importance (Not applicable for subject English and Communication Skills ‘While assessing figures, examiner may give credit for principal components indicated inthe figure. The figures drawn, by candidate and model answer may vary. The examiner may give credit for any equivalent figure drawn, Credits may be given step wise for numerical problems. In some cases, the assured constant values may vary and there may be some difference in the candidate's answers and model answer, In case of some questions eredit may be given by judgement on part of examiner of relevant answer based on candidate's understanding For programming language papers, credit may be given to any other program based on equivalent concep ‘As per the policy decision of Maharashica State Government, teaching in English’Marati and Bilingual (English + Marathi) medium is introduced at first year of AICTE diploma Programme from academic year 2021-2022. Hence if the studeats in Gist year (fst and second semesters) write answers in Marathi or bilingual language (Eaglish 4+Marzthi, the Examiner shall consider the same and assess the answer baced on matching of concepts with model ‘Sub ‘Answer Marking Q ‘Scheme N. ‘Attempt any FIVE of the following: 10M ‘a) | Enlist spplieations for python programming. 2M ‘Ans | Google's Amp Engine web development framework uses Pyition as an application | Any two language. application, ‘+ Mays, a powerful integrated 3D modeling and animation system, provides a Python | One application senpting APL for IM each + Linux Weekly News. published by using a web application written in Python, * Google makes extensive use of Python in its Web Search Sysiems. © The popular YouTube video sharing service is largely writen in Python programming + The NSA uses Python for cryptography and imtlligence analysis. iRobot uses Pybon 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 otbers uses Python in the production of animated movies. Desktop GUI Applications mage Processing Applications ‘© Sciemific and Numeric Applications = Audio and Video Based Applications # 3D CAD Applications Page No: 1 | 20 (tone mens) aia) MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION, (ASOMEC - 27001 2013 Certified) = Software Development ¢_Web Applications b ‘Write the use of elif keyword in python. 2M ‘Ans “GP stands for else if and is used in Python programming to test multiple conditions, ‘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 Tadder is bypassed. If none of the conditions is true, then the final else statement will be executed. Correct explanation 2 M ° Describe the Role of indentation in python. 2M ‘Ans Indentation refers to the spaces atthe beginning of a code line. ‘© Generally, four whitespaces are used for indentation and is preferred over tabs. ¢ Where in other programming languages the indentation in cade 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: if5>2: print Five is greater than two!”) Correct Role 2 a ‘Ans e ‘Define Data Hiding concept? Write two advantages of Data Hiding. > Data hiding user. © Data hiding is a software development technique specifically used in Object-Oriented Programming (OOP) ta hide internal object details (data members). ‘© 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 ‘2 concept which underlines the hiding of data or information from the Advantages of Data Hiding Data hiding ensures exclusive data access to class members and protects object imegrity by preventing unintended or intended changes. © Data hiding is also known as information hiding. An object's attributes may or may not be visible outside the class definition, Data hiding also minimizes system complexity for increase robustness by limiting ierdependencies between software requirements “The objects within the clas are disconnected from relevant data Itheightens the security against hackers that are unable to access confidential data. Ithelps to prevent damage to volatile data by bing i rom the public. A. user outside from the organization cannot attain the access to the data, ‘Within the organization system only specific users get the acces. This allows beter ff ‘State use of namespace in python. 2M ‘Any relevant Definition 1 M, any two Advantages 1 M 2M ‘Ans ‘= Namespaces bring you three advantages: they group names into logical containers, they prevent clashes between duplicate names, and third, they provide context to names. ‘Correctrelevant use 2M_ Page No: 2 | 20 MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION uteeoas) (ASonBC 27001-2013 CertiNed) ‘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. ‘+ Anamespace in python isa collection of names. So, a namespace is essentially a mapping of names to corresponding objects. 2.extend() Method: The extend) method extends alist by appending items. We ean add several items using extend) method. Example: Program for extend() methed. >>olistt={10, 20, 30,40) Soolistl 10, 20, 30,40) >>> list extend({60,70)) fad elements at the end of list, >>> list {10, 20,30, 40,60, 70] 1D _| State the use of read() and readline () functions in python file handling, 2M ‘Ans | 1. read({u)) Method: read) 1 Mand The read method reads the entire contents ofa file and returns it as a string, if number | readline() of bytes are not given in the argument. If we execute read(3), we will get back the first three characters of the file. ae Example: for read() method, (eampreiirane fopen("sample tx","r") > print(fread(5)) # read first 5 data print(freadQ) —# read rest of the file 2, readline({n}) Method: ‘The readfine() method just oviput the entire line whereas readline(n) outputs at most bytes ofa 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. feopen("sample.txt","r") print¢f-readline()) # read first line followed by\n print(freadline(3)) print(f readline) ® _ | Explain two ways to add objects / elements to ist. 2M “Ans | Thappend method: The append() method aids an clement to the end of alia. We can inser | 1 Method for 1 ‘single item in te list data time with the append). M (any two ‘Example: For append() method. >>> list=|10.20,30) imetiodt) >>> lst 10, 20, 30) >>> append) Fd element tthe end of ist sexonystvnee 10, 20, 30, 40], mandatory) Page No: 3 | 20 az MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION ~ scans = sone. Fn 313 ere 3 inseriO) Method: We can inert one single lem ata desied location by using the method insen( or insert multiple items by squeezing i into an empty slice ofa list Example: Program for insert) method. >>> list=[10, 20) >>>listt 110,20] >>> list inser(130) >> list 10, 30, 20) 2 ‘Attempt any THREE of the following: 2M ‘a) | Explain membership and identity operators in Python. aM ‘Ans | Membership Operators: ‘Membership ‘The membership operators in Python are used to find the existence of a particular | operator 2M. clement in the sequence, and used only with sequences like string, tuple, list, and Identity dictionary etc. roc Fak Membership operators are used to check an item or an element that is part of a string, | °P*™ alist 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. ‘Operator | Description ‘Example im "Trae i value is found in iat arin | >>> x= "Hello Workd™ sequence, and false it item is not | >>> print(H in x) in list or in sequence notin “True if value is not found in list ‘rin sequence, and false it item is | >>> print("Hello” not in x) in list or in sequence. False Identity Operators: Sometimes, in Python programming a need to compare the memory address of two objects; this is made possible with the help of the identity ‘operator. Identity operators are used to check whether both operands are same oF not. Python provides ‘is’ and ‘is not’ operators which are called identity operators and both are used to check if two values are located on the same part of the memory. Two ‘variables that are equal does not imply that they are identical Operator | Deseription Example is Return tue, if the variables on either side | >>> a=3 of the operator point tothe same object | >>> b=3 and false otherwise. >>> prim(a is b) True isnot Retum false, ifthe variables on either [>>> a=3 side of the operator point to the same | >>> b=3 “object and true otherwise >>> print(a is not b) False ib) _ | Write pyibon program to display ontpot ike. ™ Page No: 4 | 20 [MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION ‘Autosemoe) asonec 27001. 213 Cetied) z 468 10 12.14 16 18 =i Correct oF any for in rang( 1.5): relevant Logic! for im range): any other penned") suitable br Program 4M © _| Explain four built-in list functions. ™ ‘Ans | [Se No._| Function Descripion Example T [ews Te returns the Tengih ofthe | >>> list lis 0.2.3.4.) nas ee >>> least) aes 3 [mandi Trretaras the ew thathas | >>> the maximum value ina} (1,2,3,4.5] lis 35> max(list) 5 3 [sami Calculates som ofallthe | >> >Hi elements of ls. 11,2,3,4,5] >>sumiistl) 1s [mnt Tretorns the Hem that fas | >>> TT the minimum value in alist. | (1,2, 3,4, 5] 33> mindist}) 1 3 iaseay Teonvers atupleinios | >>>Tail lis 11,2,3.4,5) >>> listist!) .2.3.4.5] | stappendinem) | Wadds the nemto he end | >>> list] of thelist. 11,2,3,4.5] >>> listappend(O) 55> ht 11.2.3.4,5.6) 7 | TistcountGuem) | Nreturns numberof times | >>> list the item occursin thes. | (1,2,3.4,5,6.3) >>> list count(3) Zz 3 [Tistenendtseq) | Wadds the clemenis ofthe | >>> Ist sequence atthe end ofthe} {1.2.3.4 1 list >> lis (A, B.C] >>> lisiLextendis2) >>> bt 11.2.3.4,5A, B,C] 9 | listpopttem=Tis= | W deletes and retums the | >>> ist 1) lastelement of thelist” | (1,2,7,3.4.5.3] >>> list. popO 3 Page No: § | 20 MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION Casement) ASONEC- 27001 2013 Certified) S55 al pope) 7 TO _[Tistremovetitem) | Trdeletes the given tem | >>> intl from the list. 11.2,3,4.51 >> list remove) >>> list! 1.2.4.5) T | Tstreverset) reverses the position | >>> list! (Gndex number) of the items | (1.2.3.4. 51 in thelist. >> list reversed) >>> list! (5.4.3.2. 1] 12 listson((fanc) | Itsors the elements inside | >>> list! the lst and uses compare | (1, 3.2.5.4] function if provided. >>> list sor >>> list! (1.2.3.4. 51 @) _ | Write python program using module, show how to write and use module by aM importing it. ‘Ans | For creating a module write following code and save it as pL-py Write module 2 ‘phy Mand Import 2 def adda, b): M “This function adds two numbers and return the result” result =a+b return result def sub(a, b): “This function subtract two numbers and return the result” result=a—b return result Import the definitions inside a module: import pI print(p1.add(10,20)) print(p1-sub(20,10)) Output: 30 10 x ‘Attempt any THREE of the following: 2M '@) _ | Describe various modes of file object? Explain any two in detail. aM Page No: 6 | 20 MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION ‘ctowemons) (ASONEC “27001 2013 Certified) "Ans | Like, C, C++, and Java, a file in Python programming can be opened in various modes depending upon the purpose. For that, the programmer needs to specify the mode ‘whether read ', write 'w’, or append a mode. Apart from this, two other modes exist, which specify to open the file in text mode or binary mode. 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 fil 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 Deseription T ‘Opens a file For reading only. The file pointer is placed at the beginning of the file. This is the default mode. ‘Opens a file for reading only in binary format. The file pointer is placed at the beginning of the file. This is the default mode. cs ‘Opens a file for both reading and writing. The file pointer placed at the beginning of the file. ‘Opens a file for both reading and writing in binary format. The file pointer placed at the beginning of the file. ‘Opens a file for writing only. Overwrites the file if the file exists. Ifthe file does not exist, creates a new file for writing. ‘Opens a file for writing only in binary format. Overwrites the file if the file exists. Ifthe file does not exist, creates a new file for writing. we ‘Opens a file for both writing and reading. Overwrites the existing file ifthe file exists. If the file does not exist, creates a new file for reading and writing. ‘Opens a file for both writing and reading in binary format. Overwrites the existing file ifthe file exists. If the file does not exist, creates a new file for reading and writing. ‘Opens a file for appending, The file pointer is at the end Of the file if the file exists. Listing of modes- 1 M and explain ant 23M Page No: 7 | 20 [MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION ‘utesowoas) (ASONBC -27001 2013 Cerda) That is, the file isin the append mode. Ifthe file does not exist, it creates a new file for writing 10 ‘ab | Opensa file for appending in binary format. The file pointer is atthe end of the file if the file exists. That is, the file isin the append mode. Ifthe file does not exist, it creates a new file for writing. Ti ‘a | Opensa file for both appending and reading. The file pointer is atthe end of the file ifthe file exists. The file opens in the append mode. Ifthe file does not creates a new file for reading and writing, [12 [abr | Opens a file for both appending and reading in binary | format. The file pointer is at the end of the fie if the file exists. The file opens in the append mode. Ifthe file does not exist, it creates a new file for reading and writing rey T ‘Opens in text mode (default) 1% | Opensin binary mode 5 + | Opens a file for updating (reading and writing), 1b) _ | Explain use of Pass and Ese keyword with for loops in python. aM “Ans | Pass Statement: It is used when a statement is required syntactically but we do not | Pass for 2M ‘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 mull 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 iin range(1.11): if i620, 4 check ifthe number is even. pass +# (No operation) else: print("Odd Numbers: °,) ‘Output: (Odd Numbers: 1 (Odd Numbers: 3 (Odd Numbers: 5 (Odd Numbers: 9 (Odd Numbers: 7 Page No: 8 | 20 aia MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION = (@SOMEC- 27001-2013 Certied) Tse Statements The else block just aller Tor/while s executed only when the Toop & NOT terminated by a break statement. The else keyword in a for loop specifies a block of code 10 bbe executed when the loop is finished: Example: for Fin range(1, 4): 4# Executed because no break in for nally Exit”) S) ‘T =(spam, Spam’, SPAM!’, 'SaPm') 4M print (T (2]) print (List (7)) Ans | Input Each Print ‘T=(spam’, ‘Spam’ ‘SPAM, ‘SaPm)) Statement! ouput for 1 M atement iat SPAM! 2p, B: ist 7 SaPm @ _ | Explain method overlonding and overriding in python. aM “Ans | Method Overloading: Method overloading i the ability to dsfine te method with he same | Method name but wih a differen numberof arguments and datatypes. Wit this ability one method | —Qverioading can perform different asks, depending on the number of arguments or the types of the | OV*S% arguments given. Method overloading is a concept in which a method in a class performs operations according to the parameters passed to it. Python does mot support method | and Overriding ‘overloading, that is, is ot 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 valve, a string ora double as shown in next example. ‘lass Demo: ‘def methodiself, a): print) ‘obj= Demot ) ‘obj method 50) ‘by. method Meenakshi’) ‘ob. nethod( 100.2) Output: 50 Meenakshi 100.2 Page No: 9 | 20 ey MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION ‘Unseen ‘asonec - 27001-2013 Certied) Tis 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. ‘Method Overriding: Overriding is the ability of a class to change the implementation ‘of a method provided by one ofits base class. Method overriding is thus a strict part of the inheritance mechanism. To override a method in the base class, we must define ‘anew method with same name and same parameters inthe derived class. Overriding is a very important part of OOP since it is the feature that makes inheritance exploit its full power. Through method overriding a class may “copy” another class, avoiding, duplicated code, and at the same time enhance or customize part of it. Example: For method overriding. class A: # parent class print (This is base class’) class BA). #derived class *Child/Derived class” def display(self): Drint ("This is derived class.) 0bj = BQ # instance of child obj,display)_# child calls overridden method Output: This is derived class. ‘Attempt any THREE of the following: 2M ‘) | Explain different functions or ways to remove key : value pair from aM Dictionary. “Ans | pop0: We can remove a particular item in a dictionary by using the method popQ.| _ 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) >>> squarespop(2) # remove a particular item 4 >>> squares (1:1, 3:9, 4 16) Popitem(: The method, popitem0 can be used to remove and return an arbitrary item (key, value) form the dictionary. Example: >>> squares=(: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 (@somec:- 27001-2013 Ceried) S55 print(equares,popitem()) remove an arbitrary Wem 5,25) >>> squares (1:1, 2:4, 3:9, 4: 16) heard: Example >>> squares (1: 1, 4: 16) >>> squares.clear() —# removes all items >>> squares 1) I the items can be removed at once using the elear() method 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 pantcul >>> squares (01,4: 16) 1b) _ | Explain Nampy package In deta. aM ‘Ans | NumPy is the fundamental package for scientific computing with Python. | _ Suitable NumPy stands for “Numerical Python”. It provides high-performance | explanation 4 ‘multidimensional array object, and tools for working with these arrays. M ‘+ Anamay isa table of elements (usually numbers), all ofthe 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, ‘+ InNumPy, dimensions are called axes. Each dimension of an array has alength Which is the total number of elements in that direction. ‘© The size of an array isthe 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 «one-dimensional array and (b) is a two-dimensional array. Page No: 11 | 20 MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION ‘otenomoes) (ASOMEC - 27001 = 2013 Certed) it o cones ‘* A one dimensional array has one axis indicated by Axis-0, That axis has five clements 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: python -m pip install numpy To use NumPy you need to import Numpy: import numpy as np # alias np ‘Using NumPy, a 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. ‘Explain seek () and tell () function for file pointer manipulation in aM python with example. seek0: In python programming, within file handling concept seekQ) function is used to For seek) shifichange the position of file object to required position. By file object we mean a cursor. | method: 2M ‘And it’s cursor, who decides from where data has tobe read or write ma file and for Tell() Syntax: method 2M Lseek(offset, fromwhere) ‘where offset represents how many bytes to move fromwhere, represents the position from where the bytes are moving. ‘open("demofile x", “r") fseek(4) sets Reference point to fourth index positon from the beginning print(f readline()) tell) tell) returns the current position ofthe file pointer from the beginning of the file. Syntax: filetell = open(“demofile.txt",") # points at the start Ee) Page No: 12 | 20 MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION ‘etenens) (ASOMEC - 27001 2013 Certiied) @)__] WAP to read contents of first.txt file and write same content in second.txt, aM file. “Ans | with open fistixt, P) as & # Open the First file for reading Comrect logic contents = f.read() ‘# Read the contents of the file progranvany suitable with open(second.cxt, Was _-# Open the second file for writing fawrite(contents) 1 Write the contents ofthe first ile tothe second fle |_PrOBTam 4M ‘Aitempt any TWO of the following: aM ‘a) _ | Explain any four set operations with example. oM “Ans | Set Operations: Each operation 1. Set Union: The union of two sets is the set ofall the elements of both the sets without “14M duplicates. You can use the ‘' operator to find the union ofa Python set >>> first_set= (1,2, 3) >>> second_set = (3.4, 5} >>> first_set.union(second_set) (1,2,3.4,5) >>> first_Set | second_set_ using the “| operator 11.2.3.4.5) 2. Set Intersection: The intersection of two sei the set of all he 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} 355 first setintersection(second_set) (4.5.6) >>> first set & second_sel # using the “&? operator (5.6) 3, Set Difference ‘The difference hetween two sets isthe set of all the elements in first set that are not present inthe second set. You would use the ‘~* operator to achieve ths in Python. >>> first set= {1,2,3,4, 5,6) ppp second set = (4,5, 6,7. 8.9) >>> first_set.difference(sevond_set) (1,2,3) >>> first set second set # using the *-* operator 11,2,3) >>> second set first_set 18.9.7) 4, Set Symmetric Difference: The symmetric difference between two sets isthe set of all the elements that are either inthe 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, >>> firs_set= {1,2,3, 4, 5,6) >>> second_set = (4, 5,6,7,8,9) >>> first_setsymmetric_difference(second_set) (1.2.3.7.8.9) Page No: 13 | 20 ge. MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION — (QSOABC - 27001 2013 Cert) S55 Tii_set*second_set_ using the” operator ‘The first characte ofthe variable must bean alphabet or underscore (_) * Allthecharsters except the fit character may bean alphabet of lower-cas(a-2} upper-case (A-Z), underscore or digit (0-9). + Identifier name must nt contain any white-space, or special character (, @. #.%.. &) + Meier name must not be similar to any Keyword defined in the language. 0 Identifier names are case sensitive for example my name, and MyName isnot the same, Eg: ae=.10,18 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 idemtfier names. All the Python keywords contain lowercase leters only. 3) Indentation: Python provides no braces to indicate blacks 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 inthe indentation is variable, but all statements within the block ‘must be indented the same amount. For example ~ if True: ora else: print “False” ‘Thus, in Python all the continuous lines indented with same number of spaces would form ablock. 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 lear 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 (1.2.3,7.8.9) })_ | Explain building blocks of python. om ‘Tas | 1) Python Identifiers: Variable name is known as identifier “Any 6 building To name an idea following are the rules: ‘blocks=6M Page No: 14 | 20 ‘Autononoe:) ey MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION = asonec 27001 2013 Cert) Structures to learn in Python are List (list), Dictionary (died, Tuple (tuple), and Set, Gen. 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=‘abed! ‘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=25 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 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 cenumerate‘d on to retum 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=Ca,q, blah] Dictionaries: Dictionaries in Python are a group of key-value pairs. Dictionaries are declared with curly braces and their entries can be accessed in two ways, a) with brackets, and b) with get. The example code shows how we can access items in a dictionary. dict = { ‘a’: Sally sells sea shells’, ‘b: down by the seashore’ } ‘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 tis a tuple of 1) The example below shows how to add ‘tuples, get a tuple from alist, and return information about it x=(@b) Page No: 15 | 20 [MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION ‘Autonomoes) (@SOMEC 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. ‘tt we can tum a list into a set bye] et(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. ©) | Write a program illustrating use of user defined package in python. oM “Ans | #student.py ‘Create package: class Student: 2m def __init_Gelf, student): 5 self.name = student|'name'} Importing self,gender = student! gender'] pecs in self year = student{'year] Logic: 2m def get_student_details(self): (Any return f"Name: {self.name}\nGender: {self.gender}\n Year: (self.year}" ‘Similar/Suitable other logic/program # faculty.py ‘can consider) class Faculty: def _init_(self, faculty): selfiname = faculty{'name'] self subject = facultyf'subject] def get_faculty_details(selt): 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 impor Faculty Page No: 16 | 20 “a MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION # creating dicts for student and faculty student_dict = ('name' : “ABC, ‘gender’: ‘Male’, ‘year’ ‘3 faculty_« ‘creating instances of the Student and Faculty classes student = Student(student_dict) faculty = Faculty(faculty_dict) 4 getting and printing the student and faculty details print(stadent get_student_details()) prin) Printfaculty.get faculty detailsO) Output = Name: ABC Gender: Male Year: 3 Name: XYZ Subject: Programming ‘Aitempt any TWO of the following: aM Write a program to create class student with Roll no. and Name and display its contents oM ‘Ans lass Student: def _ init__(self, name, rollno): selfname = name self,rolino = rollno def _str_(self) return f"{self.name ({selfrolino})" sl = Student("ABC*, 32) print(st) Output: ABC 32 Create Class: 3m Display Method: 3m b ‘Write program to Implement concept of inheritance In python. oM Page No: 17 | 20 a MAMARASITRA STATE BOARD OF TECHNICAL EDUCATION - sontc. Sar Corte ‘class Animal: @super cass 4# auribute and method of the parent class name = def eats: print("I can eat") 4# inherit from Animal class Dog(Animal): sub(2 M class +# new method in subclass def display(self): ‘# access name attribute of superclass using self print("My name is", self.name) # create an object of the subclass labrador = Dog) 4# access superclass attribute and method labrador.name = "Rohu" lnbrador.eat() # call subclass method labrador display() ‘Outpat: can eat My name is Rabu “Ray other suitable Program can consider Class creation: 2m Inherit one class to another: 2m Logie: 2m ° ist and explain any four built-in functions on set. oM Built-in Functions with Set add) discard copy) remove) clear) union() difference) imersection() discard) issubset() issuperset() opt) update() symmetric_ difference) Listing: 2m Explanation of any two function: 4m. (2Mcach) Page No: 18 | 20 ‘menemens) ry MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION = \ASOMEC - 27001-2013 Certified) add: ‘Adds an element to the set. If an element is already exist im the set, then it does not Add that element. Example: s= (ee, K's) # adding f into sets sadd() print(Set after updating, s) output: Set after updating: ('sf,’e..'g'. k') (g'e, KS) print(‘Set before discard: s) sdiscard() rint(\nSet after discard g:,s) Out, Set before discard: {'s''e'.'k’'s') Set after discard g:('s'', ') remove(): Removes the specified element from the set. Ifthe specified element not found, raise an error. Example: ‘ge. KS) print(Set before remove: s) sremove''e’) print(\nSet after remove e's) Output: Set before remove: {'s' Set after remave e: {' e.g) kg) dlear(: Removes all elements from the set Example: (ge. print(Set before clear, s) sclear() prini(\nSet after clear’ s) Output: Set before clear: ('g''k,'s\'e"} Set after clear: set) Page No: 19 | 20 ee MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (utenemens) _ ASONEC - 27001 2013 Certified) copy): Returns a shallow copy of the set Example: s= (2.8K 8) pescopy() prini “original set: prini("Copied set: Output: original set: ( Copied set: {'k, Union0):The set.union() method returns a new set with distinct elements from all the given sets. ‘ums? = {4, 5, 6,7, 7, 8) distinct_nums = nums!.union(nums2) print("The union of two sets is: ", distinct_nums) Output: The union of two sets (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: ums} = (1, 2,2, 3.4.5) 4, 5.6, 7.8, 8) ‘nums3 = nums|.difference(nums2) ‘nums4 = nums2.difference(nums!) rint(“nums! - nums2: ". nums3) ‘print(“nums2 - nus}: *, nums4) Output: ‘nums1 - nums2: (1, 2.3) ‘nums2 - numst: {8 6,7) Intersection():The set.intersection() method returns a new set with the elements that are common in the given sets. Page No: 20 | 20

You might also like