You are on page 1of 12

Program: CO

Course and Code: Programming with Python (22616)


Assignment No 4

1. Describe module in python.


2. Write the steps to create package in python.
3. State use of namespace in python.
4. Write the use of any four methods in math module.
5. Compare local and global variables with example.
6. Write a python program to calculate factorial of given number using
function.

Assignment No 5
1. How to declare a constructor method in python?
2. List different object oriented features supported by python.
3. Illustrate class inheritance in python with an example.
4. Illustrate the use of method overriding. Explain with example.
5. Create a class Employee with data members: name, department and salary.
Create suitable method for reading and printing employee information.

Assignment No 6
1. Write the purpose of try, except and finally block in python .
2. Write a program to create simple file and write “Hello World” in it.
3. Explain different text modes of opening a file.
4. Write a program to illustrate append Vs write mode.
5. Design a python program that will throw exception if the value entered by
user is less than 18 for election voting.

A R Sawant
Subject Incharge
Built-In functions(Mathematical):
• These are the functions which doesn’t require any external code
file/modules/ Library files.
• These are a part of the python core and are just built within the
python compiler hence there is no need of importing these
modules/libraries in our code.
min()- Returns smallest value among supplied arguments.
e.g. print(min(20,10,30))
o/p 10
max()- Returns largest value among supplied arguments.
e.g. print(max(20,10,30))
o/p 30

Built-In functions(Math Module):


• The second type of function requires some external files(modules)
in order to be used. The process of using these external files in our
code is called importing.
ceil()- Returns smallest integral value grater than the number.
e.g. import math
print(math.ceil(2.3))
o/p 3
floor()- Returns the greatest integral value smaller than the number.
e.g. import math
print(math.floor(2.3))
o/p 2
cos()- Returns the cosine of value passed as argument. The value passed
in this function should be in radians.
e.g. import math
print(math.cos(3))
o/p -0.9899924966004454
cosh()- Returns the hyberbolic cosine of x.
e.g. import math
print(math.cosh(3))
o/p 10.067661995777765
copysign()- Returns x with sign of y.
e.g. import math
print(math.copysign(10,-12))
o/p -10.0

All variables in a program may not be available at all areas in that


program. This relies on upon where you have announced a
variable.
There are two basic scopes of variables in python
Local variables:
• When we declare a variable inside a function, it becomes a local
variable.
• Its scope is limited only to that function where it is created. That
means the local variable is available only in that function but not
outside that function.
Global variables:
• When we declare a above a function it becomes a global variable.
• Such variables are available to all functions which are written after
it.
Example:
# Local variable in a function
def myfunction():
a=1 # local variable
a+=1
print(a)
# Call myfunction
myfunction()
print(a)
Output:
2
Traceback (most recent call last):
File "F:\2019-2020\PYTH prog\for_ex.py", line 9, in <module>
print(a)
NameError: name 'a' is not defined
Example:
# Global variable in a function
a=1 # global variable
def myfunction():
b=2 # local variable
print('a= ',a)
print('b= ',b)

# Call myfunction
myfunction()
print(a)
print(b)
Output:
a= 1
b= 2
1
Traceback (most recent call last):
File "F:\2019-2020\PYTH prog\for_ex.py", line 11, in <module>
print(b)
NameError: name 'b' is not defined
Modules:
• A module are primarily .py files that represents group of classes,
methods and functions.
• We have to group them depending on their relationship into
various modules and later use these modules in other programs. It
means, when a module is developed it can be reused in any
program that needs that module.
• In python there are several built-in modules. Just like these
modules we can create our own modules and use whenever we
need them.
• Once a module is created, any programmer in the project team can
use that module. Hence modules will make software development
easy and faster.

Namespace
• 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.
• Python interpreter understands what exact method or variable one
is trying to point to in the code, depending upon the namespace.
• Name means an unique identifier while space talks something
related to scope.
• Name might be any python method or variable and space depends
upon the location from where is trying to access a variable or a
method.
To create a package in Python, we need to follow these three simple
steps:
1. First, we create a directory and give it a package name, preferably
related to its operation.
2. Then we put the classes and the required functions in it.
3. Finally we create an __init__.py file inside the directory, to let
Python know that the directory is a package.

Inheritance in Python
Inheritance is the capability of one class to derive or inherit the
properties from some another class. The benefits of inheritance are:
1. It represents real-world relationships well.
2. It provides reusability of a code. We don’t have to write the same
code again and again. Also, it allows us to add more features to a
class without modifying it.
3. It is transitive in nature, which means that if class B inherits from
another class A, then all the subclasses of B would automatically
inherit from class A.

