You are on page 1of 14

Chapter 4 : Python Functions, modules and Packages

1. Write a program to create a bar chart using Matplotlib.

import matplotlib.pyplot as plt


import numpy as np
obj=[“Sachin”,”Virat”,”Rahul”,”Dhoni”]
cen=[100,81,62,45]
y_pos=np.arange(len(obj))
plt.bar(y_pos,cen)
plt.sticks(y_pos,obj)
plt.ylabel(“Centuries”)
plt.title(“Player Stats”)
plt.show()

2. Define and explain Local variables and Global variables with suitable example.
Local Variables:
 Local variables are defined within a function or a block and can only be
accessed within that specific function or block.
 They are created when the function or block is called, and they are destroyed
when the function/block exits.
 Local variables cannot be accessed outside of the function or block in which
they are defined.

def my_function():
x = 10 # This is a local variable
print("Inside the function, x =", x)

my_function()
# Accessing x outside the function will result in an error
print("Outside the function, x =", x) # This will raise a NameError

Global Variables:
 Global variables are defined outside of any function or block and can be
accessed throughout the entire program.
 They are created when the program starts and can be used until the program
terminates.
 Global variables can be accessed and modified from any part of the program,
including inside functions.

y = 20 # This is a global variable


def function():
print("Inside the function, y =", y) # y is accessible inside the function

function()
# y is accessible outside the function as well

print("Outside the function, y =", y) # Here it works.


3. Write a short note on Function with default arguments.
 In Python, functions can have default arguments

Syntax :

def function_name(arg1, arg2=default_value):


# Function body
 When calling a function with default arguments, you can skip arguments that
have default values specified in the function definition.
 If an argument is not provided during the function call, its default value will be
used.
 When arguments are provided explicitly, and they will override the default
values.

def disp(name, msg="Hello"):


print(msg, name)

# Using default value for 'greeting'


greet("Prem") # Output: Hello Prem

# Overriding the default value


greet("Vikram", "Hi") # Output: Hi Vikram
 Note : Default arguments must be placed after non-default arguments in the
function definition. You cannot have a non-default argument after a default
argument in a function definition.
 Advantage : Default argument functions provides flexibility while calling
function.

4. What is kwargs in python? Explain its use.


 The term "kwargs" stands for "keyword arguments".
 It allows you to handle named arguments in a function.
 Keyword arguments gives us alternate way for function calling and passing
arguments.
 Keyword arguments allows us to pass parameters in any order irrespective of
their position in function definition.
 Example
def fun(para1,para2,para3):
print(“\n”,para1,para2,para3)

fun(10,20,30) #output 10 20 30
#calling fun by using parameter name(kwargs)
fun(para2=20,para3=30,para1=10) #ouput is same as above
5. How to create a module in Python? Explain its use with an example.
 In Python, a module is simply a file containing Python definitions, functions, and
statements.
 The file name becomes the module name with the .py extension.
 Modules allow you to organize code into reusable units, making it easier to manage
and maintain large projects.
 You can create your own modules and then import and use them in other Python
programs.
 Steps for creating modules,
1. Create a Python File: with a .py extension. This file will contain the
code for your module.
2. Write Your Code: Write the Python code that you want to include in
the module. Define functions, classes, variables, or any other code that
you want to make available in the module.
3. Save the File:Save the Python file with an appropriate name. The file
name will be used as the module name when importing.

# Save this file as math_op.py


def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
if y == 0:
raise ValueError("Cannot divide by zero!")
return x / y

# Save this file as main.py


import math_op as m
print(m.add(5, 3))
print(m.subtract(10, 4))
print(m.multiply(2, 6))
print(m.divide(10, 2))

6. Explain Python's built-in module: random


 Python's built-in module random provides functions for generating random
numbers and performing random selections.
 It's a versatile module commonly used in various applications, including
simulations, games, cryptography.
 Below are some of the key functions in the random module:
1. random(): This function returns a random float number in the range [0.0,
1.0).

import random
r = random.random()
print(r)

2. randrange(start, stop, step): This function returns a randomly selected


element from the range created by the start, stop, and step arguments. If
step is omitted, it defaults to 1.

