top of page
Writer's pictureHit Govani

Python MCA sem-1




Blanks:

In Python, a method that is used to handle exception cases is known as a try block.


The lambda function in Python allows you to define anonymous functions.


In Python, super is used to indicate that a method belongs to the parent class.


In Python, the special variable __name__ is used to check if a module is being run directly or imported as a module.


A Python function that returns a sequence of results rather than a single value is called a generator function.


In Python, the filter function is used to filter a list based on a condition provided by a lambda function.


The built-in Python function os.path.exists is used to check if a file exists in the file system.



QUE. & ANS :


2(A) Give a comparison between List, Tuple and Dictionaries in Python.

Feature

List

Tuple

Dictionary

Definition

Ordered collection of items.

Ordered, immutable collection of items.

Unordered collection of key-value pairs.

Mutability

Mutable (modifiable).

Immutable (cannot be modified).

Mutable (keys and values can be changed).

Syntax

Defined using square brackets [ ].

Defined using parentheses ( ).

Defined using curly braces { } with key-value pairs separated by :.

Examples

[1, 2, 3]

(1, 2, 3)

{'key1': 'value1', 'key2': 'value2'}

Order

Maintains insertion order.

Maintains insertion order (as of Python 3.7+).

Maintains insertion order (as of Python 3.7+).

Indexing

Accessible via index.

Accessible via index.

Accessible via keys (not indexable).

Duplicates

Allows duplicate values.

Allows duplicate values.

Keys must be unique, but values can be duplicates.

Use Cases

Used for collections of items that may need modifications.

Used for fixed collections of items.

Used for mappings between unique keys and values.

Performance

Faster than a dictionary for simple data.

Slightly faster than lists because they are immutable.

Slower for lookups than lists/tuples, but optimized for key-based access.

Functions

Supports append, extend, insert, remove, pop, and more.

Limited to operations like count, index.

Supports methods like keys(), values(), items(), update(), get().

Immutability

Items can be added, removed, or changed.

Once created, items cannot be altered.

Both keys and values can be changed, but keys must remain hashable.


2(B) Explain Slicing of strings in python using examples.

Slicing in Python refers to extracting a portion (substring) of a string using indexing. Strings are immutable, so slicing creates a new string.

Basic Syntax of Slicing:

string[start:end:step]

  • start: The starting index of the slice (inclusive). Defaults to 0 if omitted.

  • end: The ending index of the slice (exclusive). If omitted, slices up to the end of the string.

  • step: The interval or step between indices (defaults to 1).


OR


2(A) What is lambda function in Python? Explain lambda function with example. Explain filter(), map() and reduce() functions in brief.

Lambda Function in Python:

A lambda function in Python is a small anonymous function that can have any number of arguments, but can only have one expression. It is defined using the lambda keyword.

Syntax:

lambda arguments: expression

  • arguments: The input parameters (optional, can be none).

  • expression: A single expression that is evaluated and returned. This cannot contain multiple expressions or statements.

Example of Lambda Function:

# Regular function

def add(x, y):

return x + y

# Lambda function equivalent

add_lambda = lambda x, y: x + y

print(add(3, 5)) # Output: 8

print(add_lambda(3, 5)) # Output: 8


1. filter() Function:

The filter() function filters elements from an iterable based on a condition defined by a lambda function. It returns an iterator with only the elements for which the condition is True.

Syntax:

filter(function, iterable)

  • function: A function that tests each element in the iterable. It should return True or False.

  • iterable: The iterable (like a list or tuple) to be filtered.


2. map() Function:

The map() function applies a specified function to each item in an iterable and returns an iterator with the modified items.

Syntax:

map(function, iterable)

  • function: A function to apply to each element of the iterable.

  • iterable: The iterable to process.


3. reduce() Function:

The reduce() function, from the functools module, applies a rolling computation to sequential pairs of values in an iterable. It reduces the iterable to a single cumulative value.

Syntax:

from functools import reduce

reduce(function, iterable)

  • function: A function that takes two inputs and returns a value (e.g., addition, multiplication).

  • iterable: The iterable to be reduced.


