0% found this document useful (0 votes)
5 views16 pages

Ques bankPYsol Ut2

The document provides a comprehensive overview of various programming concepts in Python, including functions, modules, packages, variable scopes, and data hiding. It also covers file types, exception handling, inheritance, and string operations, along with examples and explanations. Additionally, it discusses user-defined exceptions and the syntax for defining classes in Python.

Uploaded by

Apurva Chaudhari
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views16 pages

Ques bankPYsol Ut2

The document provides a comprehensive overview of various programming concepts in Python, including functions, modules, packages, variable scopes, and data hiding. It also covers file types, exception handling, inheritance, and string operations, along with examples and explanations. Additionally, it discusses user-defined exceptions and the syntax for defining classes in Python.

Uploaded by

Apurva Chaudhari
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

QUESTION ANSWER

NO.

Q1 Attempt any five

1. What is Function, module, Package?


Answer:

A function is a block of reusable code that performs a specific task. It allows


you to group related code together so you can execute it by calling the
function name. Functions help in improving code modularity, reusability,
and readability.Module

A module is a single file that contains Python definitions and statements,


like functions, classes, and variables. Modules help in organizing code by
grouping related functionality together. You can import and use a module in
other Python scripts.

Package

A package is a collection of related modules grouped together in a directory.


A package is essentially a directory that contains multiple module files and a
special __init__.py file (which can be empty). Packages allow for better
organization when you have many modules to work with.

2 Difference between local & global variable

featuere Local variable Global Variable

Scope Restricted to the function/block Accessible throughout


