0% found this document useful (0 votes)
5 views44 pages

Python Data Types and Control Flow

The document provides an overview of Python programming concepts including data types like tuples, lists, and dictionaries, as well as control structures such as branching and iteration statements. It also covers functions, scoping, exception handling, abstract data types, inheritance, and sorting algorithms like linear search and bubble sort. Additionally, it mentions plotting functions in the pylab library for visualizing data.

Uploaded by

db2223167
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views44 pages

Python Data Types and Control Flow

The document provides an overview of Python programming concepts including data types like tuples, lists, and dictionaries, as well as control structures such as branching and iteration statements. It also covers functions, scoping, exception handling, abstract data types, inheritance, and sorting algorithms like linear search and bubble sort. Additionally, it mentions plotting functions in the pylab library for visualizing data.

Uploaded by

db2223167
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Q1(a)

1)IDLE stands --integrated Development and Learning


Environment
2) Who is the developer of python ?-- guido van Rossum
3) .py is the default extension of python file
4) variable is the container for storing basic data type

Q1(b)
1) What is a Tuple?
-- tuple is a collection, which is ordered and unchangeable
--tuples are assigned by parenthesis()
-- Tuples can contain elements of different data types, such
as integers, strings, and other tuples.
-- Tuples are generally faster than lists due to their
immutability.
-- example –
Mytup=(‘one’,’two’,’three’,’four’)
Print(mytup[0])
Print(mytup[2])
2) What is a List?
-- list can contain a series of values
-- list variables are declared by using brackets [] following
the variable name
-- all list in python are zero-based indexed
-- Python provides various built-in methods for lists, such as
append(), remove(), sort(), and pop().
-- example – a= [] #blank list
B=[1,23,45,67]
C=[2,4,’john’]

Q1(c)
1)What is Dictionaries? Explain with example.
--Dictionaries in Python are a built-in data type that
allow you to store and manage data as key-value pairs.
--They are highly versatile and useful for various tasks
where you need to associate unique keys with values.
--Definition:
--A dictionary is a mutable, unordered collection of
key-value pairs, where each key is unique and maps to
a value.
--Keys must be of an immutable type (like strings,
numbers, or tuples), and values can be of any type.
--Key Features:
1)Unordered: The order of items in a dictionary is not
guaranteed to be preserved.
2)Mutable: You can modify the dictionary by adding,
removing, or changing items.
3)Key-Value Pairs: Each item in a dictionary is a pair
consisting of a key and its corresponding value.
--Syntax: my_dict = {key1: value1, key2: value2, ...}
--Example:
# Creating a dictionary
person = {
"name": "Alice",
"age": 30,
"city": "New York"
}

# Accessing values using keys


print(person["name"]) # Output: Alice
print(person["age"]) # Output: 30
# Adding a new key-value pair
person["occupation"] = "Engineer"

# Modifying an existing value


person["age"] = 31

# Removing a key-value pair


del person["city"]

# Iterating through dictionary items


for key, value in [Link]():
print(f"{key}: {value}")

# Output:
# name: Alice
# age: 31
# occupation: Engineer
2) Explain Branching programs with suitable
example.
-- branching statements are used to change the normal flow of
execution based on some condition
-- the return statement is used to explicity return from a method
--it is also known as conditional or decision making statatement
1) if statement-- it will run the body of the code only when if
statement is true:
-- syantx: if expression:state
-- example :
print("this is example")
x="bca"
y= 6
if( x=="bca"):
print("hello student")
if(y==6):
print("hello 6th sem students")

2) else statement -- an else statement can be combined with if


statement
--syntax-- if expression : statement
else:
statement
--example: print("if else statement")
x="bca"
if(x== "bca")
print("\n hello bca students")
else:
print("\n hello floks")
3) elif statement: -- the elif statement allows you to check multiple
expressions for true
--syntax: if expression:
statement
elif :
statement
else:
statement
--example:
x=2
if x == 1:
print("FIRST VALUE")
elif x == 2:
print("second value")
print("x=",x)
else:
print("false expression")
Q1(d)