Different forms of Inheritance are:


1. Single inheritance: When a child class inherits from only one parent class, it is
called as single inheritance.

2. Multiple inheritance: When a child class inherits from multiple parent classes,
it is called as multiple inheritance.

3. Multilevel inheritance: When we have child and grand child relationship.

4. Hierarchical inheritance More than one derived classes are created from a
single base.
Example:-
class vehicle: #parent class
name="Maruti"
def display(self):
print("Name= ",self.name)
class category(vehicle): # derived class
price=400000
def disp_price(self):
print("price= ",self.price)
car1=category()
car1.display()
car1.disp_price()
Output:
Name= Maruti
price= 400000

Method Overriding in Python


Method overriding is an ability of any object-oriented programming language that
allows a subclass or child class to provide a specific implementation of a method
that is already provided by one of its super-classes or parent classes. When a
method in a subclass has the same name, same parameters or signature and same
return type(or sub-type) as a method in its super-class, then the method in the
subclass is said to override the method in the super-class.
The version of a method that is executed will be determined by the object that is
used to invoke it. If an object of a parent class is used to invoke the method, then
the version in the parent class will be executed, but if an object of the subclass is
used to invoke the method, then the version in the child class will be executed. In
other words, it is the type of the object being referred to (not the type of the
reference variable) that determines which version of an overridden method will be
executed.
Example-
# Python program to demonstrate
# method overriding

# Defining parent class


class Parent():

# Constructor
def __init__(self):
self.value = "Inside Parent"

# Parent's show method


def show(self):
print(self.value)

# Defining child class


class Child(Parent):

# Constructor
def __init__(self):
self.value = "Inside Child"

# Child's show method


def show(self):
print(self.value)

# Driver's code
obj1 = Parent()
obj2 = Child()

obj1.show()
obj2.show()

Output:
Inside Parent
Inside Child
• try Block- A set of statements that may cause error during runtime are to be
written in the try block.

• 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 statements written
in the try block.

• finally Block- This is the last block written while writing an exception
handler in the program which indicates the set of statements that are used to
clean up the resources used by the program.

# Python program to illustrate Append vs write mode

file1 = open("myfile.txt","w")

L = "This is Delhi \n,This is Paris \n,This is London \n"

file1.write(L)

file1.close()

# Append-adds at last

file1 = open("myfile.txt","a") #append mode

file1.write("Today \n")

file1.close()

file1 = open("myfile.txt","r")

print("Output of Readlines after appending")

print(file1.readlines())
print()

file1.close()

# Write-Overwrites

file1 = open("myfile.txt","w") #write mode

file1.write("Tomorrow \n")

file1.close()

file1 = open("myfile.txt","r")

print("Output of Readlines after writing")

print(file1.readlines())

print()

file1.close()

Modes & Description-

• r

Opens a file for reading only. The file pointer is placed at the beginning of the file.
This is the default mode.

• r+

Opens a file for both reading and writing. The file pointer placed at the beginning
of the file.

• w

Opens a file for writing only. Overwrites the file if the file exists. If the file does
not exist, creates a new file for writing.
• w+

Opens a 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.

• a

Opens a file for appending. 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.

• a+

Opens a 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.

# Program to write Hello World in a file

fo = open("README.txt","w+")

fo.write("Hello World\n")

fo = open("README.txt","r")

print(fo.read())

OOP FEATURES SUPPORTED BY PYTHON

• Class- Classes are defined by the user. The class provides the basic
structure for an object. It consists of data members and method members
that are used by the instances(object) of the class.

• Object- A unique instance of a data structure that is defined by its class.


An object comprises both data members and methods. Class itself does
nothing but real functionality is achieved through their objects.

• Data Member: A variable defined in either a class or an object; it holds the


data associated with the class or object.
• Instance variable: A variable that is defined in a method, its scope is only
within the object that defines it.

• Class variable: A variable that is defined in the class and can be used by all
the instance of that class.

• Instance: An object is an instance of a class.

• Method: They are functions that are defined in the definition of class and
are used by various instances of the class.

• Function Overloading: A function defined more than one time with


different behavior. (different arguments)

• Encapsulation: It is the process of binding together the methods and data


variables as a single entity i.e. class. It hides the data within the class and
makes it available only through the methods.

• Inheritance: The transfer of characteristics of a class to other classes that


are derived from it.

• Polymorphism: It allows one interface to be used for a set of actions. It


means same function name(but different signatures) being used for different
types.

• Data abstraction: It is the process of hiding the implementation details


and showing only functionality to the user.

You might also like