import random
r = random.randrange(1, 10) # Random number between 1 and 9
print(r)
3. randint(a, b): This function returns a random int N such that a <= N <= b.

import random
r = random.randint(1, 10) # Random integer between 1 and 10 (inclusive)
print(r)
4. choice(seq) : This function returns a randomly selected element from the non-
empty sequence seq.

import random

m = [1, 2, 3, 4, 5]
r = random.choice(m)
print(r)
5. shuffle(seq): This function shuffles the elements of the sequence seq in place.
import random
m = [1, 2, 3, 4, 5]
random.shuffle(m)
print(m)
7. Explain the concept of Parameter passing to Python functions.
 Parameter passing in Python functions refers to the mechanism by which values are
passed to function at the time of calling.
 Parameter can be passed in two ways,
1. By Value
2. By Reference
 Passing by value: In Python, when you pass immutable objects (such as numbers,
strings, and tuples) to a function, the function receives a copy of the object. Any
modifications made to the parameter within the function do not affect the original
object.

def modify(x):
x = x + 10
num = 5
modify(num)
print(num) # Output – 5

 Passing by reference: When we pass mutable objects (such as lists, dictionaries, and
sets) to a function, the function receives a reference to the original object. Any
modifications made to the parameter within the function affect the original object.

def modify_list(lst):
lst.append(4)
print("Inside function:", lst) # output – [1, 2, 3, 4]

m = [1, 2, 3]
modify_list(m)
print(m) # output – [1, 2, 3, 4]

Chapter 5: Object Oriented Programming


1. State the use of the parameter "self" in Python class

In Python, the self parameter is used in class methods to refer to the instance of the
class itself.

When defining methods within a class, the first parameter of each method is typically
self.

This parameter allows methods to access and manipulate the instance variables and
other methods of the class.

Here's a brief explanation of the use of self:

1. Accessing instance variables: Inside a class method, self is used to access instance
variables. Instance variables are variables that are unique to each instance of the
class.
2. Calling other methods: self is also used to call other methods within the same
class. This allows methods to invoke other methods that belong to the same object.
3. Referencing the instance itself: By convention, self is used to refer to the instance
of the class itself. This makes the code more readable and helps distinguish instance
variables and methods from local variables and parameters.
class Car:
def __init__(self, make, model):
self.make = make
self.model = model

def display_info(self):
print("Car: “,self.make,” “, self.model")

def change_model(self, new_model):


self.model = new_model

# Creating an instance of the Car class


C = Car("Toyota", "Camry")

# Accessing instance variables using self


print(C.make) # Output: Toyota
print(C.model) # Output: Camry

# Calling a method using self


C.display_info() # Output: Car: Toyota Camry

# Modifying instance variables using self


C.change_model("Corolla")
print(C.model) # Output: Corolla

2. What is class and object? How to create a class and its object? Explain with an example.

Class is a user deifined data type that declares data members(Attributes) and
member functions(methods)

An object is an instance(variable) of a class.

# Defining a class named 'Person'


class Person:
# Constructor method
def __init__(self, name, age):
self.name = name
self.age = age