1) Explain Function and Scoping in Python


1)Functions in Python
--A function is defined using the def keyword,
followed by the function name and parentheses.
--The function body contains the code to be executed
when the function is called. --Functions can take
parameters and can return a value using the return
statement.

--Syntax:
def function_name(parameters):
# Function body
# Optional return statement
return value
--Example:
# Define a function
def greet(name):
return f"Hello, {name}!"
# Call the function
message = greet("Alice")
print(message) # Output: Hello, Alice!

--def greet(name):: This defines a function called


greet that takes one parameter, name.
--return f"Hello, {name}!": The function returns a
greeting message.
--greet("Alice"): The function is called with the
argument "Alice", and it returns "Hello, Alice!".

--Types of Functions:
1)Built-in Functions: Functions that are part of
Python, like print(), len(), etc.
2)User-defined Functions: Functions defined by the
user, like greet() in the example above.

2)Scope in Python
--Scope defines the region of a program where a
variable is accessible.
--Variables can have different scopes, depending on
where they are declared:
1)Local Scope: Variables declared inside a function
have local scope.
--They can only be accessed within that function.
2)Global Scope: Variables declared outside of all
functions have global scope.
--They can be accessed from anywhere in the
program.
3)Enclosing Scope: This occurs in nested functions.
--The inner function can access variables from its
enclosing function.
4)Built-in Scope: This is the outermost scope that
includes built-in functions and variables like len(),
print(), etc.

--Example of Local and Global Scope:


# Global variable
x = 10
def example_function():
# Local variable
y=5
print("Inside the function, x =", x) # Access global
variable
print("Inside the function, y =", y) # Access local
variable

# Call the function


example_function()

# Outside the function


print("Outside the function, x =", x) # Access global
variable
# print(y) # This would raise an error because y is not
accessible outside the function

--x = 10: This is a global variable, accessible both


inside and outside the function.
--y = 5: This is a local variable, accessible only inside
example_function().

--Global vs. Local Variables:


1)Local variables are created within a function and are
destroyed once the function exits.
2)Global variables exist throughout the program’s
execution.
--They can be accessed inside functions, but to modify
them inside a function, you must use the global
keyword.

--Example of the global Keyword:


x = 10 # Global variable

def modify_global():
global x
x = 20 # Modifying the global variable

modify_global()
print(x) # Output: 20

--Nested Functions and Enclosing Scope:


--Nested functions can access variables from their
enclosing (outer) function, but not from the inner
function's scope.
--This is known as the enclosing scope.

--Example:
def outer_function():
outer_var = "Hello"

def inner_function():
print(outer_var) # Accessing the outer function's
variable

inner_function()

outer_function() # Output: Hello

--Python resolves variable names by searching


through the following scopes in order:

1)Local: Inside the current function.


2)Enclosing: In the enclosing function's scope (if
there's a nested function).
3)Global: At the top level of the module or script.
4)Built-in: Predefined Python variables/functions.
2)Explain Iteration statements in Python
Iteration :
Iteration in Python refers to the process of executing a sequence of
instructions repeatedly
1)for Loop
--Purpose: Iterates over a sequence and executes a block of code for
each item in the sequence.
--Syntax: for item in sequence:
# Code block to execute
--Example:
# Iterating over a list
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)

# Output:
# apple
# banana
# cherry
In this example, the for loop iterates through each item in the fruits
list and prints it.

2. while Loop
--Purpose: Repeats a block of code as long as a specified condition is
true.
--Syntax: while condition:
# Code block to execute
--Example:
# Counting from 1 to 5
count = 1
while count <= 5:
print(count)
count += 1

# Output:
#1
#2
#3
#4
#5
In this example, the while loop continues to execute as long as count
is less than or equal to 5, printing the value of count and incrementing
it in each iteration.

--Key Points:
1)Control Flow:
--break: Exits the loop prematurely.
--continue: Skips the current iteration and proceeds to the next
iteration.
--else: Can be used with loops to execute a block of code once
after the loop finishes normally (not interrupted by break).

