0% found this document useful (0 votes)
20 views

Scenario Based Python Questions-Unit 1

The document contains a series of Python programming scenarios and questions, including tasks for input validation, conditional statements, iterative processes, CSV file handling, data analysis, and simple game mechanics. Each scenario is accompanied by a program that demonstrates the required functionality, such as managing supermarket items, student grades, sales data analysis, and an ATM simulation. The document serves as a practical guide for implementing various programming concepts in Python.
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)
20 views

Scenario Based Python Questions-Unit 1

The document contains a series of Python programming scenarios and questions, including tasks for input validation, conditional statements, iterative processes, CSV file handling, data analysis, and simple game mechanics. Each scenario is accompanied by a program that demonstrates the required functionality, such as managing supermarket items, student grades, sales data analysis, and an ATM simulation. The document serves as a practical guide for implementing various programming concepts in Python.
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
You are on page 1/ 30

Scenario Based Python Questions

Unit 1

Question 1:

Imagine you're building a system for a supermarket where employees need to record items,
their prices, and availability. Your task is to:

1. Accept inputs for an item's name, price, and availability.


2. Use Python's built-in functions to:
o Check the type of each input (e.g., string, float, boolean).
o Validate whether the inputs are in the correct data type.
o Perform operations based on the input types.

Program:

# Built-in functions and type checking

# Step 1: Input the item details


item_name = input("Enter the item name: ")
item_price = input("Enter the item price: ")
item_available = input("Is the item available? (True/False): ")

# Step 2: Validate and trace the data types


print("\nTracing the data types of inputs:")
print(f"Item Name: {item_name} - Type: {type(item_name)}")

try:
# Convert item_price to float and check type
item_price = float(item_price)
print(f"Item Price: {item_price} - Type: {type(item_price)}")
except ValueError:
print("Error: Item price must be a number (float). Exiting...")
exit()

try:
# Convert item_available to boolean and check type
if item_available.lower() == "true":
item_available = True
elif item_available.lower() == "false":
item_available = False
else:
raise ValueError
print(f"Item Availability: {item_available} - Type: {type(item_available)}")
except ValueError:
print("Error: Item availability must be 'True' or 'False'. Exiting...")
exit()

# Step 3: If all inputs are valid, display the item details


print("\nItem Details:")
print(f"Name: {item_name}")
print(f"Price: ${item_price:.2f}")
print(f"Available: {'Yes' if item_available else 'No'}")

Question 2 (for conditional statement)

The player starts at the entrance of a mysterious cave. They have three choices:

1. Go into the cave.


2. Walk along the river nearby.
3. Return to the village.

Based on their choice, different scenarios unfold:

 If they go into the cave, they encounter a sleeping dragon. They can either fight,
sneak past, or run away.
 If they walk along the river, they find a treasure chest. They can either open it or
ignore it.
 If they return to the village, they meet a wise old man who gives them a hint about
the cave.

Program:

# Starting the game


print("Welcome to the Adventure Game!")
print("You are at the entrance of a mysterious cave.")
print("What do you want to do?")
print("1. Enter the cave")
print("2. Walk along the river")
print("3. Return to the village")

# Player's first choice


choice1 = input("Enter your choice (1, 2, or 3): ")

if choice1 == "1":
print("\nYou step into the cave and see a sleeping dragon!")
print("What will you do?")
print("1. Fight the dragon")
print("2. Sneak past the dragon")
print("3. Run away")

choice2 = input("Enter your choice (1, 2, or 3): ")


