Government Polytechnic
Ghaziabad
(College Code – 1101)
ASSIGNMENT
On
PYTHON
(COMPUTER PROGRAMMING USING PYTHON)
(Subject Code: -------------)
Branch / Year -PG Diploma in Web Designing / Ist Semester
Session: July-Dec 2025
Submitted To: Submitted By:
MR. Abhishek Sir Name: Som Nath
IT Department Enrollment No: E25110111300033
Q.1. Explain class in Python?
Ans. A class in Python is a blueprint for creating objects, which allows you to bundle data
(attributes) and functionality (methods) together into a single, reusable code structure.
Classes make it easier to organize, manage, and reuse code in larger programs by modeling
real-world entities and their behaviors.
Basic Syntax and Structure
To create a class, use the class keyword followed by the class name and a colon. Inside the
class body, you can define attributes and methods:
python
class Dog: # Class definition
sound = "bark" # Class attribute
This example defines a class called Dog with a single attribute, sound.
Creating Objects from Classes
Objects are specific instances of a class. You create them by calling the class name like a
function:
python
dog1 = Dog() # Creates an object (instance) of Dog
print(dog1.sound) # Outputs: bark
Each object can access the attributes and methods defined in its class.
The __init__ Method
To initialize object-specific attributes, classes often use a special method
called __init__ (constructor):
python
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
return f"{self.name} says woof!"
Here, __init__(self) sets up the values unique to each object, while bark is a method specific
to that object.
Why Use Classes?
Code organization: Bundle related data and functions together.
Code reusability: Create multiple objects from the same class.
Object-oriented programming: Model real-world things (like pets, cars, students) as
objects with specific attributes and behaviors.
Q.2. Explain various features of python.
Ans. Python has several key features that make it a popular and versatile programming
language suitable for many tasks:
Easy to Learn and Use: Python has a clear, readable syntax and uses indentation
instead of curly braces, which makes it beginner-friendly and easy to write code
quickly.
Interpreted Language: Python code is executed line-by-line by an interpreter, which
makes debugging easier and allows rapid development without explicit compilation.
Dynamically Typed: Variable types are determined at runtime, so you don't need to
declare them in advance. This flexibility speeds up coding but requires careful type
management.
Object-Oriented Programming (OOP): Python supports classes and objects,
enabling encapsulation, inheritance, polymorphism, and modular code organization.
Large Standard Library: Python includes extensive modules for file I/O, regular
expressions, web programming, databases, and more, reducing the need to write code
from scratch.
Cross-Platform: Python is platform-independent and runs on multiple operating
systems like Windows, macOS, and Linux without modification.
Multi-Paradigm: It supports procedural, object-oriented, and functional programming
styles, allowing developers to choose the best approach for their project.
Memory Management: Python automatically handles memory allocation and
garbage collection, so programmers don't need to manage memory manually.
Open Source: Python is free and open source, encouraging community contributions
and wide adoption.
Extensible and Embeddable: Python code can be extended with modules written in
languages like C/C++, and it can be embedded into larger applications as a scripting
interface.
GUI Support: Python supports graphical user interface creation through libraries like
Tkinter, PyQt, and Kivy.
These features make Python a powerful, flexible, and user-friendly language suitable for
beginners and experienced developers alike, with applications in web development, scientific
computing, artificial intelligence, automation, and more.
Q.3. Write notes on: (a) List (b) Sets
Ans. (a) List in Python:
A list is a built-in data structure used to store an ordered collection of items in Python.
Lists are created using square brackets [] containing comma-separated elements or by
using the list() constructor.
Lists are ordered, meaning the order of elements is preserved.
They are mutable, so you can change, add, or remove elements after list creation.
Lists can hold elements of different data types within the same list.
Duplicate values are allowed because each element has a unique position (index).
Elements in a list are indexed starting from 0, and negative indexing is supported for
accessing elements from the end.
Lists come with various useful methods, such as append() to add items, extend() to
concatenate lists, insert() to add an item at a specific index, remove() to delete an
item, reverse(), and sort() for organization.
Lists can also be nested to hold other lists as elements.
Example:
python
my_list = ['apple', 'banana', 'cherry']
my_list.append('date')
print(my_list) # ['apple', 'banana', 'cherry', 'date']
(b) Sets in Python:
A set is an unordered collection data type that stores unique elements.
Sets are created with curly braces {} or the set() constructor.
Since sets are unordered, they do not support indexing or slicing.
Sets automatically remove duplicate values, so only unique elements are stored.
Sets support mathematical set operations such as union, intersection, difference, and
symmetric difference.
Sets are mutable, so you can add or remove elements, but the elements themselves
must be immutable.
Being optimized for membership tests, sets are faster than lists for checking if an item
exists.
Example:
python
my_set = {1, 2, 3, 3}
print(my_set) # {1, 2, 3} - duplicates removed
my_set.add(4)
print(my_set) # {1, 2, 3, 4}
Together, lists and sets provide flexible ways to manage collections of data with different
ordering and uniqueness properties in Python.
Q.4. What is bitwise operators in Python? Explain.
Ans. Bitwise operators in Python are used to perform operations on individual bits of integer
values. These operators treat the operands as binary numbers and operate bit by bit, returning
results based on binary arithmetic. Bitwise operations are fundamental in low-level
programming and are useful for tasks such as masking, setting or clearing bits, and bit
manipulation.
Common Bitwise Operators in Python
& (Bitwise AND): Sets each bit to 1 if both bits at the same position in the operands
are 1.
Example: 5 & 3 (binary 0101 & 0011 = 0001) results in 1.
| (Bitwise OR): Sets each bit to 1 if at least one of the bits at that position is 1.
Example: 5 | 3 (binary 0101 | 0011 = 0111) results in 7.
^ (Bitwise XOR): Sets each bit to 1 only if exactly one of the bits is 1 (exclusive or).
Example: 5 ^ 3 (binary 0101 ^ 0011 = 0110) results in 6.
~ (Bitwise NOT): Flips all bits (one's complement), converting each 0 to 1 and each 1
to 0.
Example: ~5 results in -6 in two's complement representation.
<< (Left Shift): Shifts bits to the left by a specified number of positions, filling with
zeros on the right.
Example: 5 << 1 (0101 << 1 = 1010) results in 10.
>> (Right Shift): Shifts bits to the right by a specified number of positions, discarding
bits shifted out.
Example: 5 >> 1 (0101 >> 1 = 0010) results in 2.
Explanation
Each integer is represented in binary internally, and these operators manipulate those binary
digits directly. Python returns the results of bitwise operations as integers in decimal form.
Bitwise operators are particularly useful in scenarios involving flags, permissions, or low-
level data processing where direct control of bits is necessary.
Q.5. Explain various file operations in Python.
Ans. File operations in Python involve working with files to store and manipulate data.
Python provides a built-in open() function to open files, supporting different modes for
various operations such as reading, writing, appending, and creating files. Once opened, files
can be read from or written to using methods provided by the file object. Here is an overview
of common file operations:
1. Opening a File
The open() function is used to open a file, taking the file name and mode as arguments:
"r": Read mode (default). Opens the file for reading; error if the file does not exist.
"w": Write mode. Opens for writing, creates the file if it doesn't exist, or truncates the
file if it exists.
"a": Append mode. Opens the file for appending new content at the end; creates the
file if it doesn’t exist.
"x": Create mode. Creates the specified file; raises an error if the file exists.
"b": Binary mode appends to the above modes for binary file handling.
"t": Text mode (default).
Example:
python
f = open("example.txt", "r")
2. Reading a File
You can read file contents using:
read(): Reads the whole file as a single string.
readline(): Reads one line at a time.
readlines(): Reads all lines into a list.
Example:
python
content = f.read()
3. Writing to a File
Use write() or writelines() to write data to a file. If opened in write ("w") or append ("a")
mode, you can add new content.
Example:
python
with open("example.txt", "w") as f:
f.write("Hello, world!\n")
4. Closing a File
It is important to close a file after operations to free resources using close() or by using a
context manager (with) which automatically closes the file.
Example:
python
f.close()
5. Other File Operations
Renaming and deleting files: Using the os module with os.rename() and os.remove().
File existence and properties: Using os.path functions.
Copying and moving: Using shutil module functions.
Handling exceptions: Catching errors like FileNotFoundError during file operations
to ensure robustness.
Summary
Python file operations enable reading, writing, appending, creating, renaming, and deleting
files with simple, powerful functions. The use of file modes allows control over how files are
accessed, and the use of context managers ensures safe and efficient file handling in
applications.
Q.6. How dictionary created in Python.
Ans. A dictionary in Python is a collection of key-value pairs that are unordered, mutable,
and indexed by keys.
How to create a dictionary:
Using curly braces:
You define key-value pairs separated by colons, and pairs separated by commas.
Example:
python
my_dict = {"name": "Alice", "age": 30, "city": "New York"}
Using the dict() constructor:
You can create dictionaries from sequences of key-value pairs, keyword arguments, or
other dictionaries.
Examples:
python
# From a list of tuples
my_dict = dict([("apple", 2), ("banana", 3)])
# Using keyword arguments
my_dict = dict(apple=2, banana=3)
Creating an empty dictionary:
python
empty_dict = {}
# or
empty_dict = dict()
Additional points:
Keys must be immutable types like strings, numbers, or tuples.
Values can be of any data type.
Dictionaries are ordered in Python 3.7+, which means items retain insertion order.
You can access, add, modify, or delete items using their keys.
This flexibility makes dictionaries a powerful data structure for storing and managing data
efficiently.
Q.7. What is Greedy match in Python?
Ans. In Python regular expressions, a greedy match means the pattern tries to match as
much text as possible. Quantifiers like *, +, ?, and {m,n} are greedy by default, so they
match the longest possible string that fits the pattern.
For example, the regular expression <.*> applied to the string <a> b <c> will match the
entire string <a> b <c>, because .* grabs as many characters as it can between the first < and
the last >.
If you want to limit this behavior to match the smallest possible part (non-greedy or lazy
matching), you add a ? after the quantifier, like <.*?>, so it matches only <a>, and then <c>,
stopping at the first > it finds.
In summary, greedy matching tries to grab the largest substring possible, while non-greedy
matching grabs the smallest substring possible, controlled by adding a ? after quantifiers in
the regex pattern.
Q.8. Explain Exception handling in Python.
Ans. Exception handling in Python is a mechanism to gracefully manage errors or
unexpected events that occur during program execution. Instead of the program crashing
abruptly, exception handling allows the program to detect, catch, and respond to these errors,
enabling smoother execution and better user experience.
Key Concepts:
try block: Contains the code that may raise exceptions.
except block: Defines how to handle specific exceptions if they occur.
else block: (optional) Executes code if no exception occurs in the try block.
finally block: (optional) Executes code regardless of whether an exception was raised
or not, often used for cleanup.
Basic Syntax:
python
try:
# Code that may raise an exception
except SomeException:
# Code to handle the exception
else:
# Code to run if no exception occurs
finally:
# Code that runs no matter what
Example:
python
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
else:
print("Division successful.")
finally:
print("Execution completed.")
Output:
text
Cannot divide by zero!
Execution completed.
Additional Points:
You can catch multiple specific exceptions using multiple except blocks.
Catching a generic Exception can handle any exception but should be used carefully.
You can raise your own exceptions using the raise keyword.
Exception handling improves program robustness and maintainability by preventing
crashes and allowing controlled recovery.
Q.9. Explain map and filter in Python.
Ans. The map and filter functions in Python are higher-order functions that help process and
transform iterables in a concise and readable way.
Map in Python:
The map() function applies a specified function to each item in an iterable (like a list
or tuple) and returns an iterator (map object) with the results.
Syntax: map(function, iterable, ...)
You can pass multiple iterables to map if the function accepts multiple arguments.
Example:
python
def square(x):
return x * x
numbers = [1, 2, 3, 4]
squared_numbers = map(square, numbers)
print(list(squared_numbers)) # Output: [1, 4, 9, 16]
Useful to apply the same operation to all elements without writing explicit loops.
Filter in Python:
The filter() function constructs an iterator from elements of an iterable for which a
function returns true.
Syntax: filter(function, iterable)
The function passed should return a boolean, indicating whether to keep the item or
not.
Example:
python
def is_even(x):
return x % 2 == 0
numbers = [1, 2, 3, 4, 5]
even_numbers = filter(is_even, numbers)
print(list(even_numbers)) # Output: [2, 4]
It's handy to select items from a sequence based on conditions without a loop.
Both map and filter return iterators in Python 3, so you often convert them to lists or other
collections to use the results further. They promote cleaner, functional-style code and
simplify many data-processing tasks.
Q.10. Explain for loop in Python.
Ans. A for loop in Python is used to iterate over a sequence (such as a list, tuple, string, set,
or dictionary) and execute a block of code for each item in that sequence.
Basic Syntax:
python
for variable in sequence:
# code block to execute
variable is a temporary name that holds each item in the sequence during each
iteration.
sequence is the collection over which the loop iterates.
The indented code block under the for loop runs once per item in the sequence.
How it works:
The loop variable takes the first item in the sequence, the code block executes, then
the loop variable takes the next item, and so on until all items are processed.
No need to manually manage an index variable.
Example:
python
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output:
text
apple
banana
cherry
Additional points:
For loops can iterate over strings, processing each character.
You can use break to exit the loop early.
The for loop promotes readable and concise iteration without explicit index
management.
They work with any iterable, including custom objects that implement the iterator
protocol.
Q.11. Differentiate relational and Logical operator.
Ans. Relational operators and logical operators in Python are distinct in their purposes and
usage. Relational operators compare two values and return a Boolean result (True or False),
while logical operators combine or manipulate Boolean values. Both are essential for
decision-making in programming, but they work differently.
Relational Operators in Python
Relational operators are used to compare the values of two operands. The result of these
operations is always a Boolean value—either True or False.
Examples of relational operators include:
==: Equal to
!=: Not equal to
>: Greater than
<: Less than
>=: Greater than or equal to
<=: Less than or equal to
Example:
python
a=5
b=7
print(a > b) # False
print(a < b) # True
print(a == b) # False
Relational operators are typically used to compare numbers, strings, or other objects.
Logical Operators in Python
Logical operators are used to combine or invert Boolean expressions. They are most often
used with conditional statements or the results of relational operators.
Examples of logical operators include:
and: Returns True if both operands are True.
or: Returns True if at least one operand is True.
not: Returns True if the operand is False (inverts the Boolean value).
Example:
python
x = True
y = False
print(x and y) # False
print(x or y) # True
print(not y) # True
Logical operators help create complex conditions from simpler ones by combining multiple
Boolean values.
Each operator type serves a unique role in controlling program flow, with relational operators
making simple comparisons and logical operators enabling complex conditional logic.
Q.12. Explain if statement with example.
Ans. An if statement in Python is a control flow statement that executes a block of code only
when a specified condition evaluates to True. It allows the program to make decisions and
run different code depending on the situation.
How if Statement Works
The condition following the if keyword is a Boolean expression that evaluates to either True
or False. If the condition is True, the indented block of code under the if statement is
executed. If it's False, the block is skipped.
Syntax
python
if condition:
# code block to execute if condition is True
Example
python
number = 15
if number > 0:
print("The number is positive")
Output:
text
The number is positive
In this example, the condition number > 0 is True (since 15 is greater than 0), so the print
statement inside the if block is executed.
This basic structure helps control which parts of the program run based on dynamic
conditions.
Q.13. Explain various data types in Python
Ans. Python has various built-in data types that classify the kind of value a variable can
hold, enabling different operations depending on the type. These data types can be
categorized as follows:
Text Type
str: Represents text or string data, enclosed in quotes.
Example: "Hello, World!"
Numeric Types
int: Integer whole numbers, positive or negative.
Example: 10
float: Floating-point numbers for decimals.
Example: 3.14
complex: Complex numbers with real and imaginary parts.
Example: 2 + 3j
Sequence Types
list: Ordered, mutable sequences of elements enclosed in square brackets.
Example: [1, "apple", 3.14]
tuple: Ordered, immutable sequences, enclosed in parentheses.
Example: (1, "banana", 2.5)
range: Represents a sequence of numbers generated within a specified range.
Example: range(5)
Mapping Type
dict: Unordered collection of key-value pairs enclosed in curly braces.
Example: {"name": "John", "age": 30}
Set Types
set: Unordered collection of unique elements.
Example: {"apple", "banana", "cherry"}
frozenset: Immutable version of a set.
Boolean Type
bool: Represents truth values True or False.
Binary Types
bytes: Immutable sequence of bytes.
bytearray: Mutable byte sequence.
memoryview: Memory view object for binary data manipulation.
None Type
NoneType: A special type representing the absence of a value ('None').
Q.14. Define string and explain in Python.
Ans. A string in Python is a sequence of characters enclosed within single quotes (') or
double quotes ("). It is used to represent and store textual data. Python strings are immutable,
meaning once a string is created, it cannot be changed. However, new strings can be created
through operations like concatenation or slicing.
Key Characteristics of Python Strings
Enclosed in single quotes, double quotes, or triple quotes (for multi-line strings).
Immutable: Their content cannot be altered after creation.
Supports indexing and slicing.
Can contain letters, numbers, symbols, and spaces.
No separate character type; a single character is a string of length 1.
Example
python
my_string = "Hello, world!"
print(my_string) # Output: Hello, world!
print(type(my_string)) # Output: <class 'str'>
Multi-line String Example
python
multi_line = """This is a
multi-line string."""
print(multi_line)
Output:
text
This is a
multi-line string.
Q.15. Explain difference between break and continue.
Ans. In Python, break and continue are control statements used inside loops to alter their
flow, but they serve different purposes.
break
Terminates the loop entirely when encountered.
Causes the program to exit from the loop and continue with the first statement after the
loop.
Often used to stop a loop early when a certain condition is met.
Example:
python
for i in range(5):
if i == 3:
break
print(i)
Output:
text
0
1
2
In this example, when i becomes 3, the break statement terminates the loop.
continue
Skips the current iteration and proceeds with the next one.
Does not exit the loop; instead, it jumps to the beginning of the next iteration.
Commonly used to skip over specific conditions within a loop.
Example:
python
for i in range(5):
if i == 3:
continue
print(i)
Output:
text
0
1
2
4
Q.16. What are the python reserved words, and why are they important?
Ans. Python reserved words, also known as keywords, are special words that are part of the
Python language syntax and have predefined meanings. These words are reserved
exclusively by the language and cannot be used as variable names, function names, or any
other identifiers in your code because they perform specific functions that control Python
program behavior.
List of Python Reserved Words
Python has 35 reserved keywords, including:
False, None, True, and, as, assert, async, await, break, class, continue, def, del, elif, else, exc
ept, finally, for, from, global, if, import, in, is, lambda, nonlocal, not, or, pass, raise, return, tr
y, while, with, yield
These keywords are case-sensitive and must be used exactly as shown.
Importance of Reserved Words
They form the fundamental building blocks of Python syntax and control flow, such as
conditional statements (if, else, elif), loops (for, while), function and class definitions
(def, class), error handling (try, except, finally), and logical operations (and, or, not).
Using these words consistently ensures the interpreter can correctly parse and execute
code as intended.
Prevent naming conflicts by disallowing their use as identifiers, which keeps code
clear, correct, and unambiguous for both humans and the interpreter.
Reserved words act like traffic signs that direct the structure and flow of your
programs. Misusing or trying to redefine these words results in syntax errors and
breaks your program.
In summary, Python reserved words are vital for defining the grammar and semantics of the
language. They guarantee clarity, consistency, and correctness in Python programs by
reserving specific words exclusively for language use, preventing their misuse as identifiers.
Q.17. Explain the concept of dynamic typing in Python. How does it differ from static
typing in other programming languages?
Ans. Dynamic typing in Python means that variable types are determined at runtime based
on the value assigned to the variable, rather than at compile time. In Python, a variable can
hold data of any type and the type can change over its lifetime. This makes Python flexible
and easy to use because you don't have to declare variable types explicitly. For example, a
variable initially holding an integer can later be reassigned to hold a string or a list, and
Python will dynamically manage the type and memory accordingly. Type checking is done
during execution, and type errors (like adding an integer to a string) are caught at runtime
rather than before the program runs.
In contrast, static typing requires variable types to be declared explicitly before compilation,
and these types cannot change. Languages like C, C++, and Java enforce type checking at
compile time, preventing the program from compiling if there are type mismatches. This
leads to more rigid but type-safe code, as errors are caught early. Static typing directs fixed
memory allocation based on the declared types and typically prevents variables from
changing type once declared.
Dynamic typing offers ease of use and faster prototyping, while static typing offers early
error detection and optimized performance.
In summary, Python’s dynamic typing means variable types are resolved and can change at
runtime, lending flexibility, whereas static typing requires compile-time type declarations
that remain fixed, ensuring type safety before the program runs.
Q.18. Explain how to use comments in Python. Provide examples of both single-line and
multiline comments.
Ans. In Python, comments are used to explain code, make it more readable, or temporarily
disable code during testing. They are ignored by the Python interpreter and do not affect
program execution.
Single-line comments
Single-line comments start with the hash symbol #. Everything following # on that line is
treated as a comment.
Examples:
python
# This is a comment explaining the next line
print("Hello, World!") # This comment is after a line of code
Multi-line comments
Python does not have a dedicated multi-line comment syntax like some other languages, but
there are common ways to write multi-line comments:
1. Using multiple # symbols:
Place a # at the beginning of each line you want to comment out.
python
# This is a multi-line comment
# describing multiple lines
# using multiple hash symbols
2. Using triple-quoted strings:
Triple quotes (""" or ''') can be used to create multi-line strings that are ignored by
Python if they are not assigned to a variable. These are often used for docstrings but
can serve as comments.
Examples:
python
"""This is a multi-line comment
using triple double-quotes."""
'''Another multi-line comment
using triple single-quotes.'''
Remember, this second method is technically a string literal that is ignored during execution
unless used as a docstring or assigned to a variable. Its primary use in comments is a
convention for multi-line explanations or larger comment blocks.
Use case reminders
Use single # for brief explanations or notes.
Use multiple # lines or triple quotes for longer explanations or temporarily disabling
code blocks.
Avoid overusing multi-line string comments for documentation purposes; reserve
docstrings for documenting modules, classes, and functions.
This approach helps keep your code clear, maintainable, and well-documented.
Q.19. What are lists and tuples in Python, and what are the difference between list and
tuples?
Ans. Lists and tuples in Python are both used to store collections of items, but they have
important differences primarily related to mutability.
What is a List?
A list is a mutable collection, meaning you can modify it after creation by adding,
removing, or changing elements.
Lists are defined using square brackets [].
Lists support many built-in methods such as append(), remove(), pop(), and more.
Example:
python
my_list = [1, 2, 3, 'apple']
my_list.append(4) # List becomes [1, 2, 3, 'apple', 4]
my_list[1] = 'banana' # List becomes [1, 'banana', 3, 'apple', 4]
What is a Tuple?
A tuple is an immutable collection, meaning once it is created, it cannot be modified
(no adding, removing, or changing elements).
Tuples are defined using parentheses ().
Tuples have fewer built-in methods compared to lists (count() and index() mainly).
Example:
python
my_tuple = (1, 2, 3, 'apple')
# Attempting to change an element results in an error:
# my_tuple[1] = 'banana' # Raises TypeError
Key Differences Between Lists and Tuples
Feature List Tuple
Mutability Mutable (can be changed) Immutable (cannot be changed)
Syntax Defined with square Defined with parentheses ()
brackets []
Methods Many built-in methods (e.g., Limited methods (e.g., count, index)
append, remove)
Performance Slower due to dynamic size Faster due to immutability
and mutability
Memory Uses more memory due to Uses less memory
Usage flexibility
Use cases Suitable when elements need Suitable for fixed collections or
modification constants
Hashable Not hashable (cannot be used Hashable if elements are hashable
as dict keys) (can be dictionary keys)
Summary
Use lists when you need a collection of items that may change during program
execution.
Use tuples when you want a fixed collection of items that should not change, and
when you need better performance or want to use the collection as a dictionary key.
Q.20. How do you define a function in Python? Write a simple function that takes two
numbers as parameters and returns their sum.
Ans. In Python, a function is defined using the def keyword followed by the function name
and parentheses. The code block inside the function is indented, indicating what statements
belong to the function. You can then call the function by its name followed by parentheses.
Functions can also take parameters to accept inputs and can return a value using
the return statement.
Example: A simple function that takes two numbers and returns their sum
python
def add_numbers(a, b):
return a + b
Calling the function
python
result = add_numbers(3, 5)
print(result) # Output will be 8
This add_numbers function takes two parameters, a and b, adds them, and returns their sum.
You can pass different numbers to this function whenever you call it, making it reusable for
various inputs.
Q.21. How do you write data to a file in Python? Write a simple program that opens a
file in write mode, writes a few lines of text to it, and then close the file.
Ans. In Python, you write data to a file by opening the file in write mode (w), using the file
object's write() method to write text, and then closing the file to ensure the data is saved
properly. When a file is opened in write mode, if the file does not exist, it will be created. If
the file already exists, opening it in write mode will overwrite the existing content.
Simple program to write data to a file in Python:
python
# Open a file named 'example.txt' in write mode
file = open('example.txt', 'w')
# Write multiple lines to the file
file.write("Hello, World! \n")
file.write("This is a simple text file.\n")
file.write("Writing data to a file in Python.\n")
# Close the file to save changes
file.close()
Explanation:
w mode: Opens the file for writing (creates if it doesn't exist, truncates if it does).
write() method: Writes strings to the file; include \n for new lines.
close() method: Closes the file and flushes any buffered output to disk.
Using this approach, you can save text data to files safely in Python. For improved safety,
using with statement for file handling is recommended to automatically close the file.
Example with with statement:
python
with open('example.txt', 'w') as file:
file.write("Hello, World!\n")
file.write("This is a simple text file.\n")
file.write("Writing data to a file in Python.\n")
This method ensures the file is closed automatically after the block execution.
Q.22. What is a module in Python, and how do you use the ‘math’ Module?
Ans. A module in Python is a file containing Python code that defines functions, classes,
variables, and runnable code. Modules help organize code into manageable parts, making it
easier to maintain, understand, and reuse. You can then use the functionality of a module in
other Python programs by importing it using the import statement.
Using the math Module in Python
The built-in math module provides mathematical functions like square root, trigonometric
functions, logarithms, and constants.
To use the math module, you import it and then call its functions or access its constants using
dot notation.
Example:
python
import math
# Calculate the square root of 16
result = math.sqrt(16)
print(result) # Output: 4.0
# Use a constant, pi
print(math.pi) # Output: 3.141592653589793
In this example:
import math loads the math module.
math.sqrt(16) calls the square root function.
math.pi accesses the value of π.
Modules are a fundamental part of Python programming, allowing code reuse and
modularity by grouping related code in separate files.
Q.23. What is the purpose of the 'try' and 'except' block in Python?
Ans. In Python, the purpose of the try and except blocks is to handle exceptions (errors) that
might occur during the execution of a program, preventing the program from crashing.
Purpose of the try block:
The try block lets you write code that might raise an error.
Python attempts to execute the code inside the try block.
Purpose of the except block:
If an error occurs in the try block, Python stops executing that block and jumps to
the except block.
The except block contains code to handle the error gracefully, allowing the program to
continue running.
Example:
python
try:
result = 10 / 0 # This will raise a ZeroDivisionError
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
In this example, instead of crashing, the program catches the division-by-zero error and
prints a friendly message.
Summary:
Use try to test code that might cause errors.
Use except to define how to handle those errors.
This construct improves program robustness by handling anticipated errors gracefully.
Q.24. Define instance methods?
Ans. An instance method is a function defined inside a class that operates on a specific
instance of that class. It has access to the instance (the object) via the first parameter, which
is conventionally named self. This allows the method to read and modify the instance's
attributes for that particular object.
Key points:
Default method type: Instance methods are the most common type of methods in
Python classes.
First parameter: The method takes self as its first parameter to refer to the specific
object the method is called on.
Access scope: They can read and write both instance attributes and class attributes,
and can call other instance methods on the same object.
Invocation: On an instance: obj.method(args) — the object is passed
as self automatically.
Example:
Defining an instance method
python
class Counter:
def __init__(self, start=0):
self.value = start
def increment(self, amount=1):
self.value += amount
return self.value
Using an instance method
python
c = Counter(10)
c.increment() # returns 11
c.increment(5) # returns 16
In contrast, class methods and static methods are defined
with @classmethod and @staticmethod decorators, respectively, and do not operate on a
specific instance in the same way. Instance methods are the default and most common type
of methods used to work with data stored in each individual object.
Q.25. Explain the Syntax and Semantics of any two loop structures Provided by
Python.
Ans. Here are two fundamental loop structures in Python, covering both syntax and
semantics.
1) For loop
Purpose and semantics:
o Iterates over a sequence (or any iterable) and executes a block of code for each
element.
o The loop variable takes on the value of each item in the sequence in order.
o It is typically used when you know the number of items or can iterate over a
collection (lists, tuples, strings, ranges, dictionaries, etc.).
Typical syntax:
python
for <variable> in <iterable>:
<body>
Example:
o Iterate over a list of numbers and print their squares
python
numbers = [1, 2, 3, 4]
for n in numbers:
print(n * n)
o Iterate with a range of integers
python
for i in range(5): # 0, 1, 2, 3, 4
print(i)
Key semantics notes:
o The loop variable is created (or updated) on each iteration.
o If the iterable is empty, the loop body does not execute.
o An optional else block can run after the loop completes normally (i.e., no break
encountered).
2) While loop
Purpose and semantics:
o Repeats as long as a condition evaluates to True.
o Useful when the number of iterations is not known in advance and depends on
runtime conditions.
Typical syntax:
python
while <condition>:
<body>
Example:
o Print numbers from 0 up to but not including 5
python
i=0
while i < 5:
print(i)
i += 1
Key semantics notes:
o The loop continues while the condition is True; if the condition becomes False,
the loop stops.
o It is common to modify the loop variable inside the body to ensure eventual
termination.
o As with for loops, a break can exit early, and an else block can run if
no break occurs.
Comparison at a glance
Use for when you want to traverse a known collection or a range of values;
use while when the number of iterations depends on a condition that may change
during execution.
For loops are generally clearer and less error-prone for standard iterations; while loops
offer more flexibility for complex, condition-driven repetition.
These two structures cover the core loop constructs in Python, along with their typical usage
and semantics.
Q.26. Write a short note on Python Interpreter.
Ans. A Python interpreter is the program that reads, translates, and executes Python code. It
acts as the bridge between Python source code and the machine running it, handling syntax
checking, converting code to an intermediate form (bytecode), and then executing that
bytecode on a virtual machine.
Key aspects
Modes of operation: Interactive (REPL) mode where code is entered line by line, and
script mode where a complete program in a .py file is executed.
Steps in execution: Read source code, parse and check syntax, compile to bytecode,
and run on the Python Virtual Machine (PVM).
Environment features: In interactive mode, you typically get an immediate result
after each statement; in script mode, results appear as the program prints or writes to
files, etc.
Error handling: The interpreter reports syntax errors, runtime exceptions, and other
issues encountered during execution.
Portability: The interpreter abstracts away many platform differences, though
behavior can still depend on the Python version and installed standard library.
In short, the Python interpreter is the runtime engine that evaluates Python code, turning
human-readable scripts into actions performed by the computer. It provides both interactive
and script-based execution, with a pipeline that includes parsing, compiling to bytecode, and
executing on a virtual machine.
Q.27. Differentiate between Interactive Mode & Script Mode.
Ans. Here’s a concise comparison of the two Python execution modes: Interactive Mode and
Script (Batch) Mode.
What they are
Interactive Mode: A read–eval–print loop (REPL) where commands are entered one
at a time and executed immediately. You typically run Python from a terminal or an
IDE feature that provides an interactive shell.
Script (Batch) Mode: Running a complete Python program saved in a file (with a .py
extension). The interpreter reads the entire file, compiles it, and executes it from top to
bottom.
Key differences
Aspect Interactive Mode Script Mode
Input and Type a line or small expression, Write a full program in a file,
workflow press Enter, and see the result then execute the file as a whole.
instantly. Great for exploration, This supports longer, structured
quick calculations, or trying out programs with functions, classes,
ideas. and multiple modules.
Persistence Commands aren't automatically Programs are saved as files,
and reuse saved for later use, unless you versionable, and reusable. They
explicitly copy or paste them can be run multiple times, shared,
into a script file or use a history and tested independently.
feature in the environment.
Output and Immediate feedback after each Output appears as the program
visibility command, which is useful for runs, typically organized through
learning and experimentation print statements, logging, or
but can be noisy for larger tasks. GUI/terminal interactions; better
for demonstrations or automation
pipelines.
Use cases Ideal for learning Python basics,
Ideal for developing full
quick experiments, debugging applications, automation scripts,
small snippets, or performing data processing pipelines, or
ad-hoc tasks. anything requiring maintainable,
repeatable runs.
Termination Usually exits with a specific Running a script starts a fresh
and command (like exit() or Ctrl-D). process; after completion, the
environment The environment persists for the process ends, and the
session, keeping a current environment is cleared unless the
namespace. script creates persistent outputs
(files, databases, etc.).
Practical takeaway
Use Interactive Mode for learning, experimentation, and quick checks.
Use Script Mode for building, saving, and sharing real programs.
Q.28. What type of conditional structures are present in a Python? Explain with
example.
Ans. Python offers several types of conditional structures to control the flow of program
execution based on conditions:
1. If statement
Syntax:
python
if condition:
# Code block executed if condition is True
Semantics: The condition is evaluated; if it is true, the indented code block runs; if
false, the block is skipped.
Example:
python
age = 20
if age >= 18:
print("You are an adult.")
2. If-else statement
Syntax:
python
if condition:
# Code block if condition is True
else:
# Code block if condition is False
Semantics: One of two code blocks executes depending on the condition's truth value.
Example:
python
age = 16
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
3. If-elif-else ladder
Syntax:
python
if condition1:
# Block 1
elif condition2:
# Block 2
else:
# Default block if none above true
Semantics: Conditions are evaluated sequentially, and the first true condition's block
executes, skipping the rest.
Example:
python
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
else:
grade = "C"
print("Grade:", grade)
4. Ternary conditional expression
A compact, one-line conditional expression.
Syntax:
python
value_if_true if condition else value_if_false
Example:
python
age = 20
status = "Adult" if age >= 18 else "Minor"
print(status)
5. Match-case statement (introduced in Python 3.10)
A way to match values against patterns like a switch-case in other languages.
Syntax:
python
match variable:
case pattern1:
# block
case pattern2 | pattern3:
# block
case _:
# default block
Example:
python
number = 2
match number:
case 1:
print("One")
case 2 | 3:
print("Two or Three")
case _:
print("Other number")
These structures allow flexible and readable control over program execution based on
conditions.
Q.29. Why we use Collections in Python?
Ans. Collections in Python are used to organize and store multiple items together efficiently.
They provide specialized data structures that extend the functionality of Python's built-in
types like lists, tuples, dictionaries, and sets. The purpose of using collections is to:
Simplify complex data structure handling with cleaner, more readable, and faster
implementations.
Provide efficient alternatives for common programming tasks such as counting items
(Counter), handling missing keys (defaultdict), maintaining order (OrderedDict), and
managing queues (deque).
Enhance performance in data-heavy applications by using data structures optimized
for specific needs.
Increase code robustness and reduce errors by using specialized containers tailored to
particular problems.
Improve code clarity by using meaningful data types like namedtuple which allows
field access by name instead of index.
In short, collections help make Python programming more effective, readable, and efficient
when working with groups of related data.
Q.30. Discuss the Common built in data types in Python.
Ans. Python has several built-in data types that serve as the fundamental building blocks for
data manipulation and storage in Python programs.
Common Built-in Data Types in Python
Numeric Types: int (integers), float (floating-point numbers), complex (complex
numbers).
Sequence Types: str (strings), list, tuple, range.
Mapping Type: dict (dictionaries).
Set Types: set, frozenset.
Boolean Type: bool (True or False).
Binary Types: bytes, bytearray, memoryview.
None Type: NoneType (represents the absence of a value).
These data types allow Python to handle various forms of data efficiently, and you can
identify an object's type using the type() function.
Q.31. Explain Regular Expressions with any four methods with proper examples.
Ans. Regular Expressions (regex) in Python provide a powerful way to match and
manipulate strings based on specific patterns. They are widely used for searching, replacing,
and parsing efficient text.
Four Common Methods of Python's re Module with Examples:
1. re.findall()
Returns a list of all non-overlapping matches of the pattern in the string.
Example:
python
import re
text = "The rain in Spain"
matches = re.findall("ai", text)
print(matches) # Output: ['ai', 'ai']
2. re.search()
Searches the string for the first location where the regex pattern produces a match and
returns a match object or None.
Example:
python
match = re.search("rain", text)
if match:
print("Match found:", match.group()) # Output: Match found: rain
else:
print("No match")
3. re.split()
Splits the string by occurrences of the pattern and returns a list.
Example:
python
parts = re.split("\s", text)
print(parts) # Output: ['The', 'rain', 'in', 'Spain']
4. re.sub()
Replaces occurrences of the pattern in the string with a specified replacement,
returning the modified string.
Example:
python
replaced = re.sub("Spain", "France", text)
print(replaced) # Output: The rain in France
These methods enable flexible matching, searching, splitting, and transforming of textual
data using regex patterns in Python.
Q.32. Explain indexing and slicing operation for string manipulation with example.
Ans. Indexing and slicing are fundamental operations used for string manipulation in
Python.
Indexing:
Indexing allows access to a single character in a string using its position (index). Each
character in a string has a numerical index starting from 0 for the first character.
Positive indexing starts from 0 at the beginning of the string.
Negative indexing starts from -1 at the end of the string.
Example:
python
text = "Hello, World!"
print(text[0]) # Output: H (first character)
print(text[-1]) # Output: ! (last character)
Slicing:
Slicing extracts a substring from the original string by specifying a range of indices. The
syntax is string[start:end], where start is inclusive and end is exclusive.
You can also specify a step: string[start:end:step]
Example:
python
text = "Hello, World!"
print(text[0:5]) # Output: Hello (characters from index 0 to 4)
print(text[7:12]) # Output: World
print(text[:5]) # Output: Hello (start defaults to 0)
print(text[7:]) # Output: World! (goes till end)
print(text[::2]) # Output: Hlo ol! (every 2nd character)
Indexing gives you access to individual characters, while slicing lets you extract parts
(substrings) of strings efficiently for manipulation or analysis. Both are widely used in text
processing.
Q.33. Explain mutable and immutable data types with example.
Ans. Mutable and immutable data types differ in whether their values can be changed after
creation.
Mutable Data Types: These are types whose contents can be modified without changing
their identity. You can update, add, or remove elements after creation.
Examples:
Lists: You can change, append, or remove items.
python
my_list = [1, 2, 3]
my_list[0] = 10 # Now my_list is [10, 2, 3]
Dictionaries: You can modify values or add new key-value pairs.
python
my_dict = {'name': 'Alice', 'age': 25}
my_dict['age'] = 26 # Updates age to 26
Sets: You can add or remove elements.
python
my_set = {1, 2, 3}
my_set.add(4) # my_set becomes {1, 2, 3, 4}
Immutable Data Types: These cannot be altered after creation; any change creates a new
object. Attempts to modify them cause errors or create new instances.
Examples:
Strings: Cannot be changed in place; concatenation creates a new string.
python
s = "hello"
s = s + " world" # Creates a new string "hello world"
Tuples: Ordered collections that cannot be modified after creation.
python
t = (1, 2, 3)
# t[0] = 5 # This would raise an error
Numbers (int, float): Numeric values cannot be changed; operations create new
numbers.
Understanding mutability affects how variables behave, memory usage, and function side
effects in programming.
Q.34. Write a Python program to count the number of vowels in a string.
Ans.
python
# Python program to count the number of vowels in a string
def count_vowels(input_string):
vowels = "aeiouAEIOU"
count = 0
for char in input_string:
if char in vowels:
count += 1
return count
# Example usage
text = input("Enter a string: ")
vowel_count = count_vowels(text)
print("Number of vowels in the string:", vowel_count)
This program defines a function count_vowels that iterates through the string, checks if each
character is a vowel, and increments the counter accordingly. It handles both uppercase and
lowercase vowels.
Q.35. What is lambda function in Python? Explain with example.
Ans. A lambda function in Python is a small anonymous function defined with
the lambda keyword. It can take any number of arguments but contains only a single
expression, which is evaluated and returned.
Features:
It has no name unless assigned to a variable.
It is typically used for short, simple functions.
It is often used inline within higher-order functions like map(), filter(), and sorted().
Syntax:
python
lambda arguments: expression
Example:
python
# A lambda function that adds 10 to the input
add_ten = lambda x: x + 10
print(add_ten(5)) # Output: 15
# Lambda function with two arguments multiplying them
multiply = lambda a, b: a * b
print(multiply(4, 3)) # Output: 12
# Using lambda inside another function
def myfunc(n):
return lambda a: a * n
doubler = myfunc(2)
print(doubler(11)) # Output: 22
Lambda functions are concise and useful for quick, single-use functions without needing
formal function definitions.
Q.36. Write a python program to implement LEAP ( ) function to check given year is
leap year or not.
Ans.
python
# Python program to implement a function to check if a year is a leap year
def is_leap_year(year):
# Leap year if divisible by 4, but not by 100 unless divisible by 400
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
return True
else:
return False
# Example usage
year_input = int(input("Enter a year: "))
if is_leap_year(year_input):
print(year_input, "is a leap year.")
else:
print(year_input, "is not a leap year.")
This function checks the rules for leap years: divisible by 4 but not by 100, except that years
divisible by 400 are leap years. The program inputs a year and prints whether it's a leap year
or not.
Q.37. What is the difference between error and exception?
Ans. The difference between error and exception is:
Error:
An error represents a serious problem that is usually beyond the control of the
program and generally cannot be handled or recovered from during runtime. Errors
often indicate issues related to system resources or environment failures (e.g.,
OutOfMemoryError, StackOverflowError). They typically cause the program to
terminate abnormally.
Exception:
An exception is an event that disrupts the normal flow of a program's execution and
usually occurs due to coding issues or unexpected conditions during runtime.
Exceptions can often be caught and handled gracefully by the program using
mechanisms like try-catch blocks, allowing the program to recover or provide
informative messages (e.g., IOException, NullPointerException,
ArithmeticException).
In summary, errors are severe, often unrecoverable problems related to the system, while
exceptions are typically recoverable issues caused by application code that the program can
manage through proper handling.
Q.38. Write a Python program that reads a text file and changes the file by capitalizing
each character of file.
Ans.
python
# Python program to read a text file and capitalize each character
def capitalize_file(filename):
# Open the file in read mode
with open(filename, 'r') as file:
content = file.read()
# Capitalize all characters
capitalized_content = content.upper()
# Open the file in write mode to overwrite with capitalized content
with open(filename, 'w') as file:
file.write(capitalized_content)
print("File content has been capitalized successfully.")
# Example usage
filename = input("Enter the filename: ")
capitalize_file(filename)
This program reads the entire content of the file, converts it to uppercase, and overwrites the
original file with the capitalized text. Make sure the file exists in your working directory or
provide the full path.
Q.39. Write a program which demonstrates multiple inheritance.
Ans.
python
# Python program demonstrating multiple inheritance
# Base class 1
class Parent1:
def greet(self):
print("Hello from Parent1")
# Base class 2
class Parent2:
def greet(self):
print("Hello from Parent2")
def welcome(self):
print("Welcome from Parent2")
# Derived class inheriting from both Parent1 and Parent2
class Child(Parent1, Parent2):
def greet(self):
# Calling greet from Parent1 explicitly
Parent1.greet(self)
# Calling greet from Parent2 explicitly
Parent2.greet(self)
print("Hello from Child")
# Create object of Child class
c = Child()
# Call methods
c.greet() # Calls the overridden greet method in Child
c.welcome() # Calls welcome method inherited from Parent2
This program shows multiple inheritance where class Child inherits from
both Parent1 and Parent2. It overrides a method and also calls methods from both parent
classes explicitly.
Q.40. Create a class employee with data member : name, department and salary.
Create suitable methods for reading and printing employee information.
Ans.
python
# Class definition for Employee
class Employee:
def __init__(self):
self.name = ""
self.department = ""
self.salary = 0.0
def read_info(self):
self.name = input("Enter employee name: ")
self.department = input("Enter department: ")
self.salary = float(input("Enter salary: "))
def print_info(self):
print(f"Employee Name: {self.name}")
print(f"Department: {self.department}")
print(f"Salary: {self.salary}")
# Example usage
emp = Employee()
emp.read_info()
emp.print_info()
This class Employee has data members name, department, and salary. The read_info method
takes input from the user and stores it, and the print_info method displays the employee
details.
Q.41. Describe the concept of list comprehension with an example.
Ans. List comprehension in Python is a concise way to create new lists by applying an
expression to each item in an existing iterable. It allows you to write readable and efficient
code in a single line instead of using loops and append statements.
Syntax:
python
new_list = [expression for item in iterable if condition]
expression: Operation or value to include in the new list.
item: Current element from the iterable.
iterable: Sequence like a list, tuple, or range.
if condition (optional): Filter to include only items that satisfy the condition.
Example:
Create a list of squares of even numbers from 0 to 9:
python
squares = [x**2 for x in range(10) if x % 2 == 0]
print(squares)
# Output: [0, 4, 16, 36, 64]
List comprehension provides a compact and elegant way to generate lists by combining
loops and conditional logic in a single expression.
Q.42. Write a python program to swap the given two numbers using functions.
Ans.
python
# Python program to swap two numbers using a function
def swap_numbers(a, b):
return b, a
# Input numbers
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
print(f"Before swapping: num1 = {num1}, num2 = {num2}")
# Swap using the function
num1, num2 = swap_numbers(num1, num2)
print(f"After swapping: num1 = {num1}, num2 = {num2}")
This program defines a function swap_numbers that takes two arguments and returns them in
swapped order. The values are then reassigned to swap the numbers.
Q.43. What are the different flow control statements available in python?
Ans. Python provides several flow control statements that regulate the execution order of
code:
1. Conditional Statements (Decision Making)
if statement: Executes a block if a condition is true.
if-else statement: Executes one block if the condition is true, another if false.
if-elif-else chain: Checks multiple conditions sequentially to choose which block to
execute.
match-case statement (Python 3.10+): Matches a variable against patterns for
complex branching.
2. Looping Statements (Repetition)
for loop: Iterates over a sequence (like list, tuple, range) a fixed number of times.
while loop: Repeats execution as long as a condition is true.
3. Loop Control Statements
break: Terminates the nearest enclosing loop immediately.
continue: Skips the rest of the current iteration and proceeds to the next iteration of
the loop.
pass: A no-operation placeholder useful when code is syntactically required but no
action is needed.
4. Function Control Statements
return: Exits a function and optionally returns a value.
These control flow statements enable conditional execution, looping, and structured
programming for dynamic and flexible Python code.
Q.44. Explain any 2 metacharacters used in regular expression.
Ans. Two commonly used metacharacters in regular expressions are:
1. Dot (.)
o Matches any single character except a newline ('\n').
o Example: The pattern 'a.c' matches "abc", "axc", "a-c", etc., any string starting
with 'a' and ending with 'c' with any single character in between.
2. Backslash ()
o Used to escape special characters to treat them literally, or to signal special
sequences like '\d' for digits, '\w' for word characters, and '\s' for whitespace.
o Example:
'.' matches a literal dot character '.'.
'\d' matches any digit character (0-9).
These metacharacters form the building blocks of regular expressions for powerful pattern
matching and text processing in Python and many other languages.
Q.45. Discuss about libraries in python and what is the use of libraries?
Ans. Libraries in Python are collections of pre-written code, modules, and functions bundled
together to provide reusable functionality for various programming tasks. These libraries
simplify coding by allowing programmers to utilize existing code instead of writing
everything from scratch. They can contain code for tasks like mathematical operations, data
manipulation, file handling, web development, machine learning, visualization, and more.
Uses of Libraries:
Code Reusability: Avoid rewriting common functions and algorithms by importing
libraries.
Faster Development: Speeds up programming by providing tested and optimized
functionalities.
Specialized Functionality: Provides access to domain-specific tools, such as NumPy
for numerical computing or Pandas for data analysis.
Improved Code Quality: Leverages well-maintained and community-reviewed code.
Simplifies Complex Tasks: Libraries abstract complex processes, making them easier
to implement (e.g., making HTTP requests or creating plots).
For example, the standard Python library includes modules like math for
mathematics, datetime for date/time operations, and os for operating system interfaces.
Third-party libraries such as TensorFlow aid in machine learning, while Matplotlib assists
with data visualization.
Overall, libraries are essential for efficient programming, making Python powerful and
versatile across many fields.
Q.46. Explain argument and its different types in functions with suitable examples.
Ans. In functions, arguments are the actual values passed to the function parameters when
calling the function. They provide input for the function to process.
Different Types of Arguments in Python with Examples:
1. Positional Arguments:
Values are passed to parameters based on their position/order.
Example:
python
def greet(name, age):
print(f"Hello {name}, you are {age} years old.")
greet("Alice", 25) # name="Alice", age=25
2. Keyword Arguments:
Values are passed by explicitly naming the parameters, so order doesn't matter.
Example:
python
greet(age=25, name="Alice") # same output as above
3. Default Arguments:
Parameters have default values that are used if no argument is passed for them.
Example:
python
def greet(name, age=18):
print(f"Hello {name}, you are {age} years old.")
greet("Bob") # age defaults to 18
greet("Charlie", 30) # age overridden to 30
4. Arbitrary Positional Arguments (*args):
Allows passing a variable number of non-keyworded arguments as a tuple.
Example:
python
def add(*numbers):
total = 0
for num in numbers:
total += num
print("Sum:", total)
add(1, 2, 3, 4) # outputs 10
5. Arbitrary Keyword Arguments (kwargs):**
Allows passing a variable number of keyworded arguments as a dictionary.
Example:
python
def info(**details):
for key, value in details.items():
print(f"{key}: {value}")
info(name="Alice", age=25, city="Delhi")
These argument types make functions flexible and powerful by enabling different ways to
pass input to functions for diverse use cases.
Q.47. Discuss about the object oriented paradigm in python.
Ans. Object-oriented programming (OOP) in Python is a programming paradigm that
organizes code around objects and classes, mirroring real-world entities and behaviors.
Instead of writing purely procedural code, OOP structures programs by combining data
(attributes) and functions (methods) into reusable objects.
Key Concepts:
Class: A blueprint or template for creating objects. It defines attributes and methods
that characterize any instance of the class.
Object: An instance of a class that holds specific data and behaviors. For example, an
object car1 of class Car can have attributes like color and speed.
Encapsulation: Bundling the data (attributes) and methods that operate on the data
into a single unit (class) and restricting access to some components.
Inheritance: Allows a class (child or subclass) to inherit attributes and methods from
another class (parent or superclass), enabling code reuse and hierarchical relationships.
Polymorphism: The ability to use a single interface to represent different underlying
forms (data types). For example, methods with the same name behaving differently on
various classes.
Benefits in Python:
Helps organize complex programs into modular and manageable pieces.
Promotes reusability and extensibility with inheritance and polymorphism.
Makes code more readable and closer to real-world scenarios by modeling entities as
objects.
Python supports OOP natively with syntax for defining classes, creating objects, and
implementing OOP principles such as encapsulation, inheritance, and polymorphism. It is
widely used for building scalable, maintainable, and robust applications.
Q.48. Explain standard datatypes in python.
Ans. Standard data types in Python are built-in classes used to represent different kinds of
data. They provide the foundation for storing and manipulating values in programs.
Common Standard Data Types:
1. Numeric Types:
o int: Represents integer values, e.g., 5, 100.
o float: Represents floating-point numbers (decimals), e.g., 3.14, 2.0.
o complex: Represents complex numbers with real and imaginary parts,
e.g., 3+4j.
2. Sequence Types:
o str (String): Immutable sequence of Unicode characters, e.g., Hello.
o list: Mutable ordered collection of items, e.g., [1, 2, 3].
o tuple: Immutable ordered collection, e.g., (1, 2, 3).
o range: Represents an immutable sequence of numbers, commonly used in
loops.
3. Mapping Type:
o dict (Dictionary): Collection of key-value pairs, e.g., {'name': 'Alice', 'age':
25}.
4. Set Types:
o set: Mutable collection of unique elements, e.g., {1, 2, 3}.
o frozenset: Immutable version of set.
5. Boolean Type:
o bool: Represents truth values True or False.
6. Binary Types:
o bytes: Immutable sequence of bytes.
o bytearray: Mutable sequence of bytes.
o memoryview: Allows access to the memory of other binary objects without
copying.
7. None Type:
o NoneType: Represents the absence of a value, denoted by None.
These data types help Python programmers work with numbers, texts, collections, and more,
providing flexibility and power for diverse applications.
Q.49. Explain the use of dir() function.
Ans. The dir() function in Python is a built-in utility used to inspect objects and the current
namespace.
Uses:
Without any arguments, dir() returns a list of names (variables, functions, classes, etc.)
defined in the current local scope.
When passed an object as an argument, it returns a list of valid attributes and methods
belonging to that object, including user-defined and built-in properties.
Examples:
python
print(dir())
# Output: List of names in the current scope
import math
print(dir(math))
# Output: List of all functions and constants in the math module
class Person:
def __init__(self):
self.name = "John"
def greet(self):
print("Hello")
p = Person()
print(dir(p))
# Output: ['__class__', '__delattr__', ..., 'greet', 'name']
Purpose:
Helps explore available methods and attributes of an object.
Useful for debugging and introspection.
Assists learning by discovering what functionality an object or module provides.
dir() is essential for interactive exploration and understanding of Python's dynamic attributes
and object properties.
Q.50. Write a short note on assert.
Ans. The assert statement in Python is a debugging aid that tests a condition as a sanity
check during program execution. It verifies whether a given expression is true. If the
expression evaluates to False, the assert statement raises an AssertionError and optionally
displays a specified error message, halting further execution.
Syntax:
python
assert condition, "error message"
condition: The boolean expression expected to be true.
error message (optional): A message to display if the assertion fails.
Use:
Helps to catch programmatic errors early during development by validating
assumptions.
Used to ensure that certain conditions hold true for inputs, states, or results.
Not intended for handling run-time errors or user input validations; exceptions are
preferred for those.
Can be globally disabled with Python's optimized mode (python -O).
Example:
python
def divide(a, b):
assert b != 0, "Denominator cannot be zero"
return a / b
print(divide(10, 2)) # Works fine
print(divide(10, 0)) # Raises AssertionError: Denominator cannot be zero
In summary, assert is a tool for developers to catch logical errors early by enforcing
conditions that should always hold true during program execution.
Q.51. Explain how read and write method works on a file.
Ans. The read() and write() methods in Python are used to read data from and write data to
files, respectively.
read() Method:
The read() method reads the content of an opened file as a single string.
You can optionally specify the number of characters (bytes) to read: file.read(size).
If no size is provided, it reads the entire file.
Subsequent calls to read() continue from where the last read ended until the end of the
file (EOF).
Example:
python
file = open("example.txt", "r")
content = file.read()
print(content)
file.close()
write() Method:
The write() method writes a string to an open file.
It overwrites the content if the file is opened in write mode "w" or appends if in
append mode "a".
The method returns the number of characters written to the file.
The file must be opened in the appropriate mode to allow writing ("w", "a", or "r+").
Example:
python
file = open("example.txt", "w")
chars_written = file.write("Hello, this is a test.")
print(f"{chars_written} characters written.")
file.close()
Summary:
read() is used for reading file content into memory.
write() is used to output text to the file, either replacing existing content or adding to it
depending on the mode.
Both methods require opening the file first and closing it afterward to free system resources.
Q.52. What are methods in python? Explain.
Ans. In Python, a method is a function that is associated with an object and is defined within
a class. Methods are used to define the behaviors of an object; they operate on the data
contained within that object or class. Unlike standalone functions, methods implicitly receive
the instance (object) as their first parameter, traditionally named self.
Key Points about Methods:
Defined inside a class using the def keyword.
The first parameter of instance methods is self, which refers to the object calling the
method.
Methods can access and modify the object's attributes and perform actions relevant to
the object.
Methods improve code organization by associating functionality with the data it acts
upon.
Example:
python
class Dog:
def __init__(self, name):
self.name = name # Instance attribute
def bark(self):
print(f"{self.name} says Woof!")
# Create an object of Dog
dog1 = Dog("Buddy")
# Call method
dog1.bark() # Output: Buddy says Woof!
Types of Methods:
Instance Methods: Operate on individual object instances.
Class Methods: Marked with @classmethod, receive the class itself as the first
parameter.
Static Methods: Marked with @staticmethod, do not receive an implicit first
argument.
Methods encapsulate functionality related to objects and constitute a fundamental part of
Python's object-oriented programming paradigm, enhancing code readability, reusability, and
maintainability.
Q.53. Explain scope in Python.
Ans. In Python, scope refers to the region or context in a program where a variable is
accessible. It defines the visibility and lifetime of variables, determining from where they
can be referenced or modified.
Types of Scope:
1. Local Scope:
Variables declared inside a function have local scope. They can only be accessed
within that specific function and are destroyed once the function execution ends.
2. Enclosing Scope:
Applicable when there are nested functions, this scope refers to the variables in the
local scope of the outer function, accessible inside inner functions.
3. Global Scope:
Variables defined at the top level of a script or module have global scope and can be
accessed anywhere within that module.
4. Built-in Scope:
Contains names predefined by Python, such as keywords and built-in functions
like len() and print().
LEGB Rule:
Python resolves names following the LEGB rule, searching in this order:
L: Local
E: Enclosing
G: Global
B: Built-in
Example:
python
x = "global"
def outer():
x = "enclosing"
def inner():
x = "local"
print(x) # prints "local"
inner()
print(x) # prints "enclosing"
outer()
print(x) # prints "global"
Understanding scope is crucial for writing bug-free code and managing variable lifetimes
effectively.