2)Use Cases:
--for Loop: Ideal for iterating over sequences where the number of
iterations is known or finite.
--while Loop: Suitable for scenarios where the number of iterations is
not known beforehand and depends on a condition.
--These iteration statements are fundamental in Python for
performing repetitive tasks and managing the flow of execution in
your programs.

Q2(a)
1) ADT Abstract Data Type
2) Raised statement forces exception to occur
3) Exception catches all the exceptions
4) Finally block executes the code, whether an
exception has occurred or not
Q2(b)
1) explain AttributeError

 An AttributeError occurs when you try to access or call


an attribute that doesn't exist for a particular object.
 This error usually happens if you mistype the attribute
name or if the object doesn’t have the attribute due to its
type or a missing import.
 For example:
python
Copy code
my_list = [1, 2, 3]
my_list.appendd(4) # Typo in
method name
# AttributeError: 'list' object has
no attribute 'appendd'

In this case, the correct method is append, not appendd.

2) Explain Value Error


 A Value Error occurs when a function receives an
argument of the right type but an inappropriate value.
 For example, passing a string instead of a number for a
mathematical operation
Q2(c)
1) explain ADT
--(ADTs) and classes are foundational concepts in
computer science and programming, particularly in
(OOP).
--They help in defining and managing data and its
associated behaviors in a structured manner.

1)Abstract Data Types (ADTs)


--Definition: An (ADT) is a conceptual model that
defines a data structure and its associated operations
independently of implementation details.
--It specifies what operations are possible and what
behaviors they should exhibit, without specifying how
these operations are implemented.
--Key Characteristics:
1)Encapsulation: Details of the implementation are
hidden from the user.
2)Operations: Provides a set of operations that can be
performed on the data.
--Examples of ADTs:
1)Stack: A collection of elements with Last In, First Out
(LIFO) access.
2)Queue: A collection of elements with First In, First
Out (FIFO) access.

2)Explain Inheritance in Python


--Inheritance allows a new class (child class) to inherit properties and
methods from an existing class (parent class), promoting code reuse.
-Child classes can override methods of the parent class to provide
specific implementations.
-- inheritance can be single, multiple, multilevel, hierarchical, or
hybrid.
-- The super() function is used to access methods from the parent
class in the child class.
--Syntax:
To define a derived class, you use the following syntax:
class DerivedClass(BaseClass):
# Additional attributes and methods
Example:
# Base class
class Animal:
def __init__(self, name):
[Link] = name
def speak(self):
return "Animal sound"
# Derived class
class Dog(Animal):
def speak(self):
return "Woof!"

# Usage
animal = Animal("Generic Animal")
dog = Dog("Buddy")
print([Link]()) # Output: Animal sound
print([Link]()) # Output: Woof!

-Characteristics of Inheritance:
1)Code Reuse: Allows derived classes to reuse code from the base
class, reducing redundancy.
2)Extensibility: Enables the creation of new classes with additional
features or modified behavior without altering existing code.
3)Hierarchical Structure: Facilitates a hierarchical relationship
between classes, where a derived class can inherit from a base class,
and further derived classes can inherit from it.
4)Inheritance helps create a more organized and maintainable code
structure by establishing clear relationships between different
classes.
Q2(d)

1) explain linear search


-- Linear Search and Interpolation Search are two
algorithms used to find an element in a list or array.
--While both algorithms aim to locate an element, they
differ in their approach and efficiency.

1)Linear Search: Linear Search is a straightforward


searching algorithm that checks each element in a list
sequentially until the desired element is found or the
end of the list is reached.

--Algorithm:
1)Start at the beginning of the list.
2)Compare the target element with each element in
the list.
3)If the target element is found, return its index.
4)If the end of the list is reached and the element is not
found, return an indication that the element is not
present.
example:
def linear_search(arr, target):
for index, element in enumerate(arr):
if element == target:
return index # Target found, return its index
return -1 # Target not found, return -1

# Example usage
arr = [10, 20, 30, 40, 50]
target = 30
result = linear_search(arr, target)
if result != -1:
print(f"Element found at index {result}")
else:
print("Element not found")

