UNIT 1
1.Write in brief about the applications and features of Python.
Python is a popular programming language that is easy to learn and widely used in various
fields.
Web Development: Python is used for web development through frameworks like Django and
Flask, allowing you to create dynamic websites and web applications.
Data Science: Python is a go-to language for data analysis and visualization. Libraries like
NumPy, Pandas, and Matplotlib are commonly used to process and analyze data.
Machine Learning and Artificial Intelligence: Python has a rich ecosystem for machine
learning and AI, with libraries like TensorFlow and PyTorch for building and training models.
Key Features of Python:
● Easy to Learn: Python has a simple and readable syntax, making it beginner-friendly.
● Open-Source: Python is free to use, and its open-source nature means a vast
community contributes to its development.
● Cross-Platform: Python runs on various operating systems, making it versatile and
accessible.
● Large Standard Library: Python comes with a rich standard library that simplifies
many common programming tasks.
● Dynamic Typing: Python is dynamically typed, meaning you don't need to declare
variable types, making coding more flexible.
● Interpreted Language: Python is an interpreted language, allowing for quick code
execution without the need for compilation.
● Great Community Support: The Python community is vast, offering resources,
forums, and libraries to help you learn and solve problems.
● High-level Language: Python abstracts many complex programming details, making it
easier to focus on problem-solving.
2. Write the rules for choosing names of variables.
● No Spaces: Variable names cannot contain spaces.
● Start with a Letter or Underscore: Variable names must start with a letter (a-z or A-Z)
or an underscore (_).
● Use Alphanumeric Characters and Underscores: Variable names can consist of letters,
numbers, and underscores.
● Avoid Keywords: Do not use reserved words or keywords.
● No Special Characters: Avoid using special characters like $, %, or #.
● No Leading Numbers: Variable names should not start with a number.
3. Explain Assignment operators in python with appropriate examples.
Certainly, here are the assignment operators in Python with brief explanations:
● = (Assignment): Assigns a value to a variable.
● += (Addition Assignment): Adds a value to the variable and updates it.
● -= (Subtraction Assignment): Subtracts a value from the variable and updates it.
● *= (Multiplication Assignment): Multiplies the variable by a value and updates it.
● /= (Division Assignment): Divides the variable by a value and updates it.
● %= (Modulus Assignment): Computes the remainder and updates the variable.
● **= (Exponentiation Assignment): Raises the variable to a power and updates it.
● //= (Floor Division Assignment): Performs integer division and updates the variable.
4. Explain about different Logical operators in python with appropriate examples.
Logical Operator Description Example Result
and Returns True if both operands are True. x and y False
or Returns True if at least one operand is True. a or b True
not Returns the opposite boolean value of the operand. not flag False
These logical operators are fundamental for making decisions and controlling the flow of
your Python code.
5. Explain about different Relational operators in python with appropriate examples.
certainly! Here's a table summarising the different relational operators in Python with
explanations and examples:
Relational Operator Description Example Result
== Equal to x == y True
!= Not equal to a != b True
> Greater than m>n True
< Less than p<q True
>= Greater than or equal to r >= s True
<= Less than or equal to u <= v True
These relational operators allow you to compare values and make decisions based on the
relationships between them in your Python code.
6. Explain about Membership operators in python with appropriate examples.
Membership operators in Python are used to check if a particular value exists within a
sequence, such as a string, list, or tuple. There are two main membership operators: in and not
in. Here's a table with explanations and examples for each of these operators:
Membership Operator Description Example Result
in Returns True if a value is found in the sequence. 'a' in 'apple' True
Returns True if a value is not found in the
not in 'b' not in 'apple' True
sequence.
7. Explain about Identity operators in python with appropriate examples.
Identity operators in Python are used to compare the memory locations of two objects to
determine if they are the same object or not. There are two main identity operators: is and is
not. Here's a table with explanations and examples for each of these operators:
Identity Operator Description Example Result
is Returns True if both variables reference the same object. x is y True
is not Returns True if both variables reference different objects. a is not b True
8. Explain about Arithmetic operators in python with appropriate examples.
Result
Arithmetic Operator Description Example
+ Addition 5+3 8
- Subtraction 10 - 4 6
* Multiplication 6*7 42
/ Division 12 / 3 4.0
% Modulus (Remainder) 17 % 4 1
** Exponentiation 2 ** 3 8
// Floor Division (Integer Division) 19 // 5 3
Arithmetic operators in Python are used for performing basic mathematical operations on
numeric values. Here's a table with explanations and examples for the common arithmetic
operators:
9. Evaluate the given expression and Justify output. a=10 + 9 * 4 / 2 - 3 + 1
b=10 + 9 - 4 / (2 - 3) + 1
c=10 + 9 / (4 / 2 - 3) + 1
print(a) print(b) print(c)
Expression a = 10 + 9 * 4 / 2 - 3 + 1: So, a = 26.
Expression b = 10 + 9 - 4 / (2 - 3) + 1: So, b = 16.
Expression c = 10 + 9 / (4 / 2 - 3) + 1: So, c = 2.
10. What is an identifier (variable)? What are the rules to construct identifier
(variable)?
Classify the following as valid/invalid Identifiers. i) num2 ii) $num1 iii) +add iv) a_2 v)
199_space vi) _apple vii)#12
An identifier (variable) in programming is a name given to a specific memory location to
store data. It's used to uniquely identify variables, functions, classes, modules, or other
objects in your code. Identifiers are an essential part of coding and must adhere to certain
rules in most programming languages, including Python. Here are the general rules to
construct valid identifiers in Python:
Rules for constructing identifiers (variables) in Python:
1. Identifiers must start with a letter (a-z, A-Z) or an underscore (_).
2. The remaining characters in an identifier can be letters, underscores, or digits (0-9).
3. Identifiers are case-sensitive, meaning `myVar` and `myvar` are considered different
identifiers.
4. Identifiers should not be the same as reserved keywords in Python (e.g., `if`, `while`, `for`,
etc.).
5. Python supports Unicode characters in identifiers, but it's recommended to use ASCII
characters for compatibility and readability.
6. Avoid using special characters like $, %, +, or # in identifiers.
Now, let's classify the given identifiers as valid or invalid according to these rules:
i) `num2` - Valid
- It starts with a letter and includes digits, which is allowed.
ii) `$num1` - Invalid
- It starts with a special character ('$'), which is not allowed.
iii) `+add` - Invalid
- It starts with a special character ('+'), which is not allowed.
iv) `a_2` - Valid
- It starts with a letter and includes an underscore, which is allowed.
v) `199_space` -
- It starts with a digit, which is not allowed.
vi) `_apple` - Valid
- It starts with an underscore and includes letters, which is allowed.
vii) `#12` - Invalid
- It starts with a special character ('#'), which is not allowed.
So, the valid identifiers are: `num2`, `a_2`, and `_apple`. The invalid identifiers are: `$num1`,
`+add`, `199_space`, and `#12`.
UNIT 2
1. Explain different loops available in python with syntax and suitable examples
A.For Loop:
● Definition: A for loop is used to iterate over a sequence (such as a list, tuple, or string)
or other iterable objects. It executes a block of code for each item in the sequence.
● Example:
for item in sequence:
# Code to be executed for each item
B.While Loop:
● Definition: A while loop is used to repeatedly execute a block of code as long as a
specified condition is true. It may run zero or more times.
● Example:
while condition:
# Code to be executed while the condition is true
C.Do-While Loop (Simulated in Python with a while loop):
● Definition: A do-while loop is similar to a while loop but guarantees that the loop body
will execute at least once before checking the condition. In Python, it's simulated
using a while loop with a conditional break.
● Example:
while True:
# Code to be executed at least once
if condition:
Break
2. Illustrate the different types of conditional branching statements available in Python with
suitable example
A.if Statement:
● Definition: The if statement is used to execute a block of code if a specified condition
is True.
● Example:
x = 10
if x > 5:
print("x is greater than 5")
B.elif Statement (optional):
● Definition: The elif statement is used to check multiple conditions if the previous if
condition is False. It allows you to test multiple conditions sequentially.
● Example:
x=3
if x > 5:
print("x is greater than 5")
elif x == 5:
print("x is equal to 5")
else:
print("x is less than 5")
C.else Statement (optional):
● Definition: The else statement is used to execute a block of code if none of the
previous conditions in the if and elif statements is True.
● Example:
x=5
if x > 5:
print("x is greater than 5")
elif x == 5:
print("x is equal to 5")
else:
print("x is less than 5")
3. Illustrate the different types of control flow statements available in Python with
flowcharts
A.Conditional Statements (if, elif, else):
● if Statement:
● Definition: The if statement is used to execute a block of code if a specified
condition is True.
elif Statement (Optional):
● Definition: The elif statement is used to check multiple conditions if the previous if or
elif conditions are False.
else Statement (Optional):
● Definition: The else statement is used to execute a block of code if none of the
previous conditions is True.
B.Loop Statements (for, while):
● for Loop:
● Definition: The for loop is used to iterate over a sequence and execute a block
of code for each item in the sequence.
# Code to execute for each item in the sequen
● while Loop:
● Definition: The while loop is used to repeatedly execute a block of code as long
as a specified condition is True.
4. Explain the range() function with example.
The range() function in Python is used to generate a sequence of numbers, typically for use in
for loops. It creates a range object that represents a sequence of numbers within a specified
range. The basic syntax of the range() function is
range([start], stop[, step])
● start (optional) is the starting value of the sequence (default is 0).
● stop is the ending value of the sequence (exclusive).
● step (optional) is the increment between numbers (default is 1).
Example:
for i in range(5): # Generates numbers from 0 to 4 (default start and step)
print(i)
UNIT 3
1.Explain the different string functions available in Python with examples
String Function Description Example Result
len() Returns the length of a string. len("Hello, World!") 13
str() Converts a value into a string. str(42) "42"
upper() Converts a string to uppercase. "Python".upper() "PYTHON"
lower() Converts a string to lowercase. "PYTHON".lower() "python"
Removes leading and trailing
strip() " Hello, World! ".strip() "Hello, World!"
whitespace.
Replaces a substring with another
replace() "Hello, World!".replace("Hello", "Hi") "Hi, World!"
substring.
Splits a string into a list of
split() "apple, banana, cherry".split(", ") ["apple", "banana", "cherry"]
substrings.
Joins a list of strings into a single
join() ", ".join(["apple", "banana", "cherry"]) "apple, banana, cherry"
string.
2.What is the difference between list and tuples in Python?
Lists (Mutable):
● Lists are mutable, meaning you can add, remove, or modify elements after creation.
● They are defined using square brackets [].
● Lists are typically used when you need a collection of items that may change during
the program, such as a list of tasks or items in a shopping cart.
● Lists have a slightly higher memory consumption and may have lower performance
due to their mutability.
Tuples (Immutable):
● Tuples are immutable, so once you define their elements, you cannot modify them.
● They are defined using parentheses ().
● Tuples are used when you need a collection of items that should remain constant and
not be altered, like coordinates or configurations.
● Tuples are more memory-efficient and may have slightly better performance compared
to lists.
3. What are the different operations that can be performed on a list? Explain with
examples
Various operations can be performed on lists in Python. Here are some common list
operations with brief explanations and examples:
Appending Elements:
● Add an element to the end of the list.
my_list = [1, 2, 3]
my_list.append(4)
Inserting Elements:
● Insert an element at a specific position.
my_list = [1, 2, 3]
my_list.insert(1, 4) # Inserts 4 at index 1
Removing Elements:
● Remove elements by value or index.
my_list = [1, 2, 3, 4]
my_list.remove(2) # Removes element with value 2
my_list.pop(1) # Removes element at index 1 (returns 3)
Slicing and Indexing:
● Access and manipulate elements using indices and slices.
my_list = [1, 2, 3, 4, 5]
my_list[2] # Access element at index 2 (value 3)
my_list[1:4] # Slice elements from index 1 to 3 (result: [2, 3, 4])
Sorting:
● Sort elements in ascending or descending order.
my_list = [3, 1, 2]
my_list.sort() # Sort in ascending order
my_list.sort(reverse=True) # Sort in descending order
Finding Length:
● Get the length (number of elements) in a list.
my_list = [1, 2, 3, 4]
length = len(my_list) # Result: 4
4. Explain the following list methods with an example. a) append() b) extend() c) insert()
d) index() e) pop() f) sort()
a) append():
● append() adds an element to the end of a list.
● Example:
my_list = [1, 2, 3]
my_list.append(4) # Result: [1, 2, 3, 4]
b) extend():
● extend() appends the elements of an iterable (e.g., another list) to the end of the list.
● Example:
my_list = [1, 2, 3]
other_list = [4, 5]
my_list.extend(other_list) # Result: [1, 2, 3, 4, 5]
c) insert():
● insert() inserts an element at a specific position in the list.
● Example:
my_list = [1, 2, 3]
my_list.insert(1, 4) # Inserts 4 at index 1; Result: [1, 4, 2, 3]
d) index():
● index() returns the index of the first occurrence of a specified element in the list.
● Example:
my_list = [1, 2, 3, 2]
index = my_list.index(2) # Result: 1 (index of the first 2)
e) pop():
● pop() removes and returns the element at a specific index.
● Example:
my_list = [1, 2, 3, 4]
popped = my_list.pop(2) # Removes element at index 2 (value 3) and returns it
f) sort():
● sort() arranges the list's elements in ascending order. Use reverse=True for descending
order.
● Example:
my_list = [3, 1, 2]
my_list.sort() # Sorts in ascending order; Result: [1, 2, 3]
5. Write in brief about Tuple in python. Write operations with suitable examples.
A tuple in Python is an ordered, immutable, and indexed collection of elements. Tuples are
defined using parentheses ()
my_tuple = (1, 2, 3, 4, 5)
Operations on Tuples:
Accessing Elements:
● You can access elements by index, just like in lists.
first_element = my_tuple[0] # Accesses the first element (value 1)
Slicing:
● You can slice tuples to extract a subset of elements.
sliced_tuple = my_tuple[1:4] # Slices elements from index 1 to 3 (result: (2, 3, 4))
Length:
● Determine the number of elements in a tuple using len().
length = len(my_tuple) # Result: 5
Concatenation:
● Combine two or more tuples using the + operator.
new_tuple = my_tuple + (6, 7) # Concatenates two tuples
Searching for an Element:
● Check if an element exists in the tuple using the in keyword.
exists = 3 in my_tuple # Checks if 3 exists in the tuple (result: True)
6. Write in brief about Set in python. Write operations with suitable examples.
A set in Python is an unordered collection of unique elements. Sets are defined using curly
braces {} or the set() constructor
Adding Elements:
● You can add elements to a set using the add() method.
my_set.add(6) # Adds the element 6 to the set
Removing Elements:
● Remove an element from a set using the remove() method.
my_set.remove(3) # Removes the element 3 from the set
Union of Sets:
● Create a new set that contains all unique elements from multiple sets.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2) # Creates a set containing {1, 2, 3, 4, 5}
Intersection of Sets:
● Create a new set that contains elements common to multiple sets.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
intersection_set = set1.intersection(set2) # Creates a set containing {3}
Difference of Sets:
● Create a new set with elements from one set that are not in another.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
difference_set = set1.difference(set2) # Creates a set containing {1, 2}
Checking for Existence:
● Check if an element exists in a set using the in keyword.
exists = 3 in my_set # Checks if 3 exists in the set (result: True)
7. Write in brief about Dictionary in python. Write operations with suitable examples.
A dictionary in Python is an unordered collection of key-value pairs. Dictionaries are defined
using curly braces {} and have a unique key for each value.
my_dict = {'name': 'Alice', 'age': 30, 'city': 'New York'}
Accessing Values:
● You can access values in a dictionary using their keys
name = my_dict['name'] # Access the value associated with the key 'name'
Modifying Values:
● You can modify the value associated with a key in a dictionary.
my_dict['age'] = 31 # Update the 'age' value to 31
Adding Key-Value Pairs:
● You can add new key-value pairs to a dictionary.
my_dict['gender'] = 'Female' # Add a new key 'gender' with the value 'Female'
Removing Key-Value Pairs:
● You can remove a key-value pair using the pop() method.
removed_value = my_dict.pop('city') # Remove and return the value associated with 'city'
Checking for Existence:
● Check if a key exists in the dictionary using the in keyword.
exists = 'name' in my_dict # Checks if 'name' is a key in the dictionary (result: True)
8. Explain different modes of file handling.
Read Mode ('r'):
● Used to read data from an existing file.
● It starts reading from the beginning of the file.
Write Mode ('w'):
● Used to create a new file or overwrite an existing file.
● Be careful, as it erases the existing content.
Append Mode ('a'):
● Used to add data to an existing file.
● It starts writing at the end of the file.
Binary Read Mode ('rb'):
● Used to read binary data from a file.
● Useful for non-text data like images or executables.
Binary Write Mode ('wb'):
● Used to write binary data to a file.
● Great for saving non-text files like images.
Text Read Mode with Encoding ('r', 'r+', 'w+', 'a+'):
● Used for reading and writing text data with a specific character encoding.
● Encoding is important for handling different character sets.
File Truncation ('x'):
● Used to create a new file, but it will fail if the file already exists.
● Prevents overwriting existing data accidentally.
Read and Write Mode ('r+'):
● Used for both reading and writing data.
● Allows you to edit and update the file's content.
Append and Read Mode ('a+'):
● Used for both appending and reading data.
● Great for adding new information to an existing file and checking its content.
UNIT 4
1. Explain about functions with suitable examples or
A.Predefined (Built-in) Functions:
● Definition: Functions provided by Python's standard library for various tasks.
● Examples: print(), len(), input(), max(), min()
B.User-Defined Functions:
Definition: Functions created by programmers to perform specific tasks.
Example:
def add(a, b):
return a + b
C.Recursive Functions:
● Definition: Functions that call themselves to solve a problem.
● Example:
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n - 1)
D.Lambda Functions (Anonymous Functions):
● Definition: Small, unnamed functions defined using the lambda keyword.
● Example:
double = lambda x: x * 2
2.What is a function? How to define a function in python? Write a program using
function to find out the given number is even or odd.
A function is a reusable block of code that performs a specific task. In Python, you can define
a function using the def keyword, followed by the function name and its parameters. Here's a
program to find out if a given number is even or odd using a function:
def is_even_or_odd(number):
if number % 2 == 0:
return "Even"
else:
return "Odd"
num = 7
result = is_even_or_odd(num)
print(f"The number {num} is {result}.")
In this program:
● We define a function is_even_or_odd that takes a parameter number.
● Inside the function, we check if the number is even or odd.
● The function returns either "Even" or "Odd" based on the condition.
● We call the function with a number (e.g., num = 7) and print the result.
3. Write about the concept of scope of a variable in a function.(Global and Local
variables)
In Python, the scope of a variable refers to where in the code that variable can be accessed or
modified. There are two main types of variable scope:
A.Global Variables:
● Variables declared outside of any function are considered global.
● They can be accessed and modified from anywhere in the code.
Example:
global_var = 10
def my_function():
print(global_var) # Accessing the global variable
my_function()
B.Local Variables:
● Variables declared inside a function are considered local to that function.
● They can only be accessed and modified within the function where they are defined.
● Example:
def my_function():
local_var = 5 # Local variable
my_function()
# print(local_var) # This would result in an error, as local_var is not accessible here.
4. Write about different types of arguments in a function
Positional Arguments:
● These are the most common type of arguments.
● The values are passed in the order in which parameters are defined in the function.
● Example:
def greet(name, age):
print(f"Hello, {name}! You are {age} years old.")
greet("Alice", 30)
Keyword Arguments:
● Values are passed by specifying the parameter names, regardless of their order.
● This provides clarity and can make the code more readable.
● Example:
def greet(name, age):
print(f"Hello, {name}! You are {age} years old.")
greet(age=30, name="Bob")
Default Arguments:
● Parameters in the function definition can have default values.
● If a value is not provided, the default value is used.
● Example:
def greet(name, age=25):
print(f"Hello, {name}! You are {age} years old.")
greet("Charlie") # Age defaults to 25
Variable-Length Arguments (Arbitrary Arguments):
● Functions can accept a variable number of arguments.
● These are specified using *args and **kwargs for positional and keyword arguments,
respectively.
● Example:
def add(*numbers):
total = sum(numbers)
return total
result = add(1, 2, 3, 4) # Accepts any number of positional arguments
Keyword-Only Arguments:
● Arguments that can only be passed using their parameter names.
● These are specified after a single asterisk (*).
● Example:
def greet(name, *, age):
print(f"Hello, {name}! You are {age} years old.")
greet("David", age=35)
5. Explain lambda function with example.
A lambda function in Python, also known as an anonymous function, is a small, one-line
function that does not have a name. It is defined using the lambda keyword and can take
multiple arguments but can only contain a single expression. Lambda functions are often used
for short, simple operations. Here's an example:
# Lambda function to calculate the square of a number
square = lambda x: x ** 2
# Using the lambda function
result = square(5) # Result: 25
In this example:
● We define a lambda function square that takes one argument x and calculates the
square of x.
● We use the lambda function to calculate the square of the number 5 and store the
result in the result variable.
6. Explain Recursion function with example.
A recursive function in Python is a function that calls itself to solve a problem. It's a powerful
technique used when a problem can be broken down into smaller, similar sub-problems.
Here's an example of a recursive function to calculate the factorial of a number:
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
result = factorial(5) # Calculates 5! (5 factorial)
When calling factorial(5), it calculates 5! (5 factorial) by breaking it down into smaller
sub-problems and finally returns the result, which is 120.
7. How to create a module and use it in a python program explain with an example.
Step 1: Create the Module
Create a Python script with functions or variables you want to use as a module. Save it
with a .py extension. For example, let's create a module named mymodule.py with a
function.
Example (mymodule.py):
def greet(name):
return f"Hello, {name}!"
Step 2: Use the Module in a Python Program
In another Python script, import the module using the import statement. You don't need
to include the .py extension.
Example (main.py):
import mymodule
result = mymodule.greet("Alice")
print(result) # Output: "Hello, Alice!"
Step 3: Run the Program
Run the main script (main.py), and it can access the functions or variables from the
module (mymodule.py).
UNIT 5
1. What is NumPy array? Why we use NumPy? Explain different types of array
with example
NumPy stands for "Numerical Python" and is a fundamental library in Python for
numerical and mathematical operations. It provides support for arrays and matrices,
making it easier to work with large datasets
NumPy Array:
● A NumPy array is a multi-dimensional, homogeneous, and highly efficient data
structure for storing and manipulating large datasets.
● NumPy arrays are more memory-efficient and faster than Python lists for numerical
operations.
Why We Use NumPy:
● NumPy arrays are optimized for numerical operations and are significantly faster than
Python lists for tasks involving large datasets.
● NumPy simplifies complex mathematical computations, making code more concise
and readable.
Types of NumPy Arrays:
1-D Array:
● A 1-dimensional array is like a regular list of values.
● Example:
import numpy as np
arr = np.array([1, 2, 3, 4])
2-D Array (Matrix):
● A 2-dimensional array is like a table with rows and columns.
● Example:
import numpy as np
matrix = np.array([[1, 2, 3], [4, 5, 6]])
3-D Array:
● A 3-dimensional array is like a cube with multiple layers.
● Example
import numpy as np
cube = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
2. Define the Pandas/Python pandas? Define DataFrame in Pandas?
Pandas is an open-source Python library used for data manipulation and analysis. It provides
easy-to-use data structures and functions for working with structured data,
DataFrame in Pandas:
● A DataFrame is a primary data structure in Pandas.
● It is a two-dimensional, tabular data structure that resembles a spreadsheet or SQL
table.
● A DataFrame consists of rows and columns, where each column can contain different
data types (integers, floats, strings, etc.).
● It allows you to perform operations like filtering, aggregation, and transformation on
data efficiently.
Example
import pandas as pd
data = {
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 28],
'City': ['New York', 'Los Angeles', 'Chicago']
df = pd.DataFrame(data)
3. How to create series in Pandas? Explain different ways with example
In Pandas, a Series is a one-dimensional labeled array that can hold data of any type. It's
similar to a column in a spreadsheet or a single variable in statistics
Method 1: Using a List
import pandas as pd
data = [1, 2, 3, 4, 5]
series = pd.Series(data)
Method 2: Using a NumPy Array
import pandas as pd
import numpy as np
data = np.array([10, 20, 30, 40, 50])
series = pd.Series(data)
Method 3: Using a Dictionary
import pandas as pd
data = {'a': 1, 'b': 2, 'c': 3}
series = pd.Series(data)
6 Explain binary search with example
Binary search is an efficient algorithm for finding a specific target value within a sorted
sequence, such as an array. It works by repeatedly dividing the search interval in half.
def binary_search(arr, target):
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid # Target found at index mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
sorted_list = [2, 5, 8, 12, 16, 23, 38, 45, 56, 72, 91]
target = 23
result = binary_search(sorted_list, target)
if result != -1:
print(f"Target {target} found at index {result}.")
else:
print(f"Target {target} not found in the list.")
7, Write a python to find the max value with and without using built in functions
Without Using Built-in Functions:
def find_max(arr):
if len(arr) == 0:
return None # Handle empty list
max_val = arr[0]
for val in arr:
if val > max_val:
max_val = val
return max_val
# Example list
my_list = [4, 8, 2, 12, 7]
max_value = find_max(my_list)
print("Maximum value without using built-in functions:", max_value)
Using Built-in Function (max()):
# Example list
my_list = [4, 8, 2, 12, 7]
max_value = max(my_list)
print("Maximum value using built-in function:", max_value)
8 What is database? What are tables and Fields?
atabase:
● A database is a structured collection of data organized for efficient storage, retrieval,
and management.
● It is designed to store and manage large volumes of data in a structured way.
● Databases are used in various applications, such as websites, business applications,
and more.
Tables:
● In a relational database, data is organized into tables.
● A table is a two-dimensional structure with rows and columns.
● Each row represents a record or entry, and each column represents a field or attribute.
● Tables are used to store related data, and they are linked through keys to establish
relationships.
Fields:
● Fields, also known as attributes or columns, are the individual pieces of data stored in
a table.
● Each field represents a specific type of information related to the records in the table.
● For example, in a table storing information about employees, fields might include
"EmployeeID," "FirstName," "LastName," "Salary," and "HireDate."