100% found this document useful (1 vote)
7K views20 pages

Winter-23 Python Model Answer

All the best ??

Uploaded by

dishashelar196
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
100% found this document useful (1 vote)
7K views20 pages

Winter-23 Python Model Answer

All the best ??

Uploaded by

dishashelar196
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
  • Important Instructions to Examiners
  • Question 1: Attempt any FIVE of the following
  • Question 2: Attempt any THREE of the following
  • Question 3: Attempt any THREE of the following
  • Question 5: Attempt any TWO of the following
  • Question 6: Create packages of user defined package
  • Built-in Functions with Set
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autononoas) AASOMEC- 27001 - 2013 Certified) WINTER — 2023 EXAMINATION ‘Model Answer — Only for the Use of RAC Assessors Subject Name: Programming with Python, Subject Code: | 22616 Important Instructions to examiner 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 ctedit 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 & [Sub “Answer Marking No. |Q Scheme N. 1 ‘Attempt any FIVE of the following: 10M ‘a) | Enlist applications for python programming. 2M ‘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 seripting API. for | Meach 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 © semved wth Ot Scanner MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION 7 ‘Gammon = AASOMEC- 27001 - 2013 Certified) © Software Development *__Web Applications Write the use of elif keyword in python. 2M stands for ‘else IP 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 ladder is bypassed. If none of the conditions is true, then the final else statement will be executed. Conrect, explanation 2 M Describe the Role of indentation in python. 2M ‘Ans = Indentation refers to the spaces at the beginning of a code Tine. Generally, four whitespaces are used for indentation and is preferred over tabs. ‘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: if5>2: print(’Five is greater than two!") Correct Role 2 a) 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 + Data hiding is a software development technique specifically used in Object-Oriented Programming (OOP) to 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, Advantages of Data Hiding + Data hiding ensures exclusive data access to class members and protects object integrity by preventing unintended or intended changes. Data hiding is also known as information hiding. An objects attributes may or may not be visible outside the class definition Data hiding also minimizes system complexity for increase robustness by limiting interdependencies between software requirements ‘The objects within the class are disconnected from irrelevant data. Itheightens the security against hackers that are unable to access confidential data. It helps to prevent damage to volatile data by hiding it from the public. ‘A user outside from the organization cannot attain the access to the data. Within the organization/ system only specific users get the access. This allows better ‘operation. Any relevant Definition 1 M, any two Advantages 1 M °) State use of namespace in python. 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 2 M Page No: 2 | 20 © semved wth Ot Scanner MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autononoas) AASOMEC- 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 1) _ | State the use of read() and readline () functions in python file handling. 2M ‘Ans | 1. read({n}) Method: read@) 1 Mand The read method reads the entire contents of a file and returns it as a string, if number | readlineQ. of bytes are not given in the argument. If we execute read(3), we will get back the first three characters of the file. IM Example: for read( ) method. ‘ f=open("[Link]”,"t") meee print(fread(5)) — # read first 5 data print([Link]) _ # read rest of the file 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 fEopen("[Link]”,"t") print([Link]()) # read first line followed by\n print([Link](3)) print(freadline()) ) _ | Explain two ways to add objects / elements to list. 2M ‘Ans | Dappend method: The append() method adds an element to the end of a list, We can inser’ | 1 Method for 1 Jingle item in the list data time with the append) Many two methods) >>> list1=[10,20,30] >>> list [10, 20, 30) >>> list append(40)—#add element at the end of list, >>> list [10, 20, 30, 40} 2. extend() Method: The extend() method extends a list by appending items, We can add several items using extend() method. ‘ogram for extend() method, ={10, 20, 30, 40] >polistl [10, 20, 30, 40} >>> list] extend({60,70]) _ #add elements at the end of list >>> list] [10, 20, 30, 40, 60, 70] (example is not mandatory) Page No: 3 | 20 © semved wth Ot Scanner MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autononoas) AASOMEC- 27001 - 2013 Certified) [TT insert Method We can inser one single Rem ata desired location by using the method | SSCS insert() or insert multiple items by squeezing it into an empty slice ofa list. Example: Program for insert() method. >>> listI=[10, 20], SSolist] [10,20 >>> list] insert(1,30) >>> list! [10 30. 20) ‘Attempt any THREE of the following: 12M a) Explain membership and identity operators in Python. 4M Membership Operators: ‘The membership operators in Python are used to find the existence of a particular element in the sequence, and used only with sequences like string, tuple, list, dictionary etc. 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. ‘Operator | Description Example in True if value is found in list oF in sequence, and false it item is not _| >>> print(H’ in x) in list or in sequence True not in True if value is not found in list __| >>>x="Hello World” or in sequence, and false it item is | >>> primt("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 or 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] Description Example is Return true, ifthe variables on either side | >>> a=3 of the operator point to the same object | >>> b=3 and false otherwise, >>> prini(a is b) True isnot Return false, ithe variables on either | >>> a=” side of the operator point to the same | >>> be object and true otherwise. S5> print(a is not b) False Membership operator 2M and Identity operator 2M db) Write python program to display output like. 4M Page No: 4 | 20 © semved wth Ot Scanner (Autononoas) AASOMEC- 27001 - 2013 Certified) MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION z 468 10 12 14 16 18 ‘Ans [a=2 Correct or any for iin ange( 1,3) relevant Logic/ for jin range(): any other print(aens siliable a Program 4 M © | Explain four built-in list functions. aM Ans | [Sr No._| Function Description Example. T | lentlist Hse teen ofthe [>>> is] Ay 4 functions >>> lent 4M, 1M each 5 maxis) returns the fem that has | >>> TstT the maximum value ina | (1.2,3, 4,5} list, >>> max(list!) 5 3 | samt) Calealates sum oFallthe | >>>lisiT elements of li (1,2,3.4.5] >> >sumilist) 15 TP mindisty T returns the Wem that has [>>> TistT the minimum value ina lst. | (1.2.3, 4,5] >>> min(list1) 1 3p isseqy TWeonveris a ple intoa | >>>TistT list 1,2,3,4,5] >>> list(list]) [Link].5] @ | Tstappendiitem) | Wadds the emo the end | >>> istT of the list. (1,2.3,4.5] >>> lst-append6) S35 lst [[Link].5.6] 7__[listcounititem) | Rveturns number of times | >>> list] the item occurs in thelist. | [1,2, 3,4, 5,6, 3] >>> [Link](3) 3 | listentend(seq) | Wadd the elements of the | >>> list sequence at the end of the | (1.2.3, 4 list. 2 Cc] >>> list extend(list®) >>> list 11.2,3,4,5.'A. B.C] 9 [listpopdiemalis- | Tedeletes andretums the | >>> list] 1) last element ofthe list. 11,2,.7,3.4.5,3) >> listlpop) 3 Page No: 5 | 20 © semved wth Ot Scanner MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autononoas) AASOMEC- 27001 - 2013 Certified) >>> Hist pop@) 7 10 | listremovetiiem) | Iideletes the given item | >>> ist] from the list 11.2,3,4,5] >>> list remove(3) >>> list 1.2.45] TT | listreverse) Tireverses the position >>> list (index number) of the items | [1, 2, 3, 4, 5] in the lis. >>> list reverse() >>> list ([Link]. 1] 12 | listson({funcl) | Tisorts the elements inside | >>> list] the list and uses compare | (1, 3, 2,5, 4] function if provided >>> list sort) >>> list] 11.2,3.4.5] @) | Write python program using module, show how to write and use module by 4M importing ‘Ans | For creating a module write following code and save it Write module 2 apLpy M and 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 pl print(p1_add(10,20)) print([Link](20,10)) Output: 30 10 3 ‘Attempt any THREE of the following: 2M a) _ | Describe various modes of file object? Explain any two in detail. 4M Page No: 6 | 20 © semved wth Ot Scanner MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autononoas) a) ~ ASOMIEC - 27001 -2013 Certified) ‘Ans ] Like, C, Cr+, 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. 23M 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: ‘[Link]. | Mode | Description T r ‘Opens a file for reading only. The file pointer is placed at the beginning of the file, This is the default mode. 2 th | Opensa file for reading only in binary format. The file pointer is placed at the beginning of the file, This is the default mode. 3 + | Opens a file for both reading and writing. The file pointer placed at the beginning of the file 4 b+ | Opens a file for both reading and writing in binary format. The file pointer placed at the beginning of the file. 5 Ww _ | Opensa file for writing only. Overwrites the file if the file exists. Ifthe file does not exist, creates a new file for writing 6 wb | 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. 7 wi | Opens file for both writing and reading. Overwrites| the existing file if the file exists. If the file does not exist, creates a new file for reading and writing, 8 wb+ | Opens a file for both writing and reading in binary format. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing. 9 a ‘Opens a file for appending. The file pointer is at the end of the file if the file exists, Page No: 7 | 20 © semved wth Ot Scanner MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autononoas) AASOMEC- 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, 10 ab | Opensa file for appending in binary format. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing. iT ‘a+ | Opens file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing 2 ab+ | Opens a file for both appending and reading in binary format. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing, is t ‘Opens in text mode (default) 14 b (Opens in binary mode 15 + ‘Opens a file for updating (reading and writing). b) _ | Explain use of Pass and Else keyword with for loops in python. aM ‘Ans | Pass Statement: It is used when a statement is required syntactically but we do not | Pass for2M 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 pass Example: For pass statement for i in range( 1,11): if i%2==0: 4# check if the number is even es # (No operation) print("Odd Numbers: Output: Odd Numbers: 1 Odd Numbers: 3 Odd Numbers: 5 Odd Numbers: 9 Odd Numbers: 7 Page No: 8 | 20 © semved wth Ot Scanner MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autononoas) AASOMEC- 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: fori in range(1, 4): print) else: 4# Executed because no break in for print("Finally Exit”) Output: 1 2 3 Finally Exit © | T=Cspam, Spam’, SPAM, ‘SaPm') aM print (F (2)) print (1{-2]) print (1[2:)) print (List (1) ‘Ans | Input Each Print T= (spam’, ‘Spam’, ‘SPAM! 'SaPm’) Statement/ output for 1M [Python statement Output print (T (2) SPAM! print (TI-2) SPAM! print (T/2:)) [-SPAMY, 'SaPm'] print (list (T)) [-spam’, ‘Spam’, ‘SPAM, ‘SaPm') @__ | Explain method overloading and overriding in python. aM ‘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 | Qyerloading can perform different tasks, depending on the number of arguments or the types of the an 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 not support method | and Overriding overloading, that is, itis 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) Demo) obj method(50) ‘obj method(Meenakshi') obj method( 100.2) Output: 50 Meenakshi 100.2 Page No: 9 | 20 © semved wth Ot Scanner MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION 7 ‘Gammon = AASOMEC- 27001 - 2013 Certified) 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 Overt Werriding is the ability of a class to change the implementation of a method provided by one of its base class. Method overriding is thus a strict part of the inheritance mechanism. To override a method in the base class, we must define a new method with same name and same parameters in the 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 # parent class "Parent Class” def display(self) print (‘This is base class.’) class B(A): #derived class "Child/Derived class" def display(self): print (‘This is derived class.’) obj=BQ — #instance of child obj,display() _ # child calls overridden method Output: This is derived class. 4 ‘Attempt any THREE of the following: 2M a) _ | 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 popO. | _ Any two This method removes as item with the provided key and returns the value. functions, 2m Example: each 9, 4: 16} >>> squarespop(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 © semved wth Ot Scanner MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autononoas) AASOMEC- 27001 - 2013 Certified) S55 print(squares popitem() # remove an arbitrary item 65,25) >>> squares {1s 1, 2:4, 3:9, 4: 16) Clear(): All the items can be removed at once using the clear() method. Example: >>> squares (11, 4: 16) >>> [Link]()_ # removes all items >>> squares th Del(): We can also use the del keyword to remove individual items or the entire dictionary itself. Example: >>> squares {1s 1, 3:9, 4: 16} >>> del squares[3] _ # delete a particular item >>> squares {1 1, 4: 16) ) | Explain Numpy package in detail. 4M ‘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 © Anarrayis 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. + InNumPy, 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 arras Page No: 11 | 20 © semved wth Ot Scanner MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autononoas) AASOMEC- 27001 - 2013 Certified) Length © o-=woe Ask ® o 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-I. If Axis-0 in two ensional array has three elements, so its length it three and Axis-I 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, ional array has one axis indicated by Axis-0. That axis has five ©) _ | Explain seek () and tell () function for file pointer manipul: aM python with example. ‘Ans | seeK0: In python programming, within file handling concept seeKQ function is used to For seek0 shif’change 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 to be read or write in a file and for Tell) Syntax: method 2M Lscek(offset, fromwhere) where offset represents how many bytes to move fromwhere, represents the position from where the bytes are moving. Example: f= open(“demofiletxt""r") fscek(4) sets Reference point to fourth index position from the beginning print seadline() tell: tell returns the current position of the file pointer from the beginning of the file. Syntax: file tell Example: f= open("demofileaxt”, "r") # points atthe start print(f tell) Page No: 12 | 20 © semved wth Ot Scanner MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autononoas) a) ~ ASOMIEC - 27001 -2013 Certified) @)_ ] WAP to read contents of [Link] file and write same content in [Link] 4M file. ‘Ans | with open(firstixt, ¥) as f # Open the first file for reading Correct logic contents = [Link]() +# Read the contents of the file program/any . - suitable with open econ tt Wa f 4# Open the second file for writing program 4 M swrite(contents) +# Write the contents of the first file to the second file ‘Attempt any TWO of the followi 2M a) _ | Explain any four set operations with example. 6M ‘Ans_| Set Operations Each operation I. Set Union: The union of two sets is the set of all the elements of both the sets without “14M duplicates. You ean use the ‘|’ operator to find the union of a 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 (.2.3.4,5) 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 “8 operator (4,5, 6} 3. Set Difference The difference between two sets is the set ofall 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 ofall, 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.symmettic_difference(second_set) ([Link].8.9) Page No: 13 | 20 © semved wth Ot Scanner MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autononoas) AASOMEC- 27001 - 2013 Certified) S55 first_set "second set using the ™ operator ([Link],8.9) b)__ | Explain building blocks of python. 6M ‘Ans | 1) Python Identifiers: Variable name is known as Identifier. ‘Any 6 building To name an identifier following are the rules: The first character ofthe variable must be an alphabet or underscore (__) © Allthe characters except the first character may be an alphabet of lower-case(a-7), upper-case (A-Z), underscore or digit (0-9). ‘Identifier name must not contain any white-space, or special character (!, @, #, %, %, &°). © Identifier name must not be similar to any keyword defined in the language. 0 Identifier names are case sensitive for example my name, and MyName is not the b, Eg: abe=5,10,15 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. [and exec not assert finally or break for, pass class from) print ‘continue global raise def if return del import ry eli in while else is with except lambda yield 3) Indentation: Python provides no braces to indicate blocks of code for class and fu 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 “Truc” else: print "False" Thus, in Python all the continuous lines indented with same number of spaces would form a blod 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 earn 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 blocks=6M Page No: 14 | 20 © semved wth Ot Scanner a) MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autononoas) AASOMEC- 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="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 Boolean: Boolean variables in Python are either True or False. They will also return True for I and False for 0. The example shows how to assign either True or False to a variable in Python x=Twe 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=la,'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 = { ‘Sally sells sea shells, ‘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 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=(@b) Page No: 15 | 20 © semved wth Ot Scanner MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autononoas) AASOMEC- 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 xs[a 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. ©) | Write a program illustrating use of user defined package in python. oM ‘Ans | # [Link] ‘Create package: class Student: 2m def _init_(self, student); [Link] = student{‘name’] Importing self. gender = student{'gender'] packages: 2m self-year = student['year'] es def get_student_detaits(self: (Any return P’Name: ([Link]}\nGender: ([Link])\nYear: ([Link]}” Similar/Suitable other logic/program # faculty. py class Faculty: def _init__(self, faculty): [Link] = faculty['name’) self subject = faculty['subject’] def get_faculty_details(self) return f"Name: {self-name}\nSubject: {self-subject}" # [Link] # importing the Student and Faculty classes from respective files, from student import Student from faculty import Facult can consider) Page No: 16 | 20 © semved wth Ot Scanner MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autononoas) AASOMEC- 27001 - 2013 Certified) # creating dicts for student and faculty student_dict = {'name’ : ‘ABC’, 'gender': ‘Male, ‘year’: '3'} faculty_dict = (‘name': ‘XYZ’, ‘subject’: Programming’) # creating instances of the Student and Faculty classes student = Student(student_dict) faculty = Faculty(faculty_dict) # getting and printing the student and faculty details print(student.get_student_details()) print) print(faculty.get_faculty_details()) Output : Name: ABC Gender: Male Year: 3 Name: XYZ Subject: Programming 6 ‘Attempt any TWO of the following: 12M ) | Write a program to create class student with Roll no. and Name and oM display its contents ‘Ans_ | class Student Create Class: def __init_(self, name, rollno): 3m [Link] [Link] = rollno Display Method: 3m def __str_(self) return f"{[Link]}({[Link]})” s1 = Student("ABC", 32) print(s1) Output: ABC 32 ) _| Write program to implement concept of inheritance in python. oM Page No: 17 | 20 © semved wth Ot Scanner MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION oy (Astovomoas) S GSOMEC- 27001 2013 Certified) ‘Ans | class Animal: super class ‘Any other suitable # attribute and method of the parent class programcan: ame = consider def eat(self: print("I can eat") # inherit from Animal Clase creation: class Dog(Animal): — sub(2 M class 2m +# new method in subclass ene def display(self): el 4# access name attribute of superclass using self print(’My name is *, [Link]) Logic: 2m # create an object of the subclass labrador = Dog) ss superclass attribute and method [Link] = "Rohu" [Link]() # call subclass method labrador display() Output: Tan eat My name is Rohu ©) _ | List and explain any four built-in funetions on set. oM ‘Ans_| Built-in Functions with Set Listing: 2m add discard) Explanation of copy() any fro) remove() function: 4m — (2 Meach) differenceQ) intersection() discard issubset() issuperset() pop updated) symmetric_difference() Page No: 18 | 20 © semved wth Ot Scanner MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autononoas) AASOMEC- 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= (‘ge 'K,'s'} # adding f into set s [Link](f) print(Set after updating’, s) output: Set after updating: {'s','f, ‘eg ‘k'} diseard(): Removes the element from the set Example: s= (gh ek, 's} print(‘Set before discard: s) [Link]('s') print(\nSet after discard g:', s) 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: (ge k's) print(‘Set before removes’, s) sremovel'e’) print(\nSet after remove e:', s) Output: Set before remove: {'s','k’, 'e’, 'g'} Set after remove e: {'s', 'k’, 'g'} dlear(): Removes all elements from the set Example: print(‘Set before clear, s) sclear() print('\nSet after clear’, s) Output: Set before clear: {'g','k’,'s,'e') Set after clear: set() Page No: 19 | 20 © semved wth Ot Scanner MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autononoas) AASOMEC- 27001 - 2013 Certified) ‘copy: Returns a shallow copy of the set Example: (ge, k's) p=[Link]() print(“original set:",s) rint("Copied set:",p) Copied set: {'k’'s,'s','e'} Union():The [Link]() method returns a new set with distinct elements from all the given sets Example: nums! = (1, 2,2,3,4,5) nums2 = (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 is: (1,2, 3,4, 5,6, 7,8} Difference():The [Link]() method returns the new set with the unique elements that are not in the other set passed as a parameter. Example: numsl = {1, 2, 2, 3,4, 5) nums2 = {4, 5, 6,7, 8, 8} nums3 = nums|.difference(nums2) nums4 = [Link](nums!) print(“nums] - nums2: ", nums3) print(“nums2 - nums1: ", nums4) Output: ums] - nums: 1,2,3} nums2 - nums]: {8, 6,7} Intersection():The [Link]() method returns a new set with the elements that are common in the given sets. Example: x= “apple”, "banana", "cherry" y= {"google", "microsoft", "apple"} = [Link](y) print(2) Output: apple Page No: 20 | 20 © semved wth Ot Scanner

You might also like