Scenario Based Python Questions-Unit 1
Scenario Based Python Questions-Unit 1
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:
Program:
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()
The player starts at the entrance of a mysterious cave. They have three choices:
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:
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")
Imagine you are building a program for a teacher to calculate the average grade of students in
a class. The teacher wants to:
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
Output:
Question 4
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
Output:
Updated grades with averages have been saved to 'grades_with_average.csv'.
Question 5
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.
Program:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# Sales by Region
sales_by_region = data.groupby("Region")["Sales"].sum()
print("\nSales by Region:")
print(sales_by_region)
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
}
# 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())
# 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
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
Question 8
A bank wants an ATM simulation that allows withdrawals with balance checks.
Program:
# Initial account balance
balance = 5000.00
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
while True:
guess = int(input("Guess a number between 1 and 100: "))
attempts += 1
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")
Available Books:
Python 101: 3 copies
Data Science Handbook: 2 copies
Artificial Intelligence: 4 copies
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: "))
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
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
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.
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
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()
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
)
''')
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()
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()
connection.close()
This script retrieves all records from the customers table and prints each customer’s data.
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()
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()
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()
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.
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()
connection.commit()
connection.close()
This script uses ? placeholders to securely insert values into the query, preventing SQL
injection.
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()
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?
python
Copy
import sqlite3
connection = sqlite3.connect('my_database.db')
cursor = connection.cursor()
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
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.
Answer: You can use Pandas’ isnull() to detect missing values and fillna() to fill them.
python
Copy
import pandas as pd
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.
Question: How can you visualize the distribution of salaries using a histogram?
python
Copy
import seaborn as sns
import matplotlib.pyplot as plt
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)
# 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.
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)
# 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.
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
# 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
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)
This box plot shows how sales are distributed across different regions.