where it is defined the entire program (or
script

Lifetime Exists only during the Exists as long as the


execution of the function/block program runs

Access Can only be accessed inside the Can be accessed


function/block anywhere in the
program

Memory Allocated when the Allocated when the


function/block starts, program starts,
deallocated when it ends deallocated when the
program ends

3 1. Explain the concept of scope of Local Variable, Global Variable

the concepts of local variables and global variables refer to the scope of
variables in programming, which determines where and how these variables
can be accessed within the program. The scope essentially defines the region
of the code where a variable is accessible.

Local Variable:

● A local variable is a variable that is declared inside a function,


block, or method.
● It is only accessible within that specific function or block where it
was defined.
● Once the function or block of code finishes executing, the local
variable is destroyed, and its value is lost.
Example of Local Variable in Python:
● def example_function():

x = 10 # x is a local variable
print(x)

example_function()
# print(x) # This would cause an error because x is local to
example_function

n this example:

● x is a local variable because it is defined inside the


example_function() function.

● It can only be accessed and used within example_function(). Trying


to access it outside the function will result in an error.

Global Variable:

● A global variable is declared outside of all functions or methods,


typically at the top of the program.

● It can be accessed and modified from any function or block of code


within the program.

● Global variables persist throughout the program's execution and


retain their value until the program ends.

Example of Global Variable in Pytho


x = 20 # x is a global variable

def example_function():
print(x) # Accessing the global variable inside a function

example_function() # This will print 20


print(x) # This will also print 20 because x is global

4 Wirite notes on Numpy pakage


Ans
NumPy (Numerical Python) is one of the most essential libraries for
numerical computations in Python. It provides support for working with
arrays, matrices, and large datasets, offering a wide range of mathematical
functions. Here’s a breakdown of key concepts and functionalities provided
by NumPy:

Commonly Used NumPy Functions:

1. Mathematical Functions:

np.sum(), np.mean(), np.std(), np.median(): Functions for summation, mean,


standard deviation, and median.

np.dot(): Matrix multiplication (dot product).

np.linalg.inv(): Matrix inverse (linear algebra).

5 Explain concept of data Hiding with example.


Answer:

Data Hiding in Object-Oriented Programming (OOP)

Data hiding is an essential concept in Object-Oriented Programming (OOP)


that refers to restricting access to the internal state (data) of an object. This
helps in controlling how the data is accessed or modified, ensuring that the
internal workings of an object are protected from external manipulation. In
Python, data hiding is typically achieved through the use of private and
protected attributes and methods.

How Data Hiding Works in Python

In Python, data hiding is achieved through the following naming


conventions:

1. Protected variables: These are meant to be accessed by the class


and its subclasses. They are denoted by a single underscore (_).

2. Private variables: These are meant to be hidden from any external


access, including subclasses. They are denoted by a double
underscore (__).

class Person:
def __init__(self, name, age):
self.name = name # Public attribute
self.__age = age # Private attribute (data hiding)

# Public method to access private attribute


def get_age(self):
return self.__age

# Public method to modify private attribute (with validation)


def set_age(self, age):
if age >= 0:
self.__age = age
else:
print("Age cannot be negative.")

# Create an object of the Person class


person = Person("John", 30)

# Accessing public attribute


print("Name:", person.name) # Output: Name: John

# Accessing private attribute directly (will raise an error)


# print(person.__age) # Uncommenting this line will raise an AttributeError

# Using public method to get private attribute


print("Age:", person.get_age()) # Output: Age: 30

# Using public method to modify private attribute


person.set_age(35)
print("Updated Age:", person.get_age()) # Output: Updated Age: 35

# Trying to set an invalid age


person.set_age(-5) # Output: Age cannot be negative.

4 What is file? Enlist types of files in Python Programming


Answer:
In computing, a file is a collection of data or information that is stored on a
storage device, such as a hard drive, SSD, or cloud storage. In Python
programming, files are used to store and retrieve data in a structured way.
Files can store different types of information, such as text, numbers, images,
and other binary data.

In Python, files can be opened, read, written to, and closed using built-in
functions. File operations are crucial for tasks that involve saving data or
interacting with external information.

1 Text Files
2 Binary Files:

5. Difference between exception and error.


Answer:

feature Exception Error.

Definition An exception is an An error is a serious


event or condition that issue that typically
disrupts the normal flow results in the
of execution in a termination of the
program. It can be program. Errors
handled using specific usually cannot be
code to resolve the handled easily by
issue. the programmer.

Cause Exceptions occur due to Errors are often


predictable issues that caused by serious
can be handled (e.g., issues (e.g., syntax
dividing by zero, errors, memory
missing file) allocation issues)
that usually prevent
the program from
running at all.

Examples ZeroDivisionError, SyntaxError,


FileNotFoundError, MemoryError,
IndexError, ValueError, IndentationError,
etc. etc

Handling Exceptions can be Errors usually


caught and handled cannot be caught or
using try and except handled. They are
blocks in Python. critical problems,
and handling them
isn't typically
possible in the code
itself
6
Explain different modes of opening a file. (Write any 4 mode)
Ans:

. 'r' - Read Mode

● Description: Opens the file for reading. The file must exist,
otherwise, a FileNotFoundError is raised.

'w' - Write Mode

● Description: Opens the file for writing. If the file already exists, its
content is truncated (i.e., overwritten). If the file does not exist, a
new empty file is created.

'a' - Append Mode

● Description: Opens the file for appending. If the file does not exist,
it creates a new file. Data is added to the end of the file without
truncating the existing content.

'rb' - Read Binary Mode

● Description: Opens the file for reading in binary mode. The file is
opened in the same way as 'r', but it treats the file as binary rather
than text. It reads the file's raw bytes.

Q2 Attempt any three

1 1. Write a Python Program to find reverse of given number using user


defined function
Ans

# Define the function to reverse a number

def reverse_number(num):

# Initialize variable to store the reversed number

reversed_num = 0

# Loop to reverse the digits of the number

while num > 0:


digit = num % 10 # Extract the last digit

reversed_num = reversed_num * 10 + digit # Build the reversed


number

num = num // 10 # Remove the last digit from the number

return reversed_num

# Input: Take a number from the user

number = int(input("Enter a number: "))

# Call the function and print the reversed number

print("The reverse of the number is:", reverse_number(number))

2 Explain various string Operations that can be Performed using


operators in Python(CO4)
Answer:

Concatenation (+ Operator)

The + operator is used to concatenate (join) two or more strings into a single
string.

. Repetition (* Operator)

The * operator is used to repeat a string multiple times. You specify the
number of times you want to repeat the string.

Membership (in, not in Operators)

The in and not in operators are used to check whether a substring exists
within a string

.program:

str1 = "Hello"
str2 = "World"

str3 = "Python Programming"

str4 = "I love Python"

# 1. String Concatenation using + Operator

concat_result = str1 + " " + str2

print(f"Concatenation: {concat_result}") # Output: "Hello World"

# 2. String Repetition using * Operator

repeat_result = str1 * 3

print(f"Repetition: {repeat_result}") # Output: "HelloHelloHello"

# 3. Membership using in and not in Operators

is_in = "Python" in str3

is_not_in = "Java" not in str3

print(f"Membership (in): {'Python' in str3}") # Output: True

print(f"Membership (not in): {'Java' not in str3}") # Output: True

3 Explain class inheritance in python with example?


Ans:

Class Inheritance in Python

Inheritance is a mechanism in object-oriented programming (OOP) where


one class (child or subclass) inherits the attributes and methods of another
class (parent or superclass). This allows for code reuse and the creation of a
hierarchical class structure.

In Python, inheritance is implemented by defining a class that inherits from


another class. The child class can inherit all the properties and methods of
the parent class, and can also add its own properties or override inherited
methods.

# Parent class (base class)


class Animal:
def __init__(self, name):
self.name = name

def speak(self):
print(f"{self.name} makes a sound")

# Child class (derived class) inheriting from Animal


class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name) # Calling the constructor of the parent class
self.breed = breed