if choice2 == "1":
print("\nYou bravely fight the dragon but unfortunately, it wakes up and defeats you. Game
over!")
elif choice2 == "2":
print("\nYou carefully sneak past the dragon and find a pile of gold! You win!")
elif choice2 == "3":
print("\nYou run out of the cave and return to safety. Game over!")
else:
print("\nInvalid choice. The dragon wakes up and chases you out of the cave. Game over!")

elif choice1 == "2":


print("\nYou walk along the river and find a treasure chest!")
print("What will you do?")
print("1. Open the chest")
print("2. Ignore the chest and continue walking")

choice2 = input("Enter your choice (1 or 2): ")


if choice2 == "1":
print("\nYou open the chest and find a magical sword. You are now ready for any danger!")
elif choice2 == "2":
print("\nYou ignore the chest and miss out on the treasure. Game over!")
else:
print("\nInvalid choice. You slip into the river and are swept away. Game over!")

elif choice1 == "3":


print("\nYou return to the village and meet a wise old man.")
print("He tells you, 'The dragon in the cave guards a great treasure, but you must be clever to
obtain it.'")
print("Hint: Sneaking is often wiser than fighting!")
else:
print("\nInvalid choice. Please restart the game and choose a valid option.")

Question 3: (for iterative statements)

Imagine you are building a program for a teacher to calculate the average grade of students in
a class. The teacher wants to:

1. Enter the total number of students.


2. Input each student's grade one by one.
3. Calculate and display the average grade.

Program:
# Step 1: Input the total number of students
total_students = int(input("Enter the total number of students in the class: "))
# Step 2: Initialize variables for storing grades and total sum
grades = []
total_sum = 0

# Step 3: Use a loop to input grades for each student


print("\nEnter the grades for each student (0-100):")
for i in range(total_students):
while True:
try:
grade = float(input(f"Grade for Student {i + 1}: "))
if 0 <= grade <= 100:
grades.append(grade)
total_sum += grade
break
else:
print("Grade must be between 0 and 100. Try again.")
except ValueError:
print("Invalid input. Please enter a valid number.")

# Step 4: Calculate the average grade


average_grade = total_sum / total_students

# Step 5: Display the results


print("\n--- Grade Summary ---")
print(f"Total Students: {total_students}")
print(f"Grades: {grades}")
print(f"Average Grade: {average_grade:.2f}")

# Step 6: Give feedback based on the average grade


if average_grade >= 90:
print("Performance: Excellent!")
elif average_grade >= 75:
print("Performance: Good.")
elif average_grade >= 50:
print("Performance: Needs Improvement.")
else:
print("Performance: Poor.")

Output:
Question 4

Scenario: Managing Student Grades

You are tasked with creating a program to manage a CSV file containing students' grades.
You need to:

1. Read student data (names and grades) from a CSV file (grades.csv).
2. Calculate the average grade for each student and add it as a new column.
3. Write the updated data back to a new CSV file (grades_with_average.csv).

Program:
import csv

# Step 1: Read the data from the CSV file


input_file = "grades.csv"
output_file = "grades_with_average.csv"

# Step 2: Read the CSV file


students = []
with open(input_file, mode="r") as file:
csv_reader = csv.reader(file)
headers = next(csv_reader) # Read the header row
headers.append("Average") # Add an "Average" column

for row in csv_reader:


# Convert grades (from the second column onward) to integers
grades = list(map(int, row[1:]))
average = sum(grades) / len(grades)
row.append(round(average, 2)) # Add average to the row
students.append(row)

# Step 3: Write the updated data to a new CSV file


with open(output_file, mode="w", newline="") as file:
csv_writer = csv.writer(file)
csv_writer.writerow(headers) # Write the headers
csv_writer.writerows(students) # Write the student data

print(f"Updated grades with averages have been saved to '{output_file}'.")

Input CSV File (grades.csv)


Name,Math,Science,English
Alice,85,90,88
Bob,78,82,80
Charlie,92,88,94

Output CSV File (grades_with_average.csv)


Name,Math,Science,English,Average
Alice,85,90,88,87.67
Bob,78,82,80,80.0
Charlie,92,88,94,91.33

Output:
Updated grades with averages have been saved to 'grades_with_average.csv'.

Question 5

Scenario: Sales Data Analysis and Visualization

You work for a retail company and have been given a dataset (sales_data.csv) containing
sales performance information. The task is to:

1. Analyze the sales data to find key metrics like total sales, average sales, and sales by
region.
2. Visualize the data using charts and graphs to present insights such as:
o Sales trends over time.
o Regional sales distribution.
o Top-performing products.

Input CSV File (sales_data.csv)

Date Product Region Sales

2025-01-01 Product A North 1200

2025-01-01 Product B South 900

2025-01-02 Product A East 1500

2025-01-02 Product C West 1800

2025-01-03 Product B North 1300

2025-01-03 Product C South 1100

Program:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# Step 1: Load the data


data = pd.read_csv("sales_data.csv", parse_dates=["Date"])

# Step 2: Data Analysis


# Total Sales
total_sales = data["Sales"].sum()
print(f"Total Sales: ${total_sales}")

# Average Sales per transaction


average_sales = data["Sales"].mean()
print(f"Average Sales: ${average_sales:.2f}")

# Sales by Region
sales_by_region = data.groupby("Region")["Sales"].sum()
print("\nSales by Region:")
print(sales_by_region)

# Sales Trend Over Time


sales_trend = data.groupby("Date")["Sales"].sum()

# Top Products by Sales


top_products = data.groupby("Product")["Sales"].sum().sort_values(ascending=False)
print("\nTop Products by Sales:")
print(top_products)

# Step 3: Data Visualization


plt.figure(figsize=(12, 10))

# (a) Sales Trend Over Time


plt.subplot(2, 2, 1)
sales_trend.plot(marker="o", title="Sales Trend Over Time", color="blue")
plt.xlabel("Date")
plt.ylabel("Total Sales")
plt.grid(True)

# (b) Regional Sales Distribution (Pie Chart)


plt.subplot(2, 2, 2)
sales_by_region.plot.pie(autopct="%.1f%%", title="Sales by Region", startangle=140,
colormap="viridis")
plt.ylabel("") # Hide y-label for pie chart
# (c) Top Products by Sales (Bar Chart)
plt.subplot(2, 2, 3)
top_products.plot(kind="bar", title="Top Products by Sales", color="green")
plt.xlabel("Product")
plt.ylabel("Total Sales")
plt.xticks(rotation=45)

# (d) Sales Distribution (Histogram)


plt.subplot(2, 2, 4)
plt.hist(data["Sales"], bins=5, color="purple", edgecolor="black")
plt.title("Sales Distribution")
plt.xlabel("Sales")
plt.ylabel("Frequency")

plt.tight_layout()
plt.show()

Output:

Question 6
You run a coffee shop and want to create a simple ordering system. The program should:
• Display the menu with prices.
• Ask the customer to select items and quantities.
• Calculate the total bill and apply a discount if the total exceeds $50.
• Provide the final amount payable.
Program:
# Coffee Shop Menu
menu = {
"Espresso": 3.00,
"Cappuccino": 4.50,
"Latte": 5.00,
"Mocha": 5.50,
"Americano": 2.50
}

print("Welcome to Brew Bliss Coffee Shop!")


print("Here's our menu:")

# Display menu
for item, price in menu.items():
print(f"{item}: ${price:.2f}")

order = {}
while True:
item = input("\nEnter the item you want to order (or type 'done' to finish): ").title()
if item.lower() == "done":
break
if item not in menu:
print("Sorry, we don't have that item.")
continue
quantity = int(input(f"How many cups of {item} would you like? "))
order[item] = order.get(item, 0) + quantity

if not order:
print("No items ordered. Thank you for visiting!")
else:
# Calculate total bill
total_bill = sum(menu[item] * quantity for item, quantity in order.items())

# Discount for orders above $50


discount = 0.1 * total_bill if total_bill > 50 else 0
final_amount = total_bill - discount

# Print receipt
print("\n--- Order Summary ---")
for item, quantity in order.items():
print(f"{item} x {quantity} = ${menu[item] * quantity:.2f}")

print(f"Subtotal: ${total_bill:.2f}")
if discount > 0:
print(f"Discount Applied: ${discount:.2f}")
print(f"Total Amount Payable: ${final_amount:.2f}")
print("Thank you for your order!")

Output:
Welcome to Brew Bliss Coffee Shop!
Here's our menu:
Espresso: $3.00
Cappuccino: $4.50
Latte: $5.00
Mocha: $5.50
Americano: $2.50

Enter the item you want to order (or type 'done' to finish): Latte
How many cups of Latte would you like? 5

Enter the item you want to order (or type 'done' to finish): Mocha
How many cups of Mocha would you like? 3

Enter the item you want to order (or type 'done' to finish): done

--- Order Summary ---


Latte x 5 = $25.00
Mocha x 3 = $16.50
Subtotal: $41.50
Total Amount Payable: $41.50
Thank you for your order!

Question 7
A school wants a simple program to calculate student grades based on marks input for three
subjects.
Program:
# Get input marks for three subjects
name = input("Enter the student's name: ")
marks1 = float(input("Enter marks for Mathematics: "))
marks2 = float(input("Enter marks for Science: "))
marks3 = float(input("Enter marks for English: "))

# Calculate average
average = (marks1 + marks2 + marks3) / 3

# Determine grade
if average >= 90:
grade = "A"
elif average >= 75:
grade = "B"
elif average >= 60:
grade = "C"
elif average >= 50:
grade = "D"
else:
grade = "F"

# Display result
print(f"\n{name}'s Report Card")
print(f"Average Marks: {average:.2f}")
print(f"Grade: {grade}")

Output:
Enter the student's name: Alex
Enter marks for Mathematics: 88
Enter marks for Science: 78
Enter marks for English: 92

Alex's Report Card


Average Marks: 86.00
Grade: B

Question 8
A bank wants an ATM simulation that allows withdrawals with balance checks.
Program:
# Initial account balance
balance = 5000.00

print("Welcome to the ATM!")


print("1. Check Balance")
print("2. Withdraw Money")
print("3. Exit")

while True:
choice = int(input("\nChoose an option (1-3): "))

if choice == 1:
print(f"Your current balance is ${balance:.2f}")
elif choice == 2:
amount = float(input("Enter the amount to withdraw: $"))
if amount > balance:
print("Insufficient balance.")
elif amount <= 0:
print("Please enter a valid amount.")
else:
balance -= amount
print(f"Withdrawal successful! Remaining balance: ${balance:.2f}")
elif choice == 3:
print("Thank you for using the ATM. Goodbye!")
break
else:
print("Invalid choice. Please try again.")
Output:
Welcome to the ATM!
1. Check Balance
2. Withdraw Money
3. Exit

Choose an option (1-3): 2


Enter the amount to withdraw: $1000
Withdrawal successful! Remaining balance: $4000.00
Question 9

A game where the player tries to guess a randomly generated number.


Program:
import random

print("Welcome to the Guess the Number Game!")


number_to_guess = random.randint(1, 100)
attempts = 0

while True:
guess = int(input("Guess a number between 1 and 100: "))
attempts += 1

if guess < number_to_guess:


print("Too low! Try again.")
elif guess > number_to_guess:
print("Too high! Try again.")
else:
print(f"Congratulations! You guessed the number in {attempts} attempts.")
break
Output:
Welcome to the Guess the Number Game!
Guess a number between 1 and 100: 50
Too low! Try again.
Guess a number between 1 and 100: 75
Too high! Try again.
Guess a number between 1 and 100: 63
Congratulations! You guessed the number in 3 attempts.

Question 10

A library wants a system to track borrowed books and check available stock.
Program:
# Initial book inventory
library_books = {"Python 101": 3, "Data Science Handbook": 2, "Artificial Intelligence": 4}

def display_books():
print("\nAvailable Books:")
for book, stock in library_books.items():
print(f"{book}: {stock} copies")

def borrow_book():
book_name = input("Enter the book you want to borrow: ")
if book_name in library_books and library_books[book_name] > 0:
library_books[book_name] -= 1
print(f"You have borrowed '{book_name}'. Please return it on time.")
else:
print("Sorry, the book is either not available or out of stock.")

def return_book():
book_name = input("Enter the book you want to return: ")
if book_name in library_books:
library_books[book_name] += 1
print(f"Thanks for returning '{book_name}'.")
else:
print("This book doesn't belong to our library.")

while True:
print("\nLibrary System Menu:")
print("1. Display Books")
print("2. Borrow Book")
print("3. Return Book")
print("4. Exit")

choice = int(input("Choose an option (1-4): "))


if choice == 1:
display_books()
elif choice == 2:
borrow_book()
elif choice == 3:
return_book()
elif choice == 4:
print("Thank you for visiting the library!")
break
else:
print("Invalid choice. Please try again.")
Output:
Library System Menu:
1. Display Books
2. Borrow Book
3. Return Book
4. Exit
Choose an option (1-4): 1

Available Books:
Python 101: 3 copies
Data Science Handbook: 2 copies
Artificial Intelligence: 4 copies

Library System Menu:


1. Display Books
2. Borrow Book
3. Return Book
4. Exit
Choose an option (1-4): 2
Enter the book you want to borrow: python 101
Sorry, the book is either not available or out of stock.

Library System Menu:


1. Display Books
2. Borrow Book
3. Return Book
4. Exit
Choose an option (1-4):4

Question 11
A health app needs to calculate the Body Mass Index (BMI) of users and categorize their health
status.
Program:
# BMI categories
def calculate_bmi(weight, height):
bmi = weight / (height ** 2)
if bmi < 18.5:
category = "Underweight"
elif 18.5 <= bmi < 24.9:
category = "Normal weight"
elif 25 <= bmi < 29.9:
category = "Overweight"
else:
category = "Obesity"
return bmi, category
weight = float(input("Enter your weight in kg: "))
height = float(input("Enter your height in meters: "))

bmi, category = calculate_bmi(weight, height)


print(f"\nYour BMI is {bmi:.2f}, categorized as '{category}'.")

Output:
Enter your weight in kg: 70
Enter your height in meters: 1.75
Your BMI is 22.86, categorized as 'Normal weight'.

Question 12

A program to check the strength of a password based on security criteria.


Program:
import re

def password_strength(password):
# Check for password rules
if len(password) < 8:
return "Weak: Password must be at least 8 characters long."
if not re.search(r"[A-Z]", password):
return "Weak: Include at least one uppercase letter."
if not re.search(r"[a-z]", password):
return "Weak: Include at least one lowercase letter."
if not re.search(r"[0-9]", password):
return "Weak: Include at least one digit."
if not re.search(r"[!@#$%^&*(),.?\":{}|<>]", password):
return "Weak: Include at least one special character."
return "Strong Password!"
password = input("Enter a password: ")
result = password_strength(password)
print(result)

Output:
Enter a password: Pass@2023
Strong Password!
Scenario based program for built-in functions

1. Scenario: You're working with a list of numbers and you need to


calculate the average of all numbers.

Question: How can you efficiently calculate the average of the numbers in a list using
Python’s built-in functions?
Answer: You can use sum() to get the sum of all numbers in the list and len() to get the
number of elements, then calculate the average.

python
Copy
numbers = [10, 20, 30, 40, 50]
average = sum(numbers) / len(numbers)
print(average)

Output:

Copy
30.0

2. Scenario: You have a string with some leading and trailing spaces, and you
need to remove them.

Question: How can you clean the string to remove unwanted spaces?

Answer: You can use the strip() method to remove both leading and trailing whitespaces.

python
Copy
text = " Hello, World! "
clean_text = text.strip()
print(clean_text)

Output:

Copy
Hello, World!

3. Scenario: You have a list of words, and you want to sort them in
alphabetical order.

Question: Which built-in function would you use to sort the list?

Answer: You can use the sorted() function to return a new list sorted in ascending order.

python
Copy
words = ["banana", "apple", "cherry", "date"]
sorted_words = sorted(words)
print(sorted_words)

Output:

css
Copy
['apple', 'banana', 'cherry', 'date']
4. Scenario: You want to check if a particular item exists in a list.

Question: Which built-in function can help you verify the presence of an element in a list?

Answer: You can use the in operator, which returns True if the element is present, and
False if not.

python
Copy
fruits = ["apple", "banana", "cherry"]
is_present = "banana" in fruits
print(is_present)

Output:

graphql
Copy
True

5. Scenario: You need to combine two lists into a single list, but you want the
final list to be a new list and not modify the original ones.

Question: How can you achieve this using Python built-in functions?

Answer: You can use the extend() method or the + operator. The + operator will create a
new list by concatenating both lists.

python
Copy
list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined_list = list1 + list2
print(combined_list)

Output:

csharp
Copy
[1, 2, 3, 4, 5, 6]

6. Scenario: You have a list of numbers, and you want to remove all
occurrences of a specific number.

Question: What function can help you remove an element from a list?

Answer: You can use the remove() method, which removes the first occurrence of a
specified value.

python
Copy
numbers = [10, 20, 30, 20, 40]
numbers.remove(20)
print(numbers)

Output:

csharp
Copy
[10, 30, 20, 40]

7. Scenario: You're working with a list of integers, and you want to find the
maximum value in the list.

Question: How can you find the maximum value using a built-in function?

Answer: You can use the max() function to find the largest element in the list.

python
Copy
numbers = [10, 20, 30, 40, 50]
maximum_value = max(numbers)
print(maximum_value)

Output:

Copy
50

8. Scenario: You need to create a tuple with a few values but want to ensure
that it’s immutable.

Question: How can you create a tuple using built-in functions?

Answer: You can use the tuple() function to convert a list or other iterable into a tuple.

python
Copy
my_list = [1, 2, 3]
my_tuple = tuple(my_list)
print(my_tuple)

Output:

scss
Copy
(1, 2, 3)

9. Scenario: You want to convert a list of strings into a single string, with each
word separated by a space.
Question: Which function can you use to join the elements of the list into a single string?

Answer: You can use the join() method to concatenate elements of a list into a single
string.

python
Copy
words = ["Hello", "World", "Python"]
sentence = " ".join(words)
print(sentence)

Output:

nginx
Copy
Hello World Python

10. Scenario: You want to get the length of a dictionary (i.e., the number of
key-value pairs it contains).

Question: Which built-in function would you use to get the number of elements in a
dictionary?

Answer: You can use the len() function to find out how many key-value pairs are in the
dictionary.

python
Copy
my_dict = {"name": "Alice", "age": 25, "city": "New York"}
dict_length = len(my_dict)
print(dict_length)

Output:

Copy
3

Scenario based program for database communication in python

1. Scenario: You want to connect to a local SQLite database, but the database
does not exist yet.

Question: How do you establish a connection to the SQLite database and create a new one if
it doesn’t already exist?

Answer: You can use the sqlite3 library in Python to connect to a database. If the database
doesn’t exist, SQLite will automatically create it.

python
Copy
import sqlite3
# Connecting to a database (it will create the file if it doesn't exist)
connection = sqlite3.connect('my_database.db')
cursor = connection.cursor()

# Don't forget to close the connection


connection.close()

This will create a file named my_database.db in the current directory.

2. Scenario: You need to create a table in your SQLite database to store


customer information.

Question: How can you write a Python script to create a table with fields like id, name, and
email?

Answer: You can use the CREATE TABLE SQL command within the execute() method to
create a table.

python
Copy
import sqlite3

connection = sqlite3.connect('my_database.db')
cursor = connection.cursor()

# Creating a table
cursor.execute('''
CREATE TABLE IF NOT EXISTS customers (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
email TEXT
)
''')

# Commit and close


connection.commit()
connection.close()

This script creates a customers table with id, name, and email fields.

3. Scenario: You want to insert a new record into the customers table.

Question: How can you insert customer data (e.g., name and email) into the customers
table?

Answer: You can use the INSERT INTO SQL command to insert new records.

python
Copy
import sqlite3
connection = sqlite3.connect('my_database.db')
cursor = connection.cursor()

# Inserting a new customer


cursor.execute('''
INSERT INTO customers (name, email)
VALUES (?, ?)
''', ('Alice', '[email protected]'))

# Commit and close


connection.commit()
connection.close()

This script inserts a new customer with the name "Alice" and email "[email protected]"
into the customers table.

4. Scenario: You need to retrieve all customer records from the customers
table.

Question: How can you query the database to fetch all customer records?

Answer: You can use the SELECT statement to fetch records from the database.

python
Copy
import sqlite3

connection = sqlite3.connect('my_database.db')
cursor = connection.cursor()

# Query to retrieve all customers


cursor.execute('SELECT * FROM customers')
customers = cursor.fetchall()

for customer in customers:


print(customer)

connection.close()

This script retrieves all records from the customers table and prints each customer’s data.

5. Scenario: You want to update the email address of a customer with a


specific id.

Question: How do you update a customer's email address based on their id?

Answer: You can use the UPDATE SQL command to modify records.

python
Copy
import sqlite3

connection = sqlite3.connect('my_database.db')
cursor = connection.cursor()

# Update email address for customer with id 1


cursor.execute('''
UPDATE customers
SET email = ?
WHERE id = ?
''', ('[email protected]', 1))

# Commit and close


connection.commit()
connection.close()

This script updates the email address of the customer with id = 1 to


"[email protected]".

6. Scenario: You need to delete a customer record based on their id.

Question: How do you delete a customer from the database using their id?

Answer: You can use the DELETE SQL command to remove records.

python
Copy
import sqlite3

connection = sqlite3.connect('my_database.db')
cursor = connection.cursor()

# Delete customer with id 1


cursor.execute('''
DELETE FROM customers
WHERE id = ?
''', (1,))

# Commit and close


connection.commit()
connection.close()

This script deletes the customer record with id = 1.

7. Scenario: You want to fetch a single customer’s details by their email


address.

Question: How would you query the database to find a customer by email?

Answer: You can use a SELECT query with a WHERE condition to retrieve a specific customer
by email.
python
Copy
import sqlite3

connection = sqlite3.connect('my_database.db')
cursor = connection.cursor()

# Query to find a customer by email


cursor.execute('''
SELECT * FROM customers
WHERE email = ?
''', ('[email protected]',))

customer = cursor.fetchone()
if customer:
print(customer)
else:
print("Customer not found")

connection.close()

This script fetches the customer record with the email "[email protected]" and prints it.

8. Scenario: You want to use parameterized queries to prevent SQL injection


when inserting user data.

Question: How can you ensure your database interactions are secure from SQL injection?

Answer: Use parameterized queries by passing values as parameters rather than directly
embedding them into the query string.

python
Copy
import sqlite3

connection = sqlite3.connect('my_database.db')
cursor = connection.cursor()

# Safe parameterized query to insert data


cursor.execute('''
INSERT INTO customers (name, email)
VALUES (?, ?)
''', ('Bob', '[email protected]'))

connection.commit()
connection.close()

This script uses ? placeholders to securely insert values into the query, preventing SQL
injection.

9. Scenario: You want to handle database errors and rollback transactions if


something goes wrong.
Question: How do you manage database errors and ensure a rollback in case of an
exception?

Answer: You can use a try-except block along with connection.rollback() to ensure
data integrity.

python
Copy
import sqlite3

try:
connection = sqlite3.connect('my_database.db')
cursor = connection.cursor()

# Attempting to insert data into the database


cursor.execute('''
INSERT INTO customers (name, email)
VALUES (?, ?)
''', ('Charlie', '[email protected]'))

# Commit if everything is fine


connection.commit()

except sqlite3.Error as e:
print(f"Error occurred: {e}")
connection.rollback()

finally:
connection.close()

This ensures that if an error occurs during the transaction, it is rolled back and no changes are
made to the database.

10. Scenario: You need to execute multiple queries at once in a batch, such as
inserting several records.

Question: How can you efficiently execute multiple SQL queries at once?

Answer: You can use executemany() to execute a batch of queries.

python
Copy
import sqlite3

connection = sqlite3.connect('my_database.db')
cursor = connection.cursor()

# List of customer records to insert


customers_data = [
('David', '[email protected]'),
('Eva', '[email protected]'),
('Frank', '[email protected]')
]
# Inserting multiple records at once
cursor.executemany('''
INSERT INTO customers (name, email)
VALUES (?, ?)
''', customers_data)

# Commit and close


connection.commit()
connection.close()

This script inserts multiple customer records at once using executemany().

scenario based questions with answers for data analysis and visualization
using python

1. Scenario: You have a dataset of sales records, and you need to calculate the
total sales for each product.

Question: How do you calculate the total sales for each product using Python?

Answer: You can use the groupby() function in Pandas to group data by product and then
use sum() to calculate total sales.

python
Copy
import pandas as pd

# Sample sales data


data = {
'product': ['A', 'B', 'A', 'C', 'B', 'A'],
'sales': [100, 150, 200, 300, 250, 50]
}
df = pd.DataFrame(data)

# Group by 'product' and calculate total sales


total_sales = df.groupby('product')['sales'].sum()
print(total_sales)

Output:

css
Copy
product
A 350
B 400
C 300
Name: sales, dtype: int64

2. Scenario: You have a dataset with customer age and purchase data, and
you want to visualize how purchases vary with age.

Question: How can you create a scatter plot to visualize the relationship between customer
age and their purchases?
Answer: You can use Matplotlib or Seaborn to create a scatter plot.

python
Copy
import matplotlib.pyplot as plt
import pandas as pd

# Sample data
data = {
'age': [22, 25, 30, 35, 40, 45, 50],
'purchase_amount': [200, 250, 300, 350, 400, 450, 500]
}
df = pd.DataFrame(data)

# Scatter plot
plt.scatter(df['age'], df['purchase_amount'])
plt.title('Purchase Amount vs Age')
plt.xlabel('Age')
plt.ylabel('Purchase Amount')
plt.show()

This code generates a scatter plot showing how purchase amounts change with age.

3. Scenario: You want to check if there are any missing values in a dataset and
handle them appropriately.

Question: How do you detect and fill missing values in a dataset?

Answer: You can use Pandas’ isnull() to detect missing values and fillna() to fill them.

python
Copy
import pandas as pd

# Sample data with missing values


data = {
'product': ['A', 'B', 'A', 'C', None],
'sales': [100, None, 200, 300, 150]
}
df = pd.DataFrame(data)

# Detecting missing values


print(df.isnull())

# Filling missing values with a placeholder (e.g., 'Unknown' for product


and median for sales)
df['product'].fillna('Unknown', inplace=True)
df['sales'].fillna(df['sales'].median(), inplace=True)

print(df)

Output:

mathematica
Copy
product sales
0 False False
1 False True
2 False False
3 False False
4 True False

product sales
0 A 100.0
1 B 200.0
2 A 200.0
3 C 300.0
4 Unknown 150.0

This code fills missing product values with "Unknown" and sales values with the median.

4. Scenario: You need to visualize the distribution of a numerical variable,


like salary.

Question: How can you visualize the distribution of salaries using a histogram?

Answer: You can use Matplotlib or Seaborn to create a histogram.

python
Copy
import seaborn as sns
import matplotlib.pyplot as plt

# Sample salary data


data = {
'salary': [45000, 50000, 55000, 60000, 45000, 50000, 65000, 70000,
75000, 60000]
}
df = pd.DataFrame(data)

# Histogram using seaborn


sns.histplot(df['salary'], kde=True)
plt.title('Salary Distribution')
plt.xlabel('Salary')
plt.ylabel('Frequency')
plt.show()

This code generates a histogram showing the distribution of salaries along with a Kernel
Density Estimate (KDE) curve.

5. Scenario: You want to compare the average sales across different product
categories and visualize the results in a bar plot.

Question: How do you calculate the average sales by product and visualize it with a bar plot?
Answer: You can use groupby() to calculate the average sales by product and then use a
bar plot to visualize the results.

python
Copy
import pandas as pd
import matplotlib.pyplot as plt

# Sample data
data = {
'product': ['A', 'B', 'A', 'C', 'B', 'A'],
'sales': [100, 150, 200, 300, 250, 50]
}
df = pd.DataFrame(data)

# Calculate average sales by product


avg_sales = df.groupby('product')['sales'].mean()

# Bar plot
avg_sales.plot(kind='bar')
plt.title('Average Sales by Product')
plt.xlabel('Product')
plt.ylabel('Average Sales')
plt.show()

This code generates a bar plot showing the average sales for each product.

6. Scenario: You want to see if there’s a correlation between two variables,


like age and income.

Question: How can you create a correlation heatmap to show the relationship between age
and income?

Answer: You can use Seaborn’s heatmap() function to create a correlation matrix.

python
Copy
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd

# Sample data
data = {
'age': [22, 25, 30, 35, 40, 45, 50],
'income': [30000, 35000, 40000, 45000, 50000, 55000, 60000]
}
df = pd.DataFrame(data)

# Calculate correlation matrix


corr = df.corr()

# Heatmap of correlation
sns.heatmap(corr, annot=True, cmap='coolwarm', vmin=-1, vmax=1)
plt.title('Correlation Heatmap: Age vs Income')
plt.show()
This creates a heatmap to visualize the correlation between age and income.

7. Scenario: You need to visualize the relationship between multiple variables,


such as sales, advertising budget, and region.

Question: How can you use a pair plot to visualize multiple variables?

Answer: Seaborn’s pairplot() is useful for visualizing the relationships between multiple
numerical variables.

python
Copy
import seaborn as sns
import pandas as pd

# Sample data with multiple variables


data = {
'sales': [100, 200, 300, 400, 500],
'advertising': [10, 20, 30, 40, 50],
'region': ['North', 'South', 'East', 'West', 'North']
}
df = pd.DataFrame(data)

# Pairplot
sns.pairplot(df, hue='region')
plt.show()

This code creates a pair plot that visualizes the relationships between sales, advertising,
and region.

8. Scenario: You want to visualize the time series of daily temperatures over
the past year.

Question: How do you plot a time series graph for the temperature data?

Answer: You can use Matplotlib to plot time series data. Here, you can simulate daily
temperature data.

python
Copy
import matplotlib.pyplot as plt
import pandas as pd

# Sample temperature data for the past year


date_range = pd.date_range(start='2024-01-01', periods=365, freq='D')
temperature = [15 + (i % 30) for i in range(365)] # Simulated daily
temperatures

df = pd.DataFrame({'date': date_range, 'temperature': temperature})


# Plot time series
plt.plot(df['date'], df['temperature'])
plt.title('Daily Temperatures Over the Past Year')
plt.xlabel('Date')
plt.ylabel('Temperature (°C)')
plt.xticks(rotation=45)
plt.show()

This code generates a time series plot for daily temperatures.

9. Scenario: You have a dataset with sales data across different regions, and
you need to visualize how sales vary by region.

Question: How can you create a box plot to show sales distribution across regions?

Answer: You can use Seaborn’s boxplot() function to visualize the distribution of sales
across different regions.

python
Copy
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd

# Sample data
data = {
'region': ['North', 'South', 'East', 'West', 'North', 'South', 'East',
'West'],
'sales': [100, 200, 150, 300, 120, 220, 180, 280]
}
df = pd.DataFrame(data)

# Box plot for sales by region


sns.boxplot(x='region', y='sales', data=df)
plt.title('Sales Distribution by Region')
plt.show()

This box plot shows how sales are distributed across different regions.

You might also like