def display(self):
print("\nName : ”,self.name,”\nAge : “,self.age)

# Creating objects
P1 = Person("Prem",19)
P2 = Person("Vivek", 18)
# Accessing Members
P1.display()
P2.display()

4.Write a program to demonstrate the Constructor with default arguments.

A constructor is a special method used for initializing objects of a class at the


time of creation. It is called automatically when an object is created. Constructors are
defined using the __init__() method within a class.

A constructor with default arguments is a constructor that provides default values for
some or all of its parameters. If no values are provided during object creation, the
default values are used.

class Person:
# Constructor method
def __init__(self, name=”Prem Mhetre”, age=18):
self.name = name
self.age = age

def display(self):
print("\nName : ”,self.name,” Age : “,self.age)

# Creating objects
P1 = Person()
P2 = Person("Vivek", 19)

# Accessing Members
P1.display() # Output – Name : Prem Mhetre Age : 18
P2.display() # Output – Name : Vivek Age : 19
4. Write a program to demonstrate a parameterized constructor in base class and derived class.

A parameterized constructor is a constructor with parameters. It allows you to


initialize the object with specific values provided as arguments during object creation.
Following program demonstrates parameterized constructors in base and derived
class.
#Base Class Person
class Person:
# Constructor method in base class
def __init__(self, name, age):
self.name = name
self.age = age
class Test(Person):
# Constructor method in derived class
def __init__(self, name, age,tot):
Person.__init__(self,name,tot)
self.tot=tot
def display(self):
print("\nName : ”,self.name,” Age : “,self.age,” Total : “,self.tot)

# Creating object of Derived class


T = Test(“Vivek Patil”,18,659)
T.display() # Output – Name : Vive Patil Age : 18 Total : 659

5. Write a short note on method overriding in Python

 Method overriding is closely related to inheritance. When a subclass inherits a


method from its superclass, it has the option to override that method if necessary.
 The overriding method in the subclass must have the same name and parameters
(method signature) as the method being overridden in the superclass.
 Python uses dynamic dispatch to determine which version of an overridden method
to call based on the type of the object at runtime this called as dynamic method
dispatch.
 Within the overriding method, the super() function can be used to call the
overridden method from the superclass.

class Shape:
def area(self):
pass # Placeholder method

class Rectangle(Shape):
def __init__(self, length, width):
self.length = length
self.width = width

def area(self):
return self.length * self.width

R = Rectangle(5, 4)
print(R.area()) # Output: 20
6. Python does not allow method overloading, Then explain alternate ways of achieving the similar
effects of method overloading.

Python does not support method overloading in the traditional sense (i.e.,
having multiple methods with the same name but different parameters within the
same class), there are several alternative ways to achieve similar effects. These
include:

1. Using Default Parameter Values: You can define a method with default parameter
values to achieve a form of method overloading based on the number of arguments
passed.

class Calculator:
def add(self, x, y=0):
return x + y

# Example usage
C = Calculator()
print(C.add(5)) # Output: 5
print(C.add(5, 3)) # Output: 8
2**Using Variable Length Arguments (*args and kwargs): Python allows you to define
methods that accept a variable number of arguments, which can be used to simulate method
overloading based on different argument types or counts.
class Calculator:
def add(self, *args):
return sum(args)

# Example usage
C = Calculator()
print(C.add(5)) # Output: 5
print(C.add(5, 3)) # Output: 8
print(C.add(5, 3, 2)) # Output: 10
3.Using Function Overloading with Different Method Names: Although Python does not
support method overloading, you can define multiple methods with different names to
achieve similar effects based on the types or counts of arguments.

class Calculator:
def add(self, x,y):
return x+y

def add_two_numbers(self, x, y,z):


return x + y + z
# Example usage
C = Calculator()
print(C.add(5,1)) # Output: 6
print(C.add_two_numbers(5, 3, 2)) # Output: 10

7. Write a general syntax to Inherit one class into another class. Explain Multiple
Inheritance with example.
In Python, you can inherit one class into another using the following syntax

class SubClassName(SuperClassName):
# Child class methods and attributes
pass

Multiple Inheritance:

Multiple inheritance in Python refers to the capability of a class to inherit


attributes and methods from more than one parent class. This means that a subclass
can inherit from multiple parent classes.

Program for Multiple Inheritance,

Class ABC:
def dispABC(self):
print(“\nDisplay ABC”)
Class PQR:
def dispPQR(self):
print(“\nDisplay ABC”)
Class XYZ(ABC,PQR):
def dispXYZ(self):
ABC.dispABC()
PQR.dispPQR()
print(“\nDisplay XYZ”)
X=XYZ()
X.dispXYZ()
#Output –
Display ABC
Display PQR
Display XYZ
Chapter 6 – File Handling and Exception Handling

Explain seek() and tell() functions for File pointer manipulation.

seek() - Used to tell the position of the file cursor. Takes two parameters: the first is offset
and the second is whence(Refernce position) . By using seek() function, we can manipulate
the reading position of the file's content.
Syntax
f.seek(offset,whence)
Here value of whence can be ,
0 - to move file pointer from start of file
1 - to move file pointer from current position
2 - to move file pointer from end of file

Example
f.seek(0,0) – Moves read position to Satrt
f.seek(0,2) – Moves read position to end
f.seek(3,2) – 3 Bytes ahead from current position.

tell() - By using the tell() function, we can only get the position of the file cursor.
Syntax
f.tell()
Example
f.seek(0,2) # moves file pointer to end
sz=f.tell() # returns size of file in bytes

Q. 2 - Explain the following Python functions w.r.t. Directories


i) getcwd() ii) mkdir() iii) chdir() iv) listdir() v) exist()

