Q.
Difference between built-in function & User defined function
Answer: Built-in functions are predefined functions provided by the
programming language's library, while user-defined functions are
created by the programmer for specific tasks.
• Built-in functions (also known as library functions) are
embedded within the language and are readily available for use
without needing explicit definition by the user. They cover a wide
range of common tasks like mathematical operations or
input/output handling. Examples include print(), len(),
or sum() in Python.
• User-defined functions, in contrast, are defined by the
programmer to perform a specific, customized task. The user
writes the function definition, which typically involves using a
specific keyword (like def in Python). These functions allow for
code modularity and reusability, tailored to the specific needs of
a program.
Q. Write a short program on default parameters Positional parameters
Returning Value.
Here is a Python program demonstrating default parameters,
positional parameters, and returning a value from a ffunction.
Python
def calculate_area(length, width=10):
"""
Calculates the area of a rectangle.
Args:
length (int or float): The length of the rectangle (positional
parameter).
width (int or float, optional): The width of the rectangle.
Defaults to 10 if not provided (default parameter).
Returns:
int or float: The calculated area of the rectangle.
"""
area = length * width
return area
# Using positional parameters and default parameter
print(f"Area with length 5 and default width: {calculate_area(5)}")
# Overriding the default width with a positional argument
print(f"Area with length 5 and width 20: {calculate_area(5, 20)}")
# Using keyword arguments for clarity (still positional in order if not
specified)
print(f"Area with length 8 and width 15: {calculate_area(length=8,
width=15)}")
# Demonstrating a function returning None implicitly if no return
statement
def greet(name):
print(f"Hello, {name}!")
result = greet("Alice")
print(f"Result of greet function: {result}") # This will print None
Q. 3. Write short note on local and global scope
In programming, scope defines the region of a program where a
variable is accessible. The primary types are local and global scope,
which differ in where variables are declared, their accessibility, and
their lifetime.
Local Scope
• Definition: A variable declared inside a specific block of code,
typically within a function, loop, or conditional statement, has a
local scope.
• Accessibility: It is only accessible within that specific block or
function where it is defined. Code outside of this block cannot
access or modify it.
• Lifetime: Local variables are created when the function or block
is entered and are destroyed when the execution of that block
finishes. This promotes efficient memory use.
• Benefits: It helps in data encapsulation, prevents unintended
modification by other parts of the program, and allows for the
reuse of the same variable names in different functions without
conflict.
Global Scope
• Definition: A variable declared outside of any function or block,
usually at the top level of the program, has a global scope.
• Accessibility: It is accessible from anywhere within the program,
including inside all functions and blocks, unless a local variable
with the same name “shadows” it.
• Lifetime: Global variables persist in memory throughout the
entire execution of the program, from start to finish.
• Considerations: While convenient for sharing data across
multiple functions, excessive use of global variables can lead to
potential bugs and make code harder to debug and maintain due
to the risk of unintended side effects or modification from
different locations.
In summary, local scope provides isolation and organization, while
global scope offers broad accessibility. Good programming practice
generally recommends using local variables by default and using
global variables sparingly, only when necessary for shared data that
applies to the entire application.
Q. What is Modules and packages? ( PyPI python Package Index pip python
Package)
In Python, modules and packages are fundamental concepts for
organizing and structuring code.
A module is a single Python file containing Python code, such as
functions, classes, and variables. Modules allow you to logically
group related code and reuse it across different parts of your project
or in other projects. You can import modules into other Python files
using the import statement.
A package is a way to organize related modules into a hierarchical
directory structure. A package is essentially a directory containing
one or more module files and an __init__.py file (which can be empty).
The __init__.py file signifies that the directory should be treated as a
Python package. Packages provide a way to manage larger codebases
and avoid naming conflicts between modules.
PyPI (Python Package Index) is the official third-party software
repository for Python. It acts as a central hub where developers can
publish their Python packages for others to discover, download, and
use. Think of it as a vast library of pre-written Python code that you
can easily integrate into your own projects.
Pip is the standard package installer for Python. It is a command-line
tool that allows you to install, uninstall, and manage Python
packages from PyPI and other package indexes. When you use pip
install <package_name>, pip searches for the specified package on
PyPI (by default), downloads it, and installs it into your Python
environment, along with any necessary dependencies.
In summary:
• Modules: are individual Python files containing code.
• Packages: are directories that organize related modules
hierarchically.
• PyPI: is the central repository for publishing and finding Python
packages.
• Pip: is the tool used to install and manage Python packages,
typically from PyPI.
Q. How array use is created in NumPy and different functions like:
[Link]() [Link]() etc.
NumPy arrays, known as ndarray objects, are fundamental for
numerical computing in Python. They offer efficient storage and
operations for large datasets compared to standard Python lists.
Creating NumPy Arrays:
• [Link](): This is the most common way to create an array from
existing Python lists or tuples.
Python
Import numpy as np
# From a list
Arr_list = [Link]([1, 2, 3, 4, 5])
Print(f”Array from list: {arr_list}”)
# From a tuple
Arr_tuple = [Link]((6, 7, 8))
Print(f”Array from tuple: {arr_tuple}”)
# Multidimensional array from nested lists
Multi_dim_arr = [Link]([[1, 2], [3, 4]])
Print(f”Multidimensional array:\n{multi_dim_arr}”)
• [Link](): This function creates an array of a specified shape,
filled with zeros.
Python
Import numpy as np
# One-dimensional array of 5 zeros
Zeros_1d = [Link](5)
Print(f”Zeros 1D: {zeros_1d}”)
# Two-dimensional array (2 rows, 3 columns) of zeros
Zeros_2d = [Link]((2, 3))
Print(f”Zeros 2D:\n{zeros_2d}”)
# Specify data type (e.g., integer)
Zeros_int = [Link](3, dtype=int)
Print(f”Zeros as integers: {zeros_int}”)
• [Link](): Similar to [Link](), but creates an array filled with
ones.
Python
Import numpy as np
# One-dimensional array of 4 ones
Ones_1d = [Link](4)
Print(f”Ones 1D: {ones_1d}”)
# Two-dimensional array (3 rows, 2 columns) of ones
Ones_2d = [Link]((3, 2))
Print(f”Ones 2D:\n{ones_2d}”)
• [Link](): Creates an array of a given shape and data type, but
its initial content is random (uninitialized memory). This can be
faster than zeros() or ones() if you plan to fill the array
immediately.
Python
Import numpy as np
Empty_arr = [Link](3)
Print(f”Empty array (content is random): {empty_arr}”)
• [Link](): Creates an array with evenly spaced values within a
given interval (similar to Python’s range()).
Python
Import numpy as np
# Array from 0 to 4 (exclusive)
Range_arr = [Link](5)
Print(f”Arange (0-4): {range_arr}”)
# Array from 2 to 10 (exclusive) with a step of 2
Step_arr = [Link](2, 10, 2)
Print(f”Arange with step: {step_arr}”)
• [Link](): Creates an array with a specified number of
evenly spaced values over a given interval.
Python
Import numpy as np
# 5 evenly spaced values between 0 and 10 (inclusive)
Lin_space_arr = [Link](0, 10, num=5)
Print(f”Linspace: {lin_space_arr}”)
Q. what is Array Indexing and Slicing.
Array indexing and slicing are fundamental operations for accessing
and manipulating elements within data structures like arrays, lists, or
strings in programming.
1. Array Indexing:
Definition: Indexing refers to accessing a single, individual element
within an array or sequence by its specific position.
Mechanism: Elements are addressed using numerical indices,
which typically start from 0 for the first element.
Example (Python list):
Python
My_list = [10, 20, 30, 40, 50]
First_element = my_list[0] # Accesses the element at index 0 (value
10)
Third_element = my_list[2] # Accesses the element at index 2
(value 30)
Negative Indexing: Many languages also support negative indexing,
where -1 refers to the last element, -2 to the second-to-last, and so
on.
Python
Last_element = my_list[-1] # Accesses the last element (value 50)
2. Array Slicing:
Definition: Slicing involves extracting a contiguous portion or sub-
sequence from an array or sequence, rather than just a single
element.
• Mechanism: Slicing is typically performed by specifying a range
of indices using a start:stop:step syntax.
o Start: The index where the slice begins (inclusive). If
omitted, it defaults to the beginning of the sequence.
o Stop: The index where the slice ends (exclusive). If omitted,
it defaults to the end of the sequence.
o Step: The interval between elements in the slice. If omitted,
it defaults to 1.
• Example (Python list):
Python
My_list = [10, 20, 30, 40, 50, 60, 70]
Sub_list = my_list[1:4] # Extracts elements from index 1 up to
(but not including) index 4: [20, 30, 40]
First_three = my_list[:3] # Extracts the first three elements: [10,
20, 30]
Every_other = my_list[::2] # Extracts every other element: [10, 30,
50, 70]
• Negative Slicing: Negative indices can also be used in slicing to
define ranges relative to the end of the sequence.
Python
Last_two = my_list[-2:] # Extracts the last two elements: [60,
70]
In summary, indexing is for retrieving individual elements, while
slicing is for extracting sub-sequences or portions of an array.
[Link] a short note on array operation?
Array operations are fundamental actions performed on arrays,
which are data structures storing collections of elements of the same
data type in contiguous memory locations. These operations are
crucial for manipulating and managing data efficiently.
Common Array Operations:
• Traversal: Visiting each element in the array, typically for
processing or displaying its values. This often involves iterating
through the array using a loop.
• Insertion: Adding a new element to the array at a specific index.
This can require shifting existing elements to accommodate the
new value, potentially impacting performance in static arrays.
• Deletion: Removing an element from a specific index. Similar to
insertion, this might involve shifting elements to maintain
contiguity and can be performance-intensive in static arrays.
• Searching: Locating a specific element within the array and
returning its index or indicating its absence. Common search
algorithms include linear search and binary search (for sorted
arrays).
• Updating/Modification: Changing the value of an existing
element at a particular index. This is a direct operation as the
memory location is known.
• Sorting: Arranging the elements of the array in a specific order
(ascending or descending). Various sorting algorithms exist,
each with different time and space complexities.
• Accessing: Retrieving the value of an element at a given index.
Due to contiguous memory allocation, this is a highly efficient,
constant-time operation.
These operations form the basis for many algorithms and are
essential for effective data management in programming.
Q. What is linear algebra with Numpy.
Linear algebra with NumPy means using Python’s powerful
[Link] module to perform mathematical operations on vectors
and matrices, enabling efficient tasks like solving systems of
equations, finding determinants/inverses, matrix multiplication (dot
products), eigenvalues, and transformations, which are fundamental
in data science, machine learning, and graphics. NumPy arrays serve
as efficient representations for vectors (1D arrays) and matrices (2D
arrays), making complex linear algebra accessible and fast.
Key Concepts & Functions
• Vectors & Matrices: Represented by 1D and 2D [Link].
• [Link] Module: The core for linear algebra functions.
• Products: [Link]() (matrix/vector product), [Link](), [Link]().
• Matrix Properties: [Link]() (determinant), [Link]()
(inverse), [Link].matrix_rank(), [Link]() (trace).
• Eigenvalue Problems: [Link]() (eigenvalues/vectors).
• Solving Linear Systems: [Link]() for \(Ax=b\).
• Transposition: array.T attribute.
Python
Import numpy as np
# Creating vectors & matrices
V = [Link]([1, 2, 3]) # Vector
A = [Link]([[1, 2], [3, 4]]) # Matrix
# Matrix Multiplication (Dot Product)
B = [Link]([[5, 6], [7, 8]])
Print([Link](A, B))
# Finding Determinant
Print([Link](A))
# Solving Linear Equations (Ax = b)
A = [Link]([[1, 1], [1, -1]]) # Coefficients
B = [Link]([4, 0]) # Constants (x + y = 4, x – y = 0)
X = [Link](a, b)
Print(x) # Output: [2., 2.] (x=2, y=2)
Why Use NumPy?
• Efficiency: Leverages optimized C/Fortran libraries
(BLAS/LAPACK) for speed.
• Foundation: Powers many other scientific libraries like Pandas,
Scikit-learn, and TensorFlow.
• Applications: Essential for data analysis (SVD, normalization),
signal processing (FFT), and computer graphics
(transformations).
Q. what is broadcasting
In Python, specifically within the NumPy library, broadcasting refers
to a set of rules that allow NumPy to perform operations on arrays of
different shapes and sizes. It enables element-wise operations
between arrays that would otherwise be incompatible due to their
differing dimensions, without requiring explicit loops or making
unnecessary copies of data.
Here’s a breakdown of how broadcasting works:
Shape Compatibility Check: NumPy compares the shapes of the two
arrays involved in an operation, starting from the trailing (rightmost)
dimensions.
Dimension Matching Rules:
• Equal Dimensions: If the dimensions are equal, they are
considered compatible.
• Dimension of One: If one of the dimensions is 1, it is “stretched”
or “broadcast” to match the size of the other dimension. This
effectively means the single value in that dimension is repeated
to match the larger dimension.
• Padding with Ones: If the arrays have a different number of
dimensions, the shape of the array with fewer dimensions is
padded with ones on its leading (left) side until both arrays have
the same number of dimensions.
• Operation Execution: If the shapes are compatible according to
these rules, the operation is performed element-wise, with the
smaller array effectively being “broadcast” across the larger
one. If the shapes are not compatible, a ValueError is raised.
Example:
Python
Import numpy as np
A = [Link]([1, 2, 3]) # Shape (3,)
B=5 # Scalar (effectively shape (1,))
Result = a * b
Print(result)
In this example, the scalar b is broadcast across the array a.
Conceptually, b is treated as [Link]([5, 5, 5]) for the multiplication,
resulting in [5, 10, 15].
Broadcasting is a powerful feature that significantly simplifies
numerical computations in NumPy, making code more concise and
often more efficient than explicit looping.
Q. What is Exception handling?
Exception handling in Python is a mechanism for gracefully managing
runtime errors or unexpected events that disrupt the normal flow of a
program. When an error occurs during program execution, Python
raises an exception, which is an object representing the error. If this
exception is not handled, the program will terminate abruptly.
Python’s exception handling system allows developers to anticipate
potential errors and define how the program should respond to them,
preventing crashes and enhancing robustness. This is primarily
achieved through the use of try, except, else, and finally blocks:
• Try block: This block encloses the code that might potentially
raise an exception.
• Except block: If an exception occurs within the corresponding
try block, the except block catches it and executes the code
defined to handle that specific exception. You can specify
different except blocks to handle different types of exceptions.
• Else block: This optional block executes only if no exceptions
are raised within the try block.
• Finally block: This optional block always executes, regardless of
whether an exception occurred or was handled. It’s typically
used for cleanup operations, such as closing files or releasing
resources.
Example:
Python
Try:
Num1 = int(input(“Enter a number: “))
Num2 = int(input(“Enter another number: “))
Result = num1 / num2
Except ZeroDivisionError:
Print(“Error: Cannot divide by zero!”)
Except ValueError:
Print(“Error: Invalid input. Please enter a valid number.”)
Else:
Print(f”The result of the division is: {result}”)
Finally:
Print(“Execution complete.”)
In this example, the try block attempts to perform a division. If a
ZeroDivisionError occurs (division by zero), the first except block
handles it. If a ValueError occurs (invalid input for int()), the second
except block handles it. If no exceptions occur, the else block prints
the result. The finally block always executes, printing “Execution
complete.”
Q. What are the different types of errors?
Python programs can encounter various types of errors, broadly
categorized into three main groups:
• Syntax Errors: These errors occur when the Python interpreter
encounters code that does not conform to the language’s
grammatical rules. They are detected during the parsing phase,
before the code even begins to execute. Examples include
missing colons, incorrect indentation, or misplaced keywords.
Python
# Example of a SyntaxError (missing colon)
If True
Print(“Hello”)
• Runtime Errors (Exceptions): These errors occur during the
execution of a program, even if the code is syntactically correct.
They represent unexpected situations or conditions that prevent
the program from continuing its normal flow. Python provides a
mechanism called “exception handling” (using try-except
blocks) to manage and recover from these errors. Common
runtime errors include:
o NameError: Occurs when a variable or function is referenced
before it has been defined.
o TypeError: Occurs when an operation is performed on an
object of an inappropriate type.
o ValueError: Occurs when a function receives an argument of
the correct type but an invalid value.
o IndexError: Occurs when attempting to access an element of
a sequence (like a list or tuple) using an invalid index.
o KeyError: Occurs when attempting to access a non-existent
key in a dictionary.
o ZeroDivisionError: Occurs when attempting to divide a
number by zero.
o AttributeError: Occurs when attempting to access an attribute
or method that does not exist for an object.
o FileNotFoundError: Occurs when attempting to open a file
that does not exist.
Python
# Example of a NameError
Print(undefined_variable)
# Example of a TypeError
“hello” + 5
• Logical Errors: These are the most challenging errors to detect
as they do not cause the program to crash or raise an exception.
Instead, the program runs but produces incorrect or unexpected
results due to flaws in the program’s logic. Identifying logical
errors often requires careful testing and debugging.
Python
# Example of a logical error (incorrect calculation)
Def calculate_average(a, b):
Return a + b / 2 # Should be (a + b) / 2
Q. What are different types of Exception?
Python provides a comprehensive set of built-in exceptions to handle
various error conditions that can arise during program execution.
These exceptions are organized in a hierarchy, with BaseException at
the root, and Exception as the base for most common, non-system-
exiting exceptions.
Here are some common types of exceptions In Python:
1. Syntax Errors:
• SyntaxError: Raised by the parser when a syntax error is
encountered in the code, such as missing colons, unmatched
parentheses, or incorrect keywords.
• IndentationError: A subclass of SyntaxError, specifically raised
for incorrect indentation.
2. Runtime Errors (Exceptions):
• NameError: Raised when a local or global variable name is not
found in the current scope.
• TypeError: Raised when an operation or function is applied to an
object of an inappropriate type.
• ValueError: Raised when a built-in operation or function receives
an argument that has the correct type but an inappropriate
value.
• ZeroDivisionError: Raised when attempting to divide a number
by zero.
• IndexError: Raised when a sequence index is out of range.
• KeyError: Raised when a dictionary key is not found.
• AttributeError: Raised when an attribute reference or
assignment fails (e.g., trying to access a non-existent attribute
of an object).
• ImportError: Raised when an import statement fails to find a
module or when a name within a module cannot be found.
• FileNotFoundError: A subclass of OSError, raised when a file or
directory is requested but does not exist.
• IOError: Raised when an input/output operation fails, such as
reading or writing to a file.
• AssertionError: Raised when an assert statement fails,
indicating a condition that was expected to be true is false.
• MemoryError: Raised when an operation runs out of memory.
• OverflowError: Raised when the result of an arithmetic operation
is too large to be represented.
• KeyboardInterrupt: Raised when the user hits the interrupt key
(e.g., Ctrl+C), interrupting the program’s execution.
• SystemExit: Raised by the [Link]() function, used to exit the
Python interpreter.
User-Defined Exceptions:
• Python also allows users to define their own custom exceptions
by creating new classes that inherit from the Exception class or
any of its subclasses. This allows for more specific error
handling tailored to particular application logic.
Example of a custom exception:
Python
Class MyCustomError(Exception):
Pass
Def example_function(value):
If value < 0:
Raise MyCustomError(“Value cannot be negative”)
Try:
Example_function(-5)
Except MyCustomError as e:
Print(f”Caught a custom error: {e}”)
Q. What is text & Binary file.
In Python, files are broadly categorized into two types: text files and binary
files. The distinction lies in how the data is stored and interpreted.
Text Files:
• Human-Readable: Text files store data as sequences of human-
readable characters, typically encoded using schemes like
ASCII or UTF-8.
• Line Endings: Each line in a text file is usually terminated by a
special character or sequence of characters representing a
newline (e.g., \n on Unix-like systems, \r\n on Windows). Python
handles these conversions automatically when working in text
mode.
• Opened in Text Mode: When you open a file in Python without
specifying ‘b’ for binary mode (e.g., ‘r’, ‘w’, ‘a’), it defaults to text
mode. You can explicitly specify text mode with ‘rt’, ‘wt’, etc.
• Examples: Source code files (.py), configuration files (.ini, .conf),
log files (.log), CSV files (.csv), JSON files (.json).
Binary Files:
• Machine-Readable: Binary files store data in its raw, binary
format, directly as sequences of bytes (0s and 1s). This data is
not intended for direct human interpretation and often requires
specific programs to be understood.
• No Line Endings: Binary files do not have the concept of line
endings in the same way text files do. Data is stored
contiguously or in application-defined structures.
• Opened in Binary Mode: To work with binary files in Python, you
must explicitly open them in binary mode by including ‘b’ in the
mode string (e.g., ‘rb’, ‘wb’, ‘ab’).
• Examples: Image files (.jpg, .png), audio files (.mp3, .wav), video
files (.mp4), executable files (.exe), compressed archives (.zip),
serialized data (e.g., Python pickle files).
Key Differences in Python:
• Data Type: When reading from a text file, Python returns string
objects. When reading from a binary file, Python returns byte
objects.
• Encoding/Decoding: Text files involve encoding when writing
and decoding when reading to convert between character
representations and bytes. Binary files bypass this step, working
directly with bytes.
• Line Ending Handling: Text mode automatically handles
platform-specific line ending conversions. Binary mode
performs no such conversions.
Example of opening files in Python:
Python
# Opening a text file for writing
With open(‘my_text_file.txt’, ‘w’) as f:
[Link](‘This is a text string.\n’)
[Link](‘Another line of text.’)
# Opening a binary file for writing
With open(‘my_binary_file.bin’, ‘wb’) as f:
[Link](b’\x01\x02\x03\x04’) # Writing raw bytes
[Link](bytes([5, 6, 7])) # Converting a list of integers to bytes