2(B) Explain Dictionaries and associated methods.

  • get(): Retrieves a value safely.

  • keys(): Returns the dictionary keys.

  • values(): Returns the dictionary values.

  • items(): Returns key-value pairs.

  • update(): Adds or updates key-value pairs.

  • pop(): Removes a key-value pair and returns the value.

  • clear(): Clears all items in the dictionary.

  • copy(): Makes a shallow copy of the dictionary.

  • setdefault(): Gets a value or sets a default value.

  • fromkeys(): Creates a dictionary from keys with the same initial value.



3(A) What is function? How it differs from methods? Discuss use of default parameters in function using suitable example.

A function in Python is a block of reusable code that is designed to perform a specific task. Functions take input parameters, perform some operations, and return a result. Functions help in avoiding redundancy in code and make it more organized.

Syntax for Defining a Function:

def function_name(parameters):

# Function body

return result # Optional

  • def: The keyword used to define a function.

  • function_name: The name of the function.

  • parameters: Input to the function, these are optional.

  • return: A statement to return a result (optional).


The key difference between a function and a method lies in their association:

  1. Function:

    • A function is a standalone block of code that performs a task.

    • It does not belong to any object or class.

  2. Method:

    • A method is similar to a function, but it is associated with an object (or class). It operates on data that belongs to that object.

    • Methods are always called on instances (objects) of a class or on the class itself.


Use of Default Parameters in Functions:

Default parameters allow you to specify default values for parameters when defining a function. If the caller does not pass an argument for that parameter, the function uses the default value.

Syntax for Default Parameters:

def function_name(parameter1=default_value1, parameter2=default_value2):

# function body

If no argument is passed for a parameter, the default value will be used.


Example with Default Parameters:

def greet(name, age=25): # Default age is 25 if not specified

return f"Hello, {name}. You are {age} years old."

print(greet("Alice")) # Output: Hello, Alice. You are 25 years old.

print(greet("Bob", 30)) # Output: Hello, Bob. You are 30 years old.



3(B) What is Exception? Explain how to handle user defined exception in python ?

An exception in Python is an event or error that disrupts the normal flow of a program’s execution. When an error occurs, Python raises an exception, which typically results in the program stopping unless it is properly handled. Exceptions are caused by situations such as division by zero, incorrect data types, file not found, etc.

Types of Exceptions:

Common types of exceptions include:

  • ZeroDivisionError: Raised when dividing by zero.

  • ValueError: Raised when a function receives an argument of the correct type, but an inappropriate value.

  • FileNotFoundError: Raised when attempting to open a file that doesn’t exist.

  • TypeError: Raised when an operation or function is applied to an object of inappropriate type.

Python has a built-in set of exceptions, but you can define your own as well. Handling exceptions properly ensures that your program doesn't crash unexpectedly and can take corrective actions.


How to Handle User-Defined Exceptions in Python?

In Python, you can define your own exceptions using classes that inherit from the built-in Exception class. By creating custom exceptions, you can provide more meaningful error messages and handle unique situations in your programs.

Steps to Define and Handle a User-Defined Exception:

  1. Define the Exception:

    • Create a new class that inherits from Python’s Exception class (or a subclass of it).

  2. Raise the Exception:

    • Use the raise keyword to manually raise the exception.

  3. Handle the Exception:

    • Use try, except, and else blocks to catch and handle the user-defined exception.


OR


3(A) What is module? Why we need module? Discuss various ways to use module.

A module in Python is a file that contains Python code, which can define functions, classes, and variables, as well as include runnable code. Modules allow you to organize and reuse code across multiple programs. In essence, a module is a way of grouping related code together.

A Python module is simply a .py file that contains Python definitions and statements.

Why do We Need Modules?

Modules provide several benefits in programming:

  1. Code Reusability: Modules allow you to write code once and reuse it in multiple programs. This helps to avoid code duplication and makes the code more modular.

  2. Organization: Large programs can be broken down into smaller, more manageable modules. This improves code readability, maintainability, and ease of debugging.

  3. Separation of Concerns: Different parts of a program can be handled by different modules, ensuring that each module only handles a particular aspect of the problem domain (e.g., database operations, file handling, etc.).

  4. Namespace Management: Modules create their own namespace, meaning that functions and variables in a module won't interfere with those in other parts of the program.