--Explanation:
1)Time Complexity: O(n), where n is the number of
elements in the list.
2)Space Complexity: O(1), as it uses only a few extra
variables.
3)Use Case: Suitable for small or unsorted lists where
the simplicity of the algorithm is preferred.

2)explain bubble sort


--Bubble sort is a simple comparison-based sorting
algorithm
-- It repeatedly steps through the list, compares adjacent
elements, and swaps them if they are in the wrong order.
-- The process is repeated until the list is sorted.
-- Bubble sort does not require extra space, as it sorts the
list in place.
-- It maintains the relative order of equal elements.

Steps of Bubble Sort:


1. Start from the beginning of the list.
2. Compare each pair of adjacent elements (starting
from the first element).
3. If the first element in the pair is greater than the
second, swap them.
4. Continue moving to the next pair until the end of the
list.
5. After each pass through the list, the largest unsorted
element will "bubble up" to its correct position at the
end.
6. Repeat the process for the remaining unsorted part of
the list until no swaps are needed.

--Example :
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n - i - 1):
if arr[j] > arr[j + 1]:
# Swap if the element found is greater than the next element
arr[j], arr[j + 1] = arr[j + 1], arr[j]

# Example usage
numbers = [64, 34, 25, 12, 22, 11, 90]
bubble_sort(numbers)
print("Sorted array:", numbers)
Q3( a)
1) Figure() function is used to create new figure
2) Show() function is used to display a plot
3) Save() function is used to save a plot
4) An example of a sorting algorithm that uses the
divide and conquer approach is merge sort

Q3(b)
1) Explain [Link], [Link], [Link]
1) [Link]()
--Adds a title to the plot to describe the purpose of the
graph.
--Example: [Link]("My Plot Title") sets the title of
the plot.
2)[Link]()
-- Adds a label to the x-axis, explaining what the x-
values represent.
--Example: [Link]("X Axis Label") sets the label of
the x-axis.
3)[Link]()
-- Adds a label to the y-axis, explaining what the y-
values represent.
--Example: [Link]("Y Axis Label") sets the label of
the y-axis.

2) Explain Memoization in Python


Memoization is an optimization technique in programming
that speeds up function execution by caching previously
computed results.

How Memoization Works


 Store Results: When a function is called, it first checks
if the result for the given arguments is already stored in a
cache (often a dictionary).
 Return Cached Result: If the result is found in the
cache, the function returns it right away.
 Compute and Cache: If the result isn’t in the cache, the
function computes it, stores it in the cache, and then
returns it.

Q3(c)
1)Explain Fibonacci sequence
--The Fibonacci sequence is a series of numbers where each number
is the sum of the two preceding ones, starting from 0 and 1.
--The sequence typically starts with 0 and 1, and each subsequent
number is derived as follows: F(n)=F(n−1)+F(n−2)
-Key Points:
-Base Cases: The first two numbers of the sequence are defined as:
F(0)=0 , F(1)=1
Recursive Case: For n≥2, each number is the sum of the two
preceding numbers: F(n)=F(n−1)+F(n−2)
--Example in Python:
def fibonacci(n):
if n <= 1: # Base cases
return n
else:
return fibonacci(n - 1) + fibonacci(n - 2) # Recursive case

# Example usage
print(fibonacci(10)) # Output: 55

--In this example, the fibonacci() function calculates the n-th


Fibonacci number using a recursive approach. For n = 10, the
function returns 55, which is the 10th number in the Fibonacci
sequence (starting from 0).

--Characteristics of Fibonacci Sequence:


1)Recursive Nature: The sequence is defined recursively, making it a
classic example of a problem suited for recursive solutions.
2)Growth Pattern: The Fibonacci sequence grows exponentially as n
increases.
3)Applications: The Fibonacci sequence appears in various natural
phenomena, mathematical problems, and algorithmic problems,
such as dynamic programming and divide-and-conquer algorithms

2) divide and conquer algorithm


