Q1)What is function?
Explain defining functions in
Python with example.
A function in Python is a reusable block of code that performs a
specific task when called, helping to organize programs and avoid
repetition. Functions can take inputs called parameters, process
them, and optionally return a result.
## Defining Syntax
Functions start with the `def` keyword, followed by a name,
parentheses for parameters, and a colon. The body is indented, and
`return` sends output back.
def greet(name):
return f"Hello, {name}!"
```
This defines `greet` to accept a `name` parameter and return a
greeting
## Calling Functions
Invoke by using the name with arguments in parentheses, like
`result = greet("Alice")`, which outputs "Hello, Alice!"
## Example with Math
Here's a function computing rectangle area:
def area(length, width):
return length * width
print(area(5, 3)) # Outputs: 15
It multiplies inputs and returns the product, demonstrating
parameters and return
Q2)Explain command line arguments in Python with
example.
✅ Command Line Arguments in Python
Command Line Arguments are the values passed to a Python
program from the command line (terminal) when the program is
executed.
To access these arguments, Python provides the sys module,
especially:
👉 [Link]
It is a list that stores all command line arguments.
Argv[0] → name of the Python file
Argv[1] onwards → arguments passed by the user
📌 Example Program
Import sys
# Printing number of arguments
Print(“Number of arguments:”, len([Link]))
# Printing the arguments as a list
Print(“Arguments list:”, [Link])
# Accessing individual arguments
Print(“First argument:”, [Link][1])
Print(“Second argument:”, [Link][2])
Q3) Explain in brief args and **kwargs.
In Python, and are used to pass a variable number of
arguments to a function when you are unsure how many
inputs it will receive. They provide flexibility in function
design.
*args is used to pass a variable number of non-
keyworded (positional) arguments. Inside the
function, these arguments are collected into a tuple.
Args stands for arguments, and the single asterisk () is the
operator that enables this functionality.
**kwargs is used to pass a variable number of
keyworded (named) arguments in the form of key-
value pairs. Inside the function, these arguments are
collected into a dictionary.
Kwargs stands for keyword arguments, and the double
asterisk () is the operator. [3, 4, 5, 6, 7]
Key Points
The names and are by convention only; you can use any
valid variable name, provided you use the and operators.
When used together in a function definition, must come
before .
The and symbols can also be used when calling a function
to "unpack" an iterable (like a list or tuple) or a dictionary
into separate arguments. [3, 6, 8, 9, 10]
Q4) Write a note on type() Function and Is Operator
The `type()` function in Python returns the data type of an
object, aiding in runtime type checking. The `is` operator tests
if two variables reference the exact same object in memory,
distinct from equality checks with `==`.
## type() Usage
Call `type(object)` to get the class type, shown as `<class
'str'>` for strings.
x = 42
print(type(x)) # <class 'int'>
y = "hello"
print(type(y)) # <class 'str'> [web:21][web:22]
```
It supports dynamic class creation with `type(name, bases,
dict)` but is mainly for inspection [5][6].
## is Operator
`is` verifies identity, returning True only for identical objects.
a = [1, 2]
b=a
c = [1, 2]
print(a is b) # True (same object)
print(a is c) # False (different objects) [web:22]
Avoid is for value equality; use == instead, as is checks
memory location
Q5) data type in Python with example
A data type defines the kind of data a variable can hold, determining
how the computer interprets binary sequences and what operations can
be performed on it. The most common data types across various
programming languages include:
Integer ( int ): Used for whole numbers (positive or negative)
without a decimal point.
o Example: age = 30 or int number_of_students = 25 .
Float ( float , double , number ): Used for numbers with a decimal
point (floating-point numbers).
o Example: temperature = 98.6 or double pi = 3.14159 .
String ( str , String ): A sequence of characters used for text.
o Example: name = "John Doe" or String message =
'Hello, World!' .
Boolean ( bool , boolean ): Represents a logical value that can
only be either True (or true ) or False (or false ).
o Example: is_open = True or boolean dataChecked =
false .
Character ( char ): Used to store a single character, typically
enclosed in single quotes.
o Example: char grade = 'A' .
Other Data Types
Many languages also support more complex or specific data types, such
as:
Arrays/Lists: A collection of elements of the same type, stored in
contiguous memory locations.
Objects/Structures ( struct ): A user-defined data type that
groups variables of different types under a single name.
Pointers: A variable that stores the memory address of another
variable.
Date and Time: Specialized types for managing calendar dates and
times.
Q6)Explain any 4 list methods with syntax and example.
Here are explanations for four common Python list methods,
including their syntax and examples:
append() : Adds a single element to the end of the list.
This method modifies the list in place and does not return
a value.
o Syntax: list_name.append(element)
o Example:
python
fruits = ['apple', 'banana', 'cherry']
[Link]('date')
print(fruits)
# Output: ['apple', 'banana', 'cherry',
'date']
insert() : Inserts an element at a specified index
(position). The existing elements from that index onwards
are shifted to the right.
o Syntax: list_name.insert(index, element)
o Example:
python
fruits = ['apple', 'banana', 'cherry']
[Link](1, 'avocado')
print(fruits)
# Output: ['apple', 'avocado', 'banana',
'cherry']
remove() : Removes the first occurrence of a specified
value from the list. If the element is not found, it raises
a ValueError .
o Syntax: list_name.remove(element)
o Example:
python
numbers = [1, 2, 3, 2, 4]
[Link](2)
print(numbers)
Q6)
# Output: [1, 3, 2, 4]
pop() : Removes and returns the element at a specified
position. If no index is specified, it removes and returns
the last element of the list.
o Syntax: list_name.pop([index])
o Example:
python
fruits = ['apple', 'banana', 'cherry']
removed_fruit = [Link](1)
print(fruits)
print(removed_fruit)
# Output: ['apple', 'cherry']
# Output: banana
Q7)Explain list slicing and joining in Python with
example. short
List slicing extracts portions of a list using `list[start:stop:step]`
syntax, creating a shallow copy. Joining combines iterables into
a string via `join()`.
## Slicing Examples
`start` (inclusive), `stop` (exclusive), `step` (default 1); omit
for defaults.
nums = [0, 1, 2, 3, 4, 5]
print(nums[1:4]) # [1, 2, 3]
print(nums[:3]) # [0, 1, 2]
print(nums[::2]) # [0, 2, 4]
print(nums[::-1]) # [5, 4, 3, 2, 1]
```
Negative indices count from end [1][2].
## Joining Strings
`[Link](iterable)` concatenates with a delimiter.
words = ['Python', 'is', 'fun']
result = ' '.join(words) # "Python is fun"
print(result)
nums_str = ', '.join(map(str, [1, 2, 3])) # "1, 2, 3"
[web:43]
```
Q8)Explain Creating and Storing Strings in brief python
Python strings are immutable sequences of Unicode characters
created using single (`’`) or double (`”`) quotes, or via the
`str()` constructor. They store text data efficiently and support
operations like indexing and concatenation.
## Creation Methods
Assign directly with quotes for literals; use `str()` for
conversion.
```
Msg1 = ‘Hello’ # Single quotes
Msg2 = “World” # Double quotes
Num_str = str(42) # From other types: ‘42’ [web:65]
[web:67]
```
Triple quotes (`’’’` or `”””`) handle multiline strings.
Poem = ‘’’Line one
Line two’’’ [web:68]
```
## Storage and Access
Strings occupy memory as objects; access characters via
indexing (`s[0]`).
Text = “Python”
Print(text[0]) # ‘P’
Print(len(text)) # 6 [web:65]
```
Raw strings (`r’path\to\file’`) escape backslashes literally [4].
Q9) Explain creating list in Python.
Creating a list in Python is straightforward. Lists are mutable (changeable)
sequences used to store multiple items in a single variable.
1. Using Square Brackets [] (Most Common)
You place elements inside square brackets, separated by commas.
Empty List:
Empty_list = []
List with items:
Numbers = [10, 20, 30, 40]
Names = [“Alice”, “Bob”, “Charlie”]
Mixed Data Types: Lists can hold different types of data at once.
# A list containing an int, a string, and a float
Mixed = [1, “Hello”, 3.14]
2. Using the list() Constructor
You can use the built-in list() function to convert other sequences (like
strings or tuples) into a list.
# Convert a tuple to a list
My_tuple = (5, 10, 15)
New_list = list(my_tuple) # Output: [5, 10, 15]
# Convert a string to a list of characters
Char_list = list(“BCA”) # Output: [‘B’, ‘C’, ‘A’]
3. Using List Comprehension (Advanced)
This is a concise way to create lists based on existing lists or ranges.
# Create a list of squares from 0 to 4
Squares = [x**2 for x in range(5)]
Print(squares) # Output: [0, 1, 4, 9, 16]
Q10) Explain Indexing and Slicing in Tuples with
example.
Indexing and slicing in Python tuples are used to access specific
elements or a range of elements, much like with lists or strings.
A key characteristic is that these operations do not modify the
original tuple because tuples are immutable.
Here is a short explanation with an example:
Indexing
Indexing is used to retrieve a single element from a tuple by its
position (index). Python uses zero-based indexing (the first
element is at index 0 ), and also supports negative indexing to
count from the end of the tuple (the last element is at index -
1 ).
python
# Example tuple
my_tuple = ('P', 'y', 't', 'h', 'o', 'n')
# Positive indexing
first_element = my_tuple[0]
third_element = my_tuple[2]
# Negative indexing
last_element = my_tuple[-1]
second_last_element = my_tuple[-2]
print(f"First element (index 0): {first_element}")
# Output: P
print(f"Third element (index 2): {third_element}")
# Output: t
print(f"Last element (index -1): {last_element}")
# Output: n
print(f"Second last element (index -2):
{second_last_element}") # Output: o
Q10)
Slicing
Slicing allows you to extract a new tuple containing a
sequence of elements from a range of indices. The syntax
is my_tuple[start:stop:step] , where:
start : The beginning index (inclusive). Defaults to 0 .
stop : The ending index (exclusive).
step : The interval between indices (stride). Defaults
to 1 .
python
# Example tuple
my_tuple = (10, 20, 30, 40, 50, 60, 70)
# Slice from index 1 up to (but not including) index
4
slice1 = my_tuple[1:4]
# Slice from the beginning to index 3 (exclusive)
slice2 = my_tuple[:3]
# Slice from index 2 to the end
slice3 = my_tuple[2:]
# Slice the entire tuple with a step of 2
slice4 = my_tuple[::2]
print(f"Slice 1 to 4: {slice1}") # Output: (20, 30,
40)
print(f"Slice up to 3: {slice2}") # Output: (10,
20, 30)
print(f"Slice from 2 onwards: {slice3}") # Output:
(30, 40, 50, 60, 70)
print(f"Slice with step 2: {slice4}") # Output: (10,
30, 50, 70)
Q11)What is set in python Explain ant 4 set methods with syntax
and example
Sets in Python store unique, unordered, and mutable collections of
immutable elements like integers, strings, or tuples.
## add() Method
Adds a single element to the set if it doesn’t already exist. Syntax:
`[Link](element)`.
Fruits = {“apple”, “banana”}
[Link](“orange”)
Print(fruits) # Output: {‘apple’, ‘banana’, ‘orange’}
## remove() Method
Removes a specified element; raises KeyError if absent. Syntax:
`[Link](element)`.
Fruits = {“apple”, “banana”, “orange”}
[Link](“banana”)
Print(fruits) # Output: {‘apple’, ‘orange’}
## union() Method
Returns a new set with elements from the original and another set (or
iterable). Syntax: `[Link](set2)`.
Set1 = {1, 2, 3}
Set2 = {3, 4, 5}
Result = [Link](set2)
Print(result) # Output: {1, 2, 3, 4, 5}
## intersection() Method
Returns a new set with elements common to both sets. Syntax:
`[Link](set2)`.
Set1 = {1, 2, 3, 4}
Set2 = {3, 4, 5}
Result = [Link](set2)
Print(result) # Output: {3, 4}
Q12) Explain with example zip() Function
The `zip()` function in Python combines multiple iterables (like lists,
tuples, or strings) into an iterator of tuples, pairing elements by their
position. It stops at the shortest iterable's length and returns a zip object,
which can be converted to a list or tuple for use.
## Basic Syntax
`zip(*iterables)` takes any number of iterables and pairs corresponding
elements.
names = ['Alice', 'Bob', 'Charlie']
scores = [85, 90, 88]
zipped = zip(names, scores)
print(list(zipped)) # Output: [('Alice', 85), ('Bob', 90), ('Charlie', 88)]
```
## Multiple Iterables
Pairs elements from three or more iterables into tuples.
names = ['Alice', 'Bob']
ages = [25, 30]
cities = ['NYC', 'LA', 'Tokyo']
result = zip(names, ages, cities)
print(list(result)) # Output: [('Alice', 25, 'NYC'), ('Bob', 30, 'LA')]
## Unzipping
Use `zip(*)` to reverse the process, splitting tuples back into separate
iterables.
pairs = [('Alice', 85), ('Bob', 90)]
names, scores = zip(*pairs)
print(names) # Output: ('Alice', 'Bob')
print(scores) # Output: (85, 90)
```
Q13)Write a note on Traversing of Sets. Python
In Python, sets are unordered and unindexed collections,
which means you cannot access elements using indices
(like my_set[0] ). The primary and most common way to
traverse (iterate through) a set is using a for loop.
Key Points on Set Traversal
Unordered: The elements appear in an arbitrary order,
which may vary each time the code is run. The order is not
guaranteed to be the same as the insertion order.
Unindexed: Direct access via indexing or slicing is not
supported, and attempting to do so will raise
a TypeError .
Unique Elements: Traversal allows you to process each
unique item in the set exactly once.
Traversing using a for loop
The most Pythonic and efficient way to traverse a set is using a
simple for loop, which directly iterates over the elements.
Q14) what is regular expression in Python explain
various regular expression operations
8. a) Regular expressions in Python
Answer: A regular expression (regex) is a sequence of
characters that define a search pattern for text matching and
manipulation in Python, primarily using the re module.
Regular expressions are a powerful tool for tasks such as data
validation, parsing, and finding/replacing text based on
complex patterns rather than fixed strings.
Explanation of various regular expression operations:
Python's built-in re module provides several functions to
perform operations using regular expressions. Key operations
include:
[Link](): Scans through a string, looking for the first
location where the regex pattern produces a match. It
returns a match object if a match is found,
otherwise None.
[Link](): Checks for a match only at the beginning of
the string. It returns a match object if the pattern matches
the start of the string, otherwise None.
[Link](): Returns a list of all non-overlapping
matches of the pattern in the string.
[Link](): Splits the string by the occurrences of the
pattern. It returns a list containing the resulting
substrings.
[Link](): Finds all occurrences of the pattern in the string
and replaces them with a specified replacement string. It
returns the modified string.
[Link](): Compiles a regex pattern into a regular
expression object, which can be used for more efficient
matching operations when the same pattern is used
multiple times.
16) Explain Regular Expression with glob Module in
detail
Regular expressions (regex) and the glob module are both tools for
pattern matching, but they are distinct with different syntaxes and use
cases. The glob module finds file paths using simple shell-style wildcards,
while regular expressions use a more powerful, complex syntax for
general text manipulation.
Regular Expressions (Regex)
A regular expression is a specialized sequence of characters used to
define a search pattern for matching, locating, and managing text. They
are extremely powerful and can describe a full range of regular languages,
supporting complex operations like repetition and alternation (using the
pipe | symbol). In Python, regex functionality is provided by the built-
in re module.
Key regex features include:
Metacharacters like . (any single character), * (zero or more
occurrences of the preceding character/group), + (one or more),
and ? (zero or one).
Character classes using [] (e.g., [a-z] for any lowercase letter).
Groups using parentheses () to extract specific parts of a match.
The glob Module
The glob module in Python is used specifically to find all file pathnames
that match a specified pattern based on Unix shell rules. It is designed for
directory and file searching, not general text processing.
The glob module only uses a few, simpler special characters, known
as wildcards:
* : Matches zero or more characters within a single file path
segment (does not match path separators / ).
** : Matches any number of characters across multiple directory
levels when the recursive=True argument is set.
? : Matches exactly one character.
[] : Matches a single character within a range or set specified in the
brackets (e.g., [0-9] matches any digit).
Q16) Explain in brief Reading and Writing CSV Files
Reading and writing CSV (Comma-Separated Values) files
involves handling plain text data in rows and columns,
where commas separate values, making them easy to
import/export between applications like spreadsheets
and databases. Reading means opening the file, using a
program/library (like Python's module) to parse each comma-
separated line (record) into structured data (like lists or
dictionaries). Writing involves creating new rows, formatting
data with commas, and saving it to a file, often with a header
row for column names. [1, 2, 3, 4, 5, 6]
Reading CSVs
Open File: Open the file in read mode.
Parse Data: Use a CSV reader (e.g., in Python) to iterate
through rows.
Handle Data: Each row is typically a list of values
(strings) or a dictionary if using , with the header row
defining column names. [3, 5, 6]
Writing CSVs
Open File: Open a new or existing file in write mode.
Write Header: Write the column names as the first row,
separated by commas.
Write Data: For each record, format data into a comma-
separated string and write it as a new line. [3, 4, 5]
Key Concepts
Delimiter: The comma () separates values, but tabs or
semicolons can also be used (e.g., ).
Human-Readable: Simple text format viewable in any
text editor.
Data Transfer: Ideal for moving data between different
software (spreadsheets, databases, programming
languages). [2, 3, 4, 7]
Q17) What is Inheritance? Explain with example in
Python. short
Inheritance is a core concept in object-oriented programming that allows a
new child class (or subclass) to inherit properties (attributes) and
behaviors (methods) from an existing parent class (or superclass). This
promotes code reusability and creates an "is-a" relationship, e.g., a
"Dog is an Animal".
Example in Python
In this example, the Dog class inherits from the Animal class,
gaining the speak() method and name attribute, while also
defining its own unique bark() method.
python
# Parent Class (Superclass/Base Class)
class Animal:
def __init__(self, name):
[Link] = name
def speak(self):
return f"{[Link]} makes a generic sound."
# Child Class (Subclass/Derived Class)
class Dog(Animal):
def bark(self):
return "Woof! Woof!"
# Create an object of the child class
my_dog = Dog("Buddy")
# Access inherited attributes and methods
print(my_dog.name) # Output: Buddy
print(my_dog.speak()) # Output: Buddy makes a generic
sound.
# Access the child's specific method
print(my_dog.bark()) # Output: Woof! Woof!
The Dog class is defined with (Animal) in the class definition,
establishing the inheritance link. The super().__init__(name) call
(used when overriding the constructor) ensures the parent class's
attributes are properly initialized.
Q18) What is constructor method in Python? Explain
with example
A constructor method in Python is a special method used for
initializing an object's state (its attributes) when a new instance
of a class is created [1]. It is automatically called when you
create a new object.
The specific method name for a constructor in Python
is __init__ (note the double underscores on both sides).
Key Characteristics
Name: It is always named __unit__ [1].
Automatic Call: You do not call it explicitly; Python calls
it for you immediately after the object is created in
memory [1].
Purpose: Its primary role is to set the initial values of
instance variables and perform any other setup required
for the new object to be ready for use [1, 2].
self Parameter: The first parameter of
the __init__ method (by convention named self ) refers
to the newly created instance of the class itself, allowing
you to access and modify its attributes [2].
Example
Here is a short example demonstrating how to use
the __init__ method in a class:
python
class Dog:
# The constructor method
def __init__(self, name, age):
[Link] = name # Initialize the 'name'
attribute
[Link] = age # Initialize the 'age'
attribute
print(f"A new dog named {[Link]} has been
created!")
# A regular method
def bark(self):
Q18)
print(f"{[Link]} says Woof!")
# Creating new instances of the Dog class
automatically calls __init__
dog1 = Dog("Buddy", 3)
dog2 = Dog("Max", 5)
# Accessing attributes and methods
[Link]()
print(f"{[Link]} is {[Link]} years old.")
Output of the code above:
A new dog named Buddy has been created!
A new dog named Max has been created!
Buddy says Woof!
Max is 5 years old.
Q19)Explain brief Class Attributes versus Data
Attributes. Python
In Python, "data attributes" generally refer to instance
attributes, which hold data unique to each object, while class
attributes hold data that is shared by all instances of a class.
Class Attributes
Definition: Defined directly inside the class body, outside
of any methods (including __init__ ).
Scope & Access: They belong to the class itself and are
shared among all its instances. All objects refer to a single
copy of a class attribute. They can be accessed
using ClassName.attribute_name or [Link]
_name .
Use Case: Ideal for defining properties that should be the
same for every instance, such as a class constant or a
counter for the number of objects created.
Data (Instance) Attributes
Definition: Typically defined inside the __init__ method
using the self keyword (e.g., [Link] =
value ).
Scope & Access: They are specific to a particular
instance of the class (each object gets its own copy). They
are accessed using object.attribute_name .
Use Case: Used for properties that vary from one
instance to another and define the unique state of an
object, such as a person's name or age.
Q20) Explain Creating Objects in Python short
Objects in Python are instances of classes, created by calling
the class name like a function after defining the class with its
`__init__` constructor. This process instantiates the object and
initializes its attributes.
## Basic Syntax
Define a class with `__init__` to set attributes, then create the
object by passing arguments.
Class Person:
Def __init__(self, name, age):
[Link] = name
[Link] = age
# Create object
P1 = Person(“Alice”, 30)
Print([Link]) # Output: Alice
```
## Multiple Objects
One class produces many independent objects, each with its
own state.
P2 = Person(“Bob”, 25)
Print([Link]) # Output: 25