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)
24 views
Python Ut2
Uploaded by
penad40656
AI-enhanced title
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save python ut2 For Later
Download
Save
Save python ut2 For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
0 ratings
0% found this document useful (0 votes)
24 views
Python Ut2
Uploaded by
penad40656
AI-enhanced title
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save python ut2 For Later
Carousel Previous
Carousel Next
Save
Save python ut2 For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
Download now
Download
You are on page 1
/ 26
Search
Fullscreen
b) | Write any four methods of dictionary. aM ‘Ans 4M (any four, 1M each) Method Description ‘clear Removes allthe elements trom the lict={1"Viay2"Amar, 3 Santosh) dictionary >>> dict (1: Way. 2: "Amar, 3:'Santosh) >>> dictcear) >>> dict o items) | Retumsa ist containing the a tuple for | dict (7 Vay, 2 Amar, 3 Santosh] each key value par >>> for in dicutemsQ: print’) 0. ia") (2Amar) (3, ‘Santosh red) Retumsa ist containing the Sctionary’s | dict=(1-Vjay 2Amar 3°Santosh) keys 39> dicteys) ict, keys1. 2,3) 7) Remaves the element with the speciied | dict=(1Vjay2°Amar 2°Santosh) hey >>> pnintidict.popi2)) Amar popitem) | Removes the lst inserted Key-value pay | det=(1' Vijay 2/Amar,3°Santosh] >>> dictpopitem) 3, "Santosh)ey ‘What is focaland global variables? Explain with appropriaic example. ¢ Global variables: slobel veriables can be accessed throughout the progam body by all functions. © Local variables: local variables can be accessed only inside the fumction im which they are declared Concept Diagram: A global variable (x) can be reached and modified anywhere in the cade, local variable (2) cists only in Mock 2. Example: e-i0 global varisble g def tesa{)}: 20 #local variable | prnt("bocal varsibie=",f) 3 accessing global varishle print("Giabal waruible=".2) vs 5 MAHARASHTRA STATE BOARD OF TECH CAL EDUCATION ia hese == aT - Ta - Se Certified test) prist(" global variable="_g) output: focal varinblo= 21) Global vanabie= 10 global variabic= 10Illustrate with example method over loading. + Method overloading is the ability to define the method with the same name but with a different number of arguments and data types. * With this ability one method can perform different tasks, depending on the number of arguments or the types of the arguments given. * Method overloading is a concept in which a method in a class performs operations according to the parameters passed to it.def product(a, b): p=a*b print(p) def product(a, 5, c): p =a * b*¥c print(p) product(4, 5, 5)|Explain how try-catch block is used for exception handling in python, + In Python, exceptions can be handled using a try 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.1. try Block: A set of statements that may cause error during runtime are to be written in the try block. 2. except Block: It is written to display the execution details to the user when certain exception occurs in the program. The except block executed only when a certain type as exception occurs in the execution of statements written in the try block.try: # Some Code except: # Executed if error in the # try blockExample: For try-except clause/statement. n=10 m=0 try: wm except ZeroDivisionError: print("Divide by zero error") else: print (n/m) Output: Divide by zero errorA module allows you to logically organize your Python code. Grouping related code into a module makes the code easier to understand and use. A module is a Python object with arbitrarily named attributes that you can bind and reference. Simply, a module is a file consisting of Python code. A module can define functions, classes and variables, A module can also include runnable code,Example: For creating a module. Type the following code and save it as p1.py. def add(a, b): "This function adds two numbers and return the result” result = a+b return result def sub(a, b): "This function subtract two numbers ani result = a- Db return result \d return the result”print("division=" Addition= 3@ subtraction= -10 Multiplication= 200 division: rai| [2 a a MAH AIASHTICA STATE BOARD OF TECHNICAL EDUCATION ‘Auannavamciss) {ISO TEC - 27001. 2013 Certified) Create suitable method for reading and printing students details. class Student: def gerStuclentDetails(self) self.rolino=input(“Enter Roll Number < ") selliname = input("Enter Name =“) soll address ~impunl"Enter Address :") def printStudentDetuils( self phint( self rolleo.sel fname, selLaddress) SleStudemi() S1.getStudent Detailed) print("Student Detars ") Si. printSumdent 1 euils () Output: Enter Roll Number : 001 Enter Name : ABC Enter Address ; New York Student Details 001 ABC New York (Any suitable program can consider)Define class and object in python Class: A class is a user-defined blueprint or prototype from which objects are created. Classes provide a means of bundling data and functionality together. Object: An object is an instance of a class that has some attributes and behavior. Objects can be used to access the attributes of the class.list different modes of opening file in Python Monet for opening file: r: open an existing file for a read operation. ® w: open an existing file for a write operation. If the file already contains some data then it will be overridden. * a: open an existing file for append operation. It won't override existing data. * r+: To read and write data into the file. The previous data in the file will be overridden. ® w+: To write and read data. It will override existing data. ® a+: To append and read data from the file. It won't override existing data.Explain how to use user defined function in python with example © in Python, def keyword is used to declare user defined functions. ® The function name with parentheses (), which may or may not include parameters and arguments and a colon: ® An indented block of statements follows the function name and arguments which contains the body of the function. def function_name(): Statements Example: def fun(): print(“User defined function”) 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. ) def function_name( ‘1, astatements Example: def square{ x }: print(“Square=",x*x) # Driver code square(2) Output: Square= 4Write a program for importing module for addition and subtraction of two numbers calculation.py: def add(x,y): return (x+y) def sub(x,y): return (x-y) operation.py: import calculation print(calculation.add(1,2)) print(calculation.sub(4,2)) Output: 3 2Write a program iMustrating use of user defined package In python A package 6 a hierarchical file directory structure that defines a aingle Python application environment that conaists of modules and qubpackages and sub-subpackages, and so on. Packages a!iow for a hierarchical structuring of the module namespace Using dot notation. Creating a package is quite straightforward, since A makes wpe of the operating system's inherent hierarchical file structure. Consider the following arrangement By pws Bot se pyr Here. there 4 a directory named pkg that contains ho modules, mod]. py and mod?. py. The contents of the moduies are: modl.py def mi}: prieet[ “First mmodhale™) mod2.py def m2{}: print{Secend module")ithe peo dinectory reugien ins iecaten where it can te found, you can refer to the hw mmupghubes vert chet fotation|nks.=sdi,pag.ecct]) and import them with tho syinvtan: Syrian. import
].
_.|‘Syritan-2: from module name> import-crame|s)> thample >> from pig nod] import mi 2>> milf) Airst module BSS ‘Syntaw-d: from hare? import cname> ab calt_nae> xample ooo from pig. Mod. import Mm). at module oe3 module() first module: {Ou Cana Ort POtune wah TheLe LterRentT aa veel: fram
import
_| from
import
a3
ample => fren ping import emnetd ooo mod Limi) First moduWrite a program to open a file in write mode and append some content at the end of file filet. = open("myfile.txt", “w") L= [*This is Delhi \n", "This is Paris \n", “This is London") file weitetines(L) file1.close() # Append-adds at last # append mode filel = open("myfile.txt”, a") # writing newline character filet.write("\n") file. .write(“Today”) # without newline character file 1 .write("Tomorrow”) file = open("myfile.txt", "r") print("Output of Readlines after appending") print(filet.read()) pant() file1_close{)Output: Output of Readlines otter: appending This is Dethi This is Paris This is London T ‘TomorrowWrite a program to implement the concept of inheritance in python In inheritance objects of one class procure the 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. The mechanism of designing or constructing classes from other classes is called inheritance. The new class is called derived class or child class and the class from which this derived class has been inherited is the base class or parent class. In inheritance, the child class acquires the properties and can access all the data members and functions defined in the parent class. A child class can also provide its specific implementation to the functions of the parent class.Syntax: class A: # properties of class A class BA): # class B inheriting property of class A # more properties of class B Example 1: Inheritance without using constructor. class Vehicle: lparent class name="Maruti” def display(self}: print("Name= ",self.name) class Category(Vehicle): itderived class price=2000 def disp_price{self): print("Price=$"self.price) cari=Category() carldisplay()) eeeses—(i‘“‘“‘“‘iai‘eOverriding Overriding is the ability of a class to change the implementation of a method provided by one ¢ 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 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 1: For method overriding. deb product (a,5)% class A: # parent class praxb “parent Class" ideeD def display(self): ren ) print (‘This is base class.") def product La yb class B(A): #derived class "Child/Derived class" def display(self): print (‘This is derived class.") obj = 8() # instance of child obj.display() # child calls overridden method Output: This is derived class -‘Example: For data hiding. class Counter: _ _secretcount = @ #private variable ~deF Count (self): public method sIF._ _secretCount += 1 print ("count=",self._ _secretCount) # accessible in the same class cl Counter() c1.count() #invoke method ¢1.count() print ("Total count=",c1._ _secretCount) #cannot access private variable directly Output: count= 1 count= 2 AttibuteEnron: ‘Counter’ object has no attribute ‘_ _secretCount”
You might also like
Python Scripting
PDF
No ratings yet
Python Scripting
108 pages
Python: Finally
PDF
No ratings yet
Python: Finally
10 pages
Rapti Lab Report Python(Nagendra)
PDF
No ratings yet
Rapti Lab Report Python(Nagendra)
17 pages
rakesh assignment 3
PDF
No ratings yet
rakesh assignment 3
19 pages
PWP Assignment II
PDF
No ratings yet
PWP Assignment II
12 pages
Python - IA 3 Scheme
PDF
No ratings yet
Python - IA 3 Scheme
6 pages
Python , part -II
PDF
No ratings yet
Python , part -II
16 pages
unit 5 & 6(PWP)
PDF
No ratings yet
unit 5 & 6(PWP)
45 pages
python basics cs 12 pdf
PDF
No ratings yet
python basics cs 12 pdf
31 pages
Question Bank2 PWP
PDF
No ratings yet
Question Bank2 PWP
13 pages
Python Ml Theory
PDF
No ratings yet
Python Ml Theory
6 pages
Python
PDF
No ratings yet
Python
40 pages
Advance Python
PDF
No ratings yet
Advance Python
202 pages
AdvancedPython PartI PDF
PDF
No ratings yet
AdvancedPython PartI PDF
44 pages
Uday_codes_python_4
PDF
No ratings yet
Uday_codes_python_4
15 pages
santhoshkumar
PDF
No ratings yet
santhoshkumar
12 pages
lecture 3
PDF
No ratings yet
lecture 3
41 pages
Python Notes - Chapter 5 and 6
PDF
No ratings yet
Python Notes - Chapter 5 and 6
17 pages
Pwp answers
PDF
No ratings yet
Pwp answers
9 pages
Python Glossary - Codecademy
PDF
No ratings yet
Python Glossary - Codecademy
10 pages
PYTHON-FUNCTIONS.pptx
PDF
No ratings yet
PYTHON-FUNCTIONS.pptx
25 pages
PWP QB UT2
PDF
No ratings yet
PWP QB UT2
8 pages
PYTHON
PDF
No ratings yet
PYTHON
22 pages
Programming & Numerical Analysis: Kai-Feng Chen
PDF
No ratings yet
Programming & Numerical Analysis: Kai-Feng Chen
39 pages
phyton
PDF
No ratings yet
phyton
12 pages
Introduction To Python
PDF
No ratings yet
Introduction To Python
42 pages
Python Cheat Sheat
PDF
No ratings yet
Python Cheat Sheat
10 pages
PYTHON Map, Filter and Reduce
PDF
No ratings yet
PYTHON Map, Filter and Reduce
33 pages
python
PDF
No ratings yet
python
21 pages
Python in Easy Steps Presentation: Presented by Syed Hussain Razavi
PDF
No ratings yet
Python in Easy Steps Presentation: Presented by Syed Hussain Razavi
32 pages
ENGG1810 Recap
PDF
No ratings yet
ENGG1810 Recap
28 pages
Python Modul 4 - Sivanandha m s
PDF
No ratings yet
Python Modul 4 - Sivanandha m s
10 pages
Paython
PDF
No ratings yet
Paython
66 pages
Mech Python
PDF
No ratings yet
Mech Python
30 pages
Unit V Files, Modules, Packages: File Operation and File Functions
PDF
No ratings yet
Unit V Files, Modules, Packages: File Operation and File Functions
9 pages
Python Cheat Sheet
PDF
No ratings yet
Python Cheat Sheet
9 pages
Python Notes V2
PDF
No ratings yet
Python Notes V2
6 pages
By Karthik Prakash
PDF
No ratings yet
By Karthik Prakash
16 pages
Programs_Model Papers
PDF
No ratings yet
Programs_Model Papers
7 pages
Binary Search
PDF
No ratings yet
Binary Search
18 pages
Python Notes PDF
PDF
No ratings yet
Python Notes PDF
7 pages
Python Notes - 4
PDF
No ratings yet
Python Notes - 4
23 pages
Python Cheat Sheet
PDF
No ratings yet
Python Cheat Sheet
9 pages
Py 11
PDF
No ratings yet
Py 11
19 pages
1523_67_122_Module_4
PDF
No ratings yet
1523_67_122_Module_4
54 pages
Python 1707650972
PDF
No ratings yet
Python 1707650972
8 pages
PSPP Unit-5 PPT
PDF
No ratings yet
PSPP Unit-5 PPT
19 pages
Chapter 6
PDF
No ratings yet
Chapter 6
23 pages
Model Answer Paper
PDF
No ratings yet
Model Answer Paper
27 pages
py 3
PDF
No ratings yet
py 3
16 pages
Python Solved Sample Paper
PDF
No ratings yet
Python Solved Sample Paper
18 pages
Python the Essentials 1731972875
PDF
No ratings yet
Python the Essentials 1731972875
11 pages
Python Interview
PDF
No ratings yet
Python Interview
77 pages
Introduction To Python: 6th School On LHC Physics
PDF
No ratings yet
Introduction To Python: 6th School On LHC Physics
24 pages
Understanding The 10 Most Difficult Python Concepts - by Joanna - Geek Culture
PDF
No ratings yet
Understanding The 10 Most Difficult Python Concepts - by Joanna - Geek Culture
24 pages
PYTHON 505
PDF
No ratings yet
PYTHON 505
22 pages
Python: BY Kannan Moudgalya
PDF
No ratings yet
Python: BY Kannan Moudgalya
21 pages