The divide and conquer algorithm is a powerful problem-solving
technique used in computer science and programming. It works by
recursively breaking down a problem into smaller subproblems until
they become simple enough to be solved directly. Once the
subproblems are solved, the solutions are combined to give a solution
to the original problem. This approach is commonly used in
algorithms for sorting, searching, and other complex problems.

Steps of Divide and Conquer

1. Divide: Split the problem into smaller subproblems.


2. Conquer: Solve the subproblems recursively. If they are small
enough, solve them directly.
3. Combine: Merge the solutions of the subproblems to get the
solution to the original problem.

Example: Merge Sort

One of the classic examples of the divide and conquer approach is the
Merge Sort algorithm. Here’s how it works:

1. Divide: Split the array into two halves.


2. Conquer: Recursively sort both halves.
3. Combine: Merge the two sorted halves to produce the sorted
array.

Implementation of Merge Sort in Python


Here’s how you can implement the Merge Sort algorithm in Python:
python
Copy code
def merge_sort(arr):
# Base case: If the array is of length 1 or
empty, return it
if len(arr) <= 1:
return arr

# Step 1: Divide
mid = len(arr) // 2 # Find the middle
index
left_half = arr[:mid] # Split the array
into left half
right_half = arr[mid:] # Split the array
into right half

# Step 2: Conquer (recursively sort both


halves)
left_sorted = merge_sort(left_half)
right_sorted = merge_sort(right_half)

# Step 3: Combine (merge the sorted halves)


return merge(left_sorted, right_sorted)

def merge(left, right):


merged = []
i = j = 0

# Merge the two lists while comparing


elements
while i < len(left) and j < len(right):
if left[i] < right[j]:
[Link](left[i])
i += 1
else:
[Link](right[j])
j += 1

# If there are remaining elements in left


or right, add them
[Link](left[i:])
[Link](right[j:])

return merged

# Example usage
if __name__ == "__main__":
unsorted_array = [38, 27, 43, 3, 9, 82, 10]
sorted_array = merge_sort(unsorted_array)
print("Sorted array:", sorted_array)

Explanation of the Code

1. Base Case: The merge_sort function first checks if the array


length is 1 or less. If it is, the function returns the array as it is
already sorted.
2. Divide: The array is split into two halves using the middle
index.
3. Conquer: The merge_sort function is called recursively on
both halves.
4. Combine: The merge function is used to merge the two sorted
halves back into a single sorted array.

Complexity

 Time Complexity: The time complexity of the merge sort


algorithm is O(nlog⁡n)O(n \log n)O(nlogn), where nnn is the
number of elements in the array. The logarithmic factor comes
from the division of the array, and the linear factor comes from
merging the sorted subarrays.
 Space Complexity: The space complexity is O(n)O(n)O(n) due
to the temporary arrays used for merging.
Q3(d)
1) Explain plotting mortagages
2) Explain 0/1 knapsack algorithm

Q4(a)
1. The socket module is commonly used for socket
programming to handle network connection

2. The bind() method is used to associate the socket


with a specific network interface and port number

3. The SMTP protocol is used to send email over the


internet

4. The [Link]() function in python


returns the hostname of the machine

Q4(b)
1) explain [Link]()
 In Python, the [Link]() method is used to associate
a socket with a specific IP address and port number,
effectively “binding” it to a network interface.
 This is essential for servers, as it lets the socket listen for
incoming connections on the specified port, allowing it
to communicate over the network.
import socket
# Create a socket object
server_socket = [Link](socket.AF_INET,
socket.SOCK_STREAM)
# Define the IP address and port to bind to
host = '[Link]' # Localhost
port = 12345
# Bind the socket to the specified host and port
server_socket.bind((host, port))
# Enable the server to accept connections
server_socket.listen(5)
print(f"Server is listening on {host}:{port}")
# Accept and handle incoming connections
while True:
client_socket, addr = server_socket.accept()
print(f"Got connection from {addr}")
client_socket.send(b"Hello, client!")
client_socket.close()
2) explain [Link]()

 In Python, the [Link]() method is used by a