Ways to Use a Module in Python:

  1. Import Entire Module:

    import module_name

  2. Import Specific Elements:

    from module_name import element_name

  3. Use Aliases:

    import module_name as alias

  4. Dynamic Importing:

    import importlib and importlib.import_module('module_name')s


3(B) What do you mean by Assertion? Explain with examexample.

Assertion in Python is a debugging aid that tests a condition as part of the code, raising an exception if the condition evaluates to False. It is primarily used during development and debugging to ensure that certain conditions hold true at specific points in the program. Assertions help catch bugs early by providing a way to automatically check for correctness.

In Python, assertions are implemented using the assert keyword.

Syntax:

assert condition, "Optional error message"

Example:

def check_age(age):

assert age > 0, "Age must be positive"

print(f"Age is {age}")


check_age(25) # Output: Age is 25

check_age(-5) # Raises AssertionError: Age must be positive


  • Assertions in Python are used to test if a condition in the code is true. If it's false, an AssertionError is raised.

  • They're used to catch bugs early by ensuring that certain conditions hold at specific points in the program.

  • The assert keyword is used with a condition and an optional error message to perform the check.

  • Assertions should primarily be used for debugging and development purposes, not for handling runtime errors or production-level exceptions.



4(A) Define : readline(), writeline() with example.

1. readline() Method:

The readline() method is used to read one line at a time from a file. It reads from the current file position and moves the pointer to the next line.

  • Syntax:

    file_object.readline(size=-1)

    • size: (Optional) The number of bytes to read. If not specified, the method will read one complete line.

  • The readline() method will return the next line from the file, including the newline character (\n), which signifies the end of a line in text files.

  • If the file pointer reaches the end of the file, readline() returns an empty string ("").


Example:

# Open a file in read mode

with open("example.txt", "r") as file:

line1 = file.readline() # Reads the first line

line2 = file.readline() # Reads the second line

print("First Line:", line1)

print("Second Line:", line2)


# Read another line (this would return an empty string if there's no more lines)

last_line = file.readline()

print("Last Line:", last_line) # Will print an empty string if it's at the end


2. writeline() Method:

The writeline() method is used to write a single line to a file. This method is generally used to write text to a file object in a line-by-line manner.

  • Syntax:

    file_object.writeline(string)

    • string: The string to be written to the file. It can also be a list or any iterable of strings.

  • When using writeline(), you have to manually handle the newlines (i.e., you need to add \n at the end of the string if required).

Example:

# Open a file in write mode

with open("output.txt", "w") as file:

file.writeline("Hello, this is the first line.\n")

file.writeline("Here comes the second line.\n")

file.writeline("Final line in the file.\n")


# Reading the written content

with open("output.txt", "r") as file:

print(file.read())


4(B) Write a program to read a text file in Python and print no. of lines and no. of unique words.

*Program:

def read_file_and_count(file_path):

# Initialize counters

line_count = 0

unique_words = set() # Set to hold unique words


# Open the file in read mode

with open(file_path, 'r') as file:

for line in file:

line_count += 1 # Count each line


# Split the line into words (you can customize the split logic if needed)

words = line.split()

for word in words:

# Convert to lowercase and remove punctuation to ensure unique words are counted properly

cleaned_word = ''.join(char.lower() for char in word if char.isalnum())

if cleaned_word: # Avoid counting empty strings

unique_words.add(cleaned_word)


# Print the results

print("Number of lines:", line_count)

print("Number of unique words:", len(unique_words))


# Provide the path to your text file

file_path = "sample.txt" # Replace with your file path

read_file_and_count(file_path)



OR


4(A) Discuss various file handling methods available in python with suitable code.

Opening a File:

  • The file path (including the filename).

  • The mode in which you want to open the file.

Modes:

  • r: Opens the file for reading (default).

  • w: Opens the file for writing, truncating the file first.

  • a: Opens the file for appending, writing at the end of the file.

  • x: Opens the file for exclusive creation, failing if the file already exists.

  • r+: Opens the file for both reading and writing.

  • w+: Opens the file for both reading and writing, truncating the file first.

  • a+: Opens the file for both reading and writing, appending at the end of the file.

  • b: Opens the file in binary mode (for images, videos, etc.).

