Professional Documents
Culture Documents
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.
function()
# y is accessible outside the function as well
Syntax :
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.
import random
r = random.random()
print(r)
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]
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.
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")
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)
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()
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.
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
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:
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
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
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:
def __str__(self):
return self.message
#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)
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)