client to establish a connection to a server.
 It takes a tuple containing the server's IP address and port
number and attempts to connect to that address over the
specified port.
 Once connected, the client can send and receive data
through the socket.
Example
Here's a simple client example using [Link]() to
connect to a server:
python
Copy code
import socket

# Create a socket object


client_socket =
[Link](socket.AF_INET,
socket.SOCK_STREAM)

# Define the server IP address and port


to connect to
host = '[Link]' # Server's IP address
(localhost in this example)
port = 12345

# Connect to the server


client_socket.connect((host, port))
print("Connected to the server")
# Receive and print data from the server
message = client_socket.recv(1024)
print("Received from server:",
[Link]())

# Close the connection


client_socket.close()

Q4(c)
Explain recv() and recfrom()

--in Python, the recv() and recvfrom() functions are


used to receive data from sockets.
--They are commonly used in network programming for
handling data sent between client and server applications.
--Here’s a quick breakdown:
1. recv():
 Usage: recv(buffer_size)
 Function: Receives data from a connected socket.
 Details: Used in TCP connections where the connection
is already established. It reads up to buffer_size
bytes of data from the socket.
 Example:
python
Copy code
data = [Link](1024) # Receives
up to 1024 bytes
 Return: Returns the data received as bytes.
2. recvfrom():
 Usage: recvfrom(buffer_size)
 Function: Receives data along with the address of the
sender.
 Details: Primarily used with UDP connections where
there isn’t a permanent connection. It reads up to
buffer_size bytes and returns a tuple containing
both the data and the sender's address.
 Example:
python
Copy code
data, address = [Link](1024)
# Receives up to 1024 bytes and
sender’s address
 Return: Returns a tuple with the data (bytes) and the
sender’s address.
Key Difference:
 recv() is for connected sockets (TCP), while recvfrom()
is for datagram sockets (UDP) that need to know the
sender's address each time data is received.

2)explain send and sendto()


--In Python, the send() and sendto() functions are used
to send data through sockets, essential in network
programming for data transfer between a client and server.
--Here’s a concise explanation:
1. send():
 Usage: send(data)
 Function: Sends data to a connected socket.
 Details: Commonly used with TCP sockets where a
connection is established. It transmits the data (in
bytes) to the connected remote socket.
 Example:
python
Copy code
[Link](b"Hello, World!")
 Return: Returns the number of bytes sent. May send less
data than specified if buffer limits are reached.
2. sendto():
 Usage: sendto(data, address)
 Function: Sends data to a specific address.
 Details: Typically used with UDP sockets, where there
is no established connection. It sends data to the
specified address (a tuple of IP and port).
 Example:
python
Copy code
[Link](b"Hello, World!",
("[Link]", 8080))
 Return: Returns the number of bytes sent.
Key Difference:
 send() is used with connected sockets (TCP), while
sendto() is for datagram sockets (UDP) to specify the
recipient address directly.

Q4(d)
1) python code to download a web page
2) download an image

Q5(a)
1. Callproc() method is used to call existing procedure
of MYSQL database

2. Info() method gives information about last query

3. Execute() method accepts a MYSQL query as a


parameter and executes the given query

4. Fetchone() method fetches the next row in the


result of a query and returns it as tuple
Q5(b)
1) explain lastrowid , statement property of mysql cursor

1. lastrowid:
 This property returns the ID of the last row
inserted by an INSERT statement using the
cursor.
 This is useful for tables with an auto-
incrementing primary key, allowing you to
retrieve the new ID immediately after an
insertion.
 If no row was inserted or if the last query was not