1. getcwd(): This function returns the current working directory (CWD) as a string.

import os
current_directory = os.getcwd()
print("Current Directory:", current_directory)

2. mkdir(path):This function creates a new directory with the specified path. If the
directory already exists, it will raise a FileExistsError.

import os
os.mkdir("BVJNIOT") # Creates BVJNIOT directory at current path.

3. chdir(path): This function changes the current working directory to the one
specified in the path argument.
import os
os.chdir("c:\\Python")

4. listdir(path) : This function returns a list containing the names of the entries in the
directory specified by the path argument. If path is not specified, it defaults to the
current working directory.

import os
print("Files in current directory:", os.listdir())

5. exists(path) : This function checks whether the specified file or directory by path exists
or not. It returns True if the path exists, otherwise False.

import os
path = "/path/to/some/directory"
if os.exists(“demo.y”):
print("file exists!")
else:
print("File does not exist!")

Q. 3. How to create user-defined exceptions and raise it manually? Explain with complete
example.

In Python, you can create your own custom exceptions by defining a new class that
inherits from the built-in Exception class or any of its subclasses.
Here's a complete example:

# Define a custom exception class


class CustomError(Exception):
def __init__(self, message):
self.message = message

def __str__(self):
return self.message

# Function that raises the custom exception


def myFun(x):
if x < 0:
raise CustomError("Input value cannot be negative")

#main program
myFun(10) # no excepton raised in this call
myFun(-2) # exception gets raised in this call
4. What is use of read(),readline() and readlines() function in Python's File Handling.

1. read() : This function reads and returns the entire contents of the file as a single
string. If you specify a size argument, it reads that many characters from the file. If no
size argument is given, it reads the entire file.

f=open("file.txt", "r")
content = f.read()
print(content)

2. readline() : This function reads a single line from the file and returns it as a string.
Each time you call readline(), it reads the next line from the file. When the end of
the file is reached, readline() returns an empty string ('').

f=open("file.txt", "r")
line1 = file.readline()
line2 = file.readline()
print("Line 1:", line1)
print("Line 2:", line2)

3. readlines() : This function reads all the lines of the file and returns them as a list of
strings. Each string in the list corresponds to a line from the file, including the newline
character at the end of each line.

f=open("file.txt", "r")
list1= file.readlines()
print("Line s in file:", list1)

5.Write the general syntax of using try: except : finally block.

Syntax
try:
# Code block where exceptions may occur
# If no exception occurs, this block is executed without interruption
# You can have multiple statements in this block
except ExceptionType1:
# Code block to handle exceptions of type ExceptionType1
except ExceptionType2 as e:
# Code block to handle exceptions of type ExceptionType2
else:
# Code block that executes if no exceptions occur in the try block
# This block is optional
finally:
# Code block that always executes, regardless of whether an exception occurred or
#not. Useful for cleanup actions like closing files or releasing resources
# This block is optional
6. Write an individual program to demonstrate the occurrence of the following errors:
i) IOError ii) AttributeError iii) KeyError

1. IOError

try:
# Trying to open a file that does not exist
F=open("nonexistent_file.txt", "r")
content = file.read()
except IOError as e:
print("IOError occurred:", e)

2. AttributeError

try:
# Trying to access an attribute that does not exist
x = 10
print(x.length) # 'length' attribute does not exist for integers
except AttributeError as e:
print("AttributeError occurred:", e)

3. KeyError

try:
# Trying to access a key that does not exist in a dictionary
my_dict = {"key1": "value1", "key2": "value2"}
print(my_dict["key3"]) # 'key3’ does not exist in the dictionary
except KeyError as e:
print("KeyError occurred:", e)

You might also like