# Method overriding
def speak(self):
print(f"{self.name} barks")

# Create an instance of Dog


dog = Dog("Buddy", "Golden Retriever")

# Calling methods
dog.speak() # Output: Buddy barks

4 1. Explain the concept of method overriding in python


programming with example.
Ans:Method Overriding in Python

Method Overriding is an object-oriented programming (OOP) concept in


Python that allows a subclass to provide its specific implementation of a
method that is already defined in its parent class. In other words, the child
class can "override" or "replace" the functionality of a method inherited from
the parent class.

When a method in a child class has the same name, signature, and
parameters as a method in the parent class, it overrides the parent class
method. This is a key feature of polymorphism, where different classes can
have methods that behave differently, even if they have the same name.

# Parent Class
class Animal:
def sound(self):
print("Some generic animal sound")

# Child Class
class Dog(Animal):
def sound(self):
print("Woof! Woof!")
# Child Class
class Cat(Animal):
def sound(self):
print("Meow! Meow!")

# Creating instances of the classes


animal = Animal()
dog = Dog()
cat = Cat()

# Calling the sound method


animal.sound() # Output: Some generic animal sound
dog.sound() # Output: Woof! Woof!
cat.sound() # Output: Meow! Meow!

5 1. Explain exception handling with example using try,


(CO6)
except, raise keywords
Ans:

Exception Handling in Python

Exception Handling is a mechanism that allows a program to handle


runtime errors (exceptions) in a graceful way. Python provides several tools
for handling exceptions, including the try, except, and raise keywords.

● try block: The code that might raise an exception is placed inside
the try block.

● except block: If an exception occurs inside the try block, the code
inside the except block is executed. It handles the exception.

● raise keyword: Used to manually trigger an exception. It can also be


used to re-raise an exception that was caught in the except block.

def divide_numbers(num1, num2):


try:
# Attempt division
result = num1 / num2
except ZeroDivisionError as e:
# Handle division by zero error
print(f"Error: {e} - Cannot divide by zero.")
else:
# This block runs if no exception occurs
print(f"Result: {result}")
finally:
# This block will always execute, regardless of exception
print("Execution of the division operation is complete.\n")

def check_positive_number(number):
try:
if number < 0:
raise ValueError("Number must be positive!")
print(f"Input number {number} is valid.")
except ValueError as e:
print(f"Error: {e}")
finally:
print("Completed number validation.\n")

def get_integer_input():
try:
user_input = int(input("Please enter a number: "))
check_positive_number(user_input)
return user_input
except ValueError as e:
print(f"Error: {e} - Invalid input, please enter an integer.")
except Exception as e:
print(f"Unexpected error: {e}")
finally:
print("Input process is complete.\n")

# Main program flow


print("Example 1: Division Operation")
divide_numbers(10, 2) # Valid division
divide_numbers(10, 0) # Division by zero

print("Example 2: Positive Number Validation")


check_positive_number(10) # Valid positive number
check_positive_number(-5) # Invalid negative number

print("Example 3: Integer Input Validation")


get_integer_input() # User input handling

6 1. What is user defined Exception Give example


Ans

User-Defined Exception in Python

In Python, exceptions are typically predefined, such as ZeroDivisionError,


ValueError, etc. However, there may be cases where you want to define your
own exception to handle specific errors in your program. These are known as
user-defined exceptions.
A user-defined exception is a custom exception class that is created by the
user to handle specific types of errors or exceptional cases that are not
covered by built-in exceptions.

7 Write syntax of defining class in python

Syntax for Defining a Class in Python

In Python, a class is defined using the class keyword, followed by the name
of the class (usually in CamelCase), and a colon :. Inside the class, you
define methods and variables (also known as attributes) that belong to the
class.

Here's the basic syntax for defining a class in Python:

class ClassName:
# Constructor to initialize object attributes (optional)
def __init__(self, param1, param2):
# Initialize the instance variables
self.param1 = param1
self.param2 = param2
# Method of the class
def some_method(self):
# Code for the method
pass

# Another method
def another_method(self, value):
# Code for another method
pass

Explanation of the Components:

1. class ClassName:

○ The class keyword is used to define a new class.

○ ClassName is the name of the class, and it is typically


written in CamelCase (the first letter of each word
capitalized).

2. def __init__(self, param1, param2):

○ This is the constructor method (called when a new instance


of the class is created).

○ The self parameter refers to the instance of the class (it's a


convention and is used to access instance variables and
methods).

○ param1 and param2 are parameters passed when an object is


instantiated.

3. Instance Variables (self.param1, self.param2):

○ These are variables that belong to the instance of the class.


They are created inside the constructor (__init__) using the
self keyword.

4. Methods (e.g., some_method, another_method):

○ These are functions defined inside the class that describe the
behaviors of the class objects.

○ They have self as the first parameter to refer to the instance.

8 Write a python program that calculate area and circumference of


circle using inbuilt maths module
Ans
import math

# Function to calculate area and circumference of a circle


def calculate_circle_properties(radius):
# Area = π * radius^2
area = math.pi * radius ** 2

# Circumference = 2 * π * radius
circumference = 2 * math.pi * radius

return area, circumference

# Input: radius of the circle


radius = float(input("Enter the radius of the circle: "))

# Calculate area and circumference


area, circumference = calculate_circle_properties(radius)

# Output the results


print(f"Area of the circle: {area:.2f}")
print(f"Circumference of the circle: {circumference:.2f}")

9 Python program that will display calendar of month using calender module.
Ans:
import calendar

# Function to display the calendar of a specific month


def display_month_calendar(year, month):
# Display the calendar for the specified year and month
print(calendar.month(year, month))

# Input: year and month


year = int(input("Enter the year (e.g., 2025): "))
month = int(input("Enter the month (1-12): "))

# Call the function to display the calendar


display_month_calendar(year, month)

10 Explain any four built in function with example


Ans

1. len()

The len() function is used to return the number of items in an object, such as
a list, string, tuple, dictionary, etc. It returns the length of the object.

Syntax:
len(object)

2. type()

The type() function is used to get the type (or class) of an object. It returns
the type of the object passed to it.

Syntax:
type(object)

3. max()

The max() function returns the largest item from an iterable (like a list, tuple,
etc.) or the largest of two or more arguments.

Syntax:
max(iterable, *args, key=None)

4. sum()
The sum() function returns the sum of all elements in an iterable (e.g., a list
or tuple). Optionally, you can also provide a starting value to add to the sum.

Syntax:
sum(iterable, start=0)

These four built-in functions—len(), type(), max(), and sum()—are


commonly used for basic operations in Python. Here's a quick summary:

1. len(): Returns the length of an object (string, list, etc.).

2. type(): Returns the type of an object.

3. max(): Returns the largest item from an iterable or a set of


arguments.

4. sum(): Returns the sum of elements in an iterable, optionally with a


starting value.

# Example 1: Using len() to get the length of a string and list


string_example = "Hello, World!"
list_example = [10, 20, 30, 40, 50]

# Using len() to get the length of the string and the list
print("Length of the string:", len(string_example)) # Output: 13
print("Length of the list:", len(list_example)) # Output: 5

# Example 2: Using type() to check the type of various objects


integer_example = 42
string_example = "Python"
list_example = [1, 2, 3]

# Using type() to get the type of each object


print("\nType of integer_example:", type(integer_example)) # Output:
<class 'int'>
print("Type of string_example:", type(string_example)) # Output: <class
'str'>
print("Type of list_example:", type(list_example)) # Output: <class 'list'>

# Example 3: Using max() to get the maximum value from a list and multiple
arguments
numbers_list = [10, 20, 5, 30, 15]

# Using max() to get the maximum from a list


print("\nMaximum value in the list:", max(numbers_list)) # Output: 30
# Using max() with multiple arguments
print("Maximum value among 3, 5, 1, 9:", max(3, 5, 1, 9)) # Output: 9

# Example 4: Using sum() to get the sum of a list of numbers


numbers_list = [10, 20, 30, 40]

# Using sum() to get the sum of the numbers in the list


print("\nSum of the numbers in the list:", sum(numbers_list)) # Output: 100

# Using sum() with a starting value


print("Sum of the numbers in the list with a starting value of 50:",
sum(numbers_list, 50)) # Output: 150

You might also like