an INSERT statement, lastrowid will be
None.
Example:
python
Copy code
[Link]("INSERT INTO users
(name, age) VALUES ('Alice', 30)")
print("Last inserted row ID:",
[Link])
2. statement:

 This property contains the most recent SQL


statement executed by the cursor, providing
insight into what was last run by the cursor.
 It can be useful for debugging or logging SQL
queries dynamically in the code.
Example:
python
Copy code
[Link]("SELECT * FROM users
WHERE age > 25")
print("Last executed statement:",
[Link])

2) explain column_name, description property of mysql


cursor

1. column_names:
 This property provides a list of the column
names in the result set after executing a SELECT
query.
 It allows you to retrieve column headers
programmatically, which is useful for
dynamically accessing or displaying query
results.
Example:
python
Copy code
[Link]("SELECT id, name, age
FROM users")
column_names = [desc[0] for desc in
[Link]]
print("Column Names:", column_names)

2. description:
o The description property provides detailed
metadata about each column in the result set,
including the column name, type, display size, and
other attributes.
o It is a tuple of tuples, where each inner tuple
contains metadata about one column. For example,
(column_name, type_code,
display_size, internal_size,
precision, scale, null_ok).
Example:
python
Copy code
[Link]("SELECT id, name, age
FROM users")
for col in [Link]:
print("Column:", col[0], "|
Type:", col[1])

Q5(c)
1)Executemany()
the executemany() method in Python’s MySQL cursor is
used to run the same SQL query multiple times with different
parameters. This is especially useful for inserting multiple
records into a database efficiently.
Explanation:
 Purpose: To execute an SQL statement repeatedly with
different sets of data.
 Efficiency: More efficient than executing execute()
in a loop, as it reduces the number of calls made to the
database.
 Usage: Often used for bulk insertions or updates.
Syntax:
python
Copy code
[Link](query, data)
 query: The SQL query to execute.
 data: A list of tuples, where each tuple contains the
parameters for a single execution of the query.
Example:
Here’s an example of using executemany() to insert
multiple rows into a MySQL table named students:
python
Copy code
import [Link]

# Establishing the connection


conn = [Link](
host="localhost",
user="yourusername",
password="yourpassword",
database="school"
)
cursor = [Link]()
# SQL query for insertion
query = "INSERT INTO students (name, age)
VALUES (%s, %s)"

# List of tuples containing student data


data = [
("Alice", 22),
("Bob", 21),
("Charlie", 23)
]

# Executing the query for multiple


records
[Link](query, data)

# Committing the transaction


[Link]()

# Confirming the number of rows inserted


print([Link], "rows inserted.")

# Closing the connection


[Link]()
[Link]()

Explanation of the Example:


 Insert Statement: "INSERT INTO students
(name, age) VALUES (%s, %s)"
 Data List: Each tuple in data represents values for one
row (name and age).
 executemany() Call: Executes the insert statement for
each tuple in data.
 Output: Outputs the number of rows inserted after
committing the transaction.

2)fetchall()
The fetchall() method in MySQL’s Python connector is
used to retrieve all rows from the result set of a query
executed through a cursor. It’s useful when you want to work
with the full result set at once.
Explanation of fetchall()

 Function: fetchall() retrieves all remaining rows of


a query result, returning them as a list of tuples.
 Usage: Typically used after execute() to fetch the
query results.
 Return Value: Returns a list of tuples, where each tuple
represents a row in the result set.
Example
Suppose we have a users table with the columns id, name,
and age, and we want to retrieve all records.
python
Copy code
import [Link]

# Establishing a connection
connection = [Link](
host="localhost",
user="your_username",
password="your_password",
database="your_database"
)

# Creating a cursor object


cursor = [Link]()

# Executing a SQL query


[Link]("SELECT * FROM users")

# Fetching all rows from the executed


query
all_rows = [Link]()

# Printing the results


for row in all_rows:
print(row) # Each row is a tuple
(id, name, age)

# Closing the connection


[Link]()
[Link]()

Explanation of Output:
 After fetchall(), all_rows will hold a list of
tuples. If the users table contains data like (1,
"Alice", 30), (2, "Bob", 25), it will print
each row as a tuple.
Key Points:
 fetchall() retrieves the entire result set, so it's best used
for smaller data sets.
 For large datasets, consider using fetchone() to
retrieve one row at a time to avoid memory issues.
Q5(d)
1)Create database and table in mysql
2)Inserting, updating, deleting rows of mysql table

You might also like