Example:

# Open a file for reading

with open('my_file.txt', 'r') as file:

content = file.read()

print(content)


# Open a file for writing

with open('new_file.txt', 'w') as file:

file.write('Hello, World!')


# Open a file for appending

with open('my_file.txt', 'a') as file:

file.write('\nThis is a new line.')


Reading from a File:

  • read(): Reads the entire file content as a string.

  • readline(): Reads a single line from the file.

  • readlines(): Reads all lines into a list of strings.

Example:

with open('my_file.txt', 'r') as file:

# Read the entire file

content = file.read()

print(content)


# Read one line at a time

line = file.readline()

while line:

print(line.strip()) # Remove trailing newline

line = file.readline()


# Read all lines into a list

lines = file.readlines()

print(lines)


Writing to a File:

  • write(): Writes a string to the file.

  • writelines(): Writes a list of strings to the file.

Example:

with open('my_file.txt', 'w') as file:

file.write('This is a test.')


lines = ['Line 1\n', 'Line 2\n']

file.writelines(lines)


Closing a File:

It is important to close a file after you're done with it.This releases system resources and ensures data is written to disk.

  • close(): Closes the file object.

Example:

file = open('my_file.txt', 'r')

# ... do something with the file ...

file.close()



4(B) Write a program to read email ids from a file.

Program :

def read_emails_from_file(file_path): 
 try:
        # Open the file in read mode
        with open(file_path, 'r') as file:
            # Read each line in the file
            emails = file.readlines()
            # Iterate and print each email address
            print("List of Email IDs in the file:")

            for email in emails:
                print(email.strip())  # .strip() is used to remove leading/trailing whitespace or newline characters
    except FileNotFoundError:
        print(f"Error: The file at {file_path} does not exist.")
    except Exception as e:
        print(f"An error occurred: {str(e)}")

# Specify the file path
file_path = 'emails.txt'  # Replace with your file path
read_emails_from_file(file_path)

5(A) Write the general syntax of class declaration in Python. Explain declaration of class and its object with example.

In Python, a class is declared using the class keyword, followed by the class name and a colon. The body of the class contains the class methods and attributes (variables).

class ClassName:
# Constructor Method
    def __init__(self, parameter1, parameter2):
        self.parameter1 = parameter1
        self.parameter2 = parameter2
    # Other methods
    def some_method(self):
        # Code for method
        pass

Declaration of Class and its Object:

After the class is defined, an object is created by calling the class name like a function. Each object will have its own instance of the class's attributes.

Steps for Class Declaration and Object Creation:

  1. Declare a class.

  2. Define its constructor (__init__) to initialize its attributes.

  3. Define other methods within the class.

  4. Create an object by invoking the class.

  5. Access object attributes and methods using dot notation.


  • init() method: The constructor method (__init__) is used to initialize the object attributes when the object is created.

  • self: It represents the instance of the object and allows the object to refer to its own attributes and methods.

  • Object Creation: An object is created by calling the class and passing the required arguments.

  • Method Calling: Methods can be called on the object using the dot notation.



5(B) What is Inheritance? Explain multiple level inheritance with example.

Inheritance is a feature of object-oriented programming (OOP) that allows one class (child class) to inherit the properties and methods of another class (parent class). The purpose of inheritance is to promote code reusability and establish a relationship between classes.

  • Parent class (also called base class or superclass) is the class whose properties and methods are inherited.

  • Child class (also called derived class or subclass) is the class that inherits the properties and methods from the parent class.


What is Inheritance?

Inheritance is a feature of object-oriented programming (OOP) that allows one class (child class) to inherit the properties and methods of another class (parent class). The purpose of inheritance is to promote code reusability and establish a relationship between classes.

  • Parent class (also called base class or superclass) is the class whose properties and methods are inherited.

  • Child class (also called derived class or subclass) is the class that inherits the properties and methods from the parent class.

Advantages of Inheritance:

  1. Code Reusability: Inheritance allows you to reuse the code from the parent class, avoiding redundancy.

  2. Extensibility: A child class can extend or override the functionality of the parent class.

  3. Improved Code Organization: Organizing common functionalities in the parent class allows for cleaner and more manageable code.


Multiple Level Inheritance in Python:

In multiple level inheritance, a class (called the grandchild class) inherits from another class (the child class), which, in turn, inherits from a parent class. Thus, the inheritance forms a chain of relationships between three or more classes.

  • Parent class → Child class → Grandchild class

  • In this case, the grandchild class inherits methods and attributes from both the parent class and child class.

  • Multiple Level Inheritance is the type of inheritance where a subclass inherits from another subclass, forming a hierarchy. The hierarchy allows a class to inherit attributes and methods from its ancestor classes, promoting reusability and extensibility.

Syntax:

class Parent:

# Parent class constructor and methods

pass

class Child(Parent):

# Child class inherits from Parent

pass

class Grandchild(Child):

# Grandchild class inherits from Child (and indirectly from Parent)

pass


OR


5(A) Discuss Encapsulation and Information Hiding.

Encapsulation refers to the bundling of data (attributes) and methods (functions) that operate on the data into a single unit, or class. This means that the internal representation of an object is hidden from outside manipulation and access. Instead, access to the data is provided through methods that form an interface between the object and the outside world. In essence, encapsulation ensures that the object's data and operations are kept together, but access to the data can be controlled and managed.

Key Points of Encapsulation:

  • It allows you to define the object's interface for interacting with the object while hiding the implementation details.

  • Encapsulation protects the object's internal state from accidental changes.

  • It improves code modularity, maintainability, and reusability.

2. Information Hiding:

Information hiding is a design principle closely tied to encapsulation. It refers to the idea of hiding the internal details or implementation of a class from outside users (other classes, external systems, etc.). In other words, the internals of a class should not be exposed unnecessarily—only the essential functionalities that a class performs should be made accessible.

Information hiding encourages focusing on "what" an object does rather than "how" it does it.

  • Internal implementation (such as details of calculations, data structures, etc.) is hidden from users, making it easier to modify the class’s internal workings without affecting external code that uses the class.

  • This hides complexity, reduces dependencies, and prevents accidental misuse of the class's internal data.

Conclusion:

  • Encapsulation and Information Hiding are essential principles in OOP to create robust, flexible, and maintainable systems.

  • Encapsulation helps in bundling data and operations into a cohesive unit (class), while Information Hiding controls access to data and hides unnecessary details, focusing on essential interactions.



5(B) What is Class Variable and Instance Variable? Explain both and give one small example.

1. Class Variable:

Class variables are variables that are shared by all instances of the class. They are defined within the class construction and are usually used to store values that should be consistent for all instances of that class.

  • Class variables are created within the class but outside any methods, typically using the class definition itself.

  • Since class variables are shared by all objects of that class, they can be accessed by any object of that class.

  • Access: You can access class variables via the class name (ClassName.variable) or directly through an instance (objectName.variable).


2. Instance Variable:

Instance variables are variables that belong to a particular instance or object of a class. They are created inside the init() method (constructor) using the self keyword. Each instance of the class has its own copy of these variables.

  • Instance variables are initialized within the init() method and are specific to the object created.

  • Access: Instance variables are accessed using the self keyword inside class methods and by accessing the object itself (objectName.variable).


Differences Between Class Variables and Instance Variables:

Aspect

Class Variables

Instance Variables

Defined in

Inside the class but outside methods.

Inside methods, typically in the init method.

Access

Accessed via class name or through object instances.

Accessed through object instances only.

Scope

Shared by all instances of the class.

Specific to the instance of the class.

Modification

Modifying a class variable via any instance affects all instances.

Modifying an instance variable only affects that particular object.

Purpose

Used for values that should be the same across all instances (common).

Used for values that are unique to each instance (specific).









31 views0 comments

Recent Posts

See All

RDBMS MCA

Comentários

Avaliado com 0 de 5 estrelas.
Ainda sem avaliações

Adicione uma avaliação

Connect To Me 

  • YouTube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter
  • Pinterest
bottom of page