Scenario-Based Coding Problems on Python Functions

Functions make coding easier by breaking tasks into smaller parts, but learning them can be more exciting with real-world challenges! Imagine designing a game’s scoring system, checking for duplicate items in a list, or working with nested loops and arrays to solve complex problems using functions. Syntax Scenarios is here with fun, scenario-based coding challenges that cover functions with and without arguments, return values, and overloaded functions. These problems will help you understand how functions work and how they make coding more efficient and practical. 
Each challenge comes with a clear scenario, a step-by-step explanation, a well-organized Python solution, and a test case to help you practice. 

Note: You can view the answer code and its explanation by clicking on the question (or the drop-down icon).

How many Pizza Slices did you get?

Pizza Slices Python Funtions Problem
You and your friends have ordered a large pizza. You want to ensure that everyone gets an equal number of slices. Write a Python function calculate_slices() that takes the number of people and the total pizza slices as input and returns the number of slices each person gets. If slices can’t be divided equally, print how many remain.

Test Case:
Input: 
people= 4
slices= 10  
Expected Output: 
Each person gets 2 slices. 2 slices remain.

Explanation:
This code helps people share pizza slices fairly. It calculates how many slices each person gets and how many are left.

  • First, it defines a function called calculate_slices(), which takes two numbers: people (number of people) and slices (total pizza slices).
  • Inside the function, // (floor division) is used to divide slices equally. The result is stored in each_person.
  • Next, since some slices might not divide perfectly, % (modulus) is used to find the leftover slices. The result is stored in remaining.
  • After that, the function returns both each_person and remaining to the main code.
  • Then, in the main part of the code, input() asks for numbers. However, since input() takes text, int() converts it into actual numbers.
  • Once the numbers are ready, calculate_slices(people, slices) is called, and the results are stored in each and left.
  • Afterward, the program prints how many slices each person gets. If there are extra slices, it prints how many are left.
def calculate_slices(people, slices):
    each_person = slices // people
    remaining = slices % people
    return each_person, remaining

people = int(input("Enter the number of people: "))
slices = int(input("Enter the total number of pizza slices: "))

each, left = calculate_slices(people, slices)
print(f"Each person gets {each} slices.")
if left > 0:
    print(f"{left} slice(s) remain.")

Speeding Ticket Checker

Speeding Ticket Checker Python Function Problem
A traffic police officer checks if a car is speeding. The speed limit is 60 km/h. Write a function check_speed(speed) that takes the car’s speed as input and prints if the driver is “Safe”, “Warning”, or “Over Speeding”.

Test Case:
Input:
speed= 85  
Expected Output:
Over Speeding!

Explanation:
This code checks if a car’s speed is safe, needs a warning, or is over the limit.

  • First, it defines a function called check_speed(), which takes one number: speed (the car’s speed).
  • Inside the function, a if statement checks if the speed is 60 or less. If true, it prints "Safe".
  • Next, an elif statement checks if the speed is between 61 and 80. If true, it prints "Warning".
  • Otherwise, if the speed is above 80, the else statement prints "Over Speeding!".
  • After defining the function, the main code uses input() to ask for the car’s speed. However, since input() takes text, int() converts it into a number.
  • Then, check_speed(speed) is called to check the speed and display the correct message.
def check_speed(speed):
    if speed <= 60:
        print("Safe")
    elif speed <= 80:
        print("Warning")
    else:
        print("Over Speeding!")

speed = int(input("Enter the car speed: "))
check_speed(speed)

Temperature Converter

Temperature Converter Python Function Problem
You are conducting a science experiment in your lab practical, where precise temperature measurements are crucial. However, the thermometer provided measures temperature in Celsius, while your experiment requires readings in Fahrenheit. To ensure accuracy in your observations and calculations, you decide to write a function that converts temperature from Celsius to Fahrenheit.

Test Case:
Input:
celsius= 25  
Expected Output:
Temperature in Fahrenheit: 77.00°F

Explanation:
This code converts a temperature from Celsius to Fahrenheit.

  • First, it defines a function called convert_temp(), which takes one number: celsius (the temperature in Celsius).
  • Inside the function, it uses the formula (celsius * 9/5) + 32 to convert the temperature into Fahrenheit and returns the result.
  • In the main part of the code, input() asks for the temperature in Celsius. Since input() takes text, float() converts it into a decimal number.
  • Then, convert_temp(celsius) is called to convert the Celsius temperature into Fahrenheit. The result is stored in fahrenheit.
  • Finally, the program uses print() to display the Fahrenheit temperature, formatted to two decimal places using {fahrenheit:.2f}.
  • This way, the code helps you easily convert temperatures between Celsius and Fahrenheit! 🌡️
def convert_temp(celsius):
    return (celsius * 9/5) + 32

celsius = float(input("Enter temperature in Celsius: "))
fahrenheit = convert_temp(celsius)
print(f"Temperature in Fahrenheit: {fahrenheit:.2f}")

Area Calculator

Area Calculator Python Function Problem
You are building a geometry calculator for a school project to assist students in calculating the area or volume of different shapes. The goal is to create a single function that can handle multiple shapes based on the number of arguments provided:
If one argument is given, the shape is assumed to be a circle, and the function calculates the area using the formula: π×r^2.
If two arguments are given, the shape is assumed to be a rectangle, and the function calculates the area using the formula: length × width.
If three arguments are given, the shape is assumed to be a cuboid, and the function calculates the volume using the formula: length × width × height.

Test Case:
Input:
a = 5
Expected Output:
Circle Area: 78.53975

Explanation:
This code calculates the area of different shapes: a circle, a rectangle, or the volume of a cuboid.

  • First, it defines a function called calculate_area(), which takes three parameters: a, b, and c. The parameters b and c have default values of None.
  • Inside the function:
    • If both b and c are None, it calculates the area of a circle using the formula 3.14159 * a * a and returns the result.
    • If only c is None, it calculates the area of a rectangle using the formula a * b and returns the result.
    • If neither b nor c is None, it calculates the volume of a cuboid using the formula a * b * c and returns the result.
  • In the main part of the code, calculate_area(5) calculates the area of a circle with radius 5.
  • Then, calculate_area(4, 6) calculates the area of a rectangle with length 4 and width 6.
  • Finally, calculate_area(3, 4, 5) calculates the volume of a cuboid with length 3, width 4, and height 5.
def calculate_area(a, b=None, c=None):
    if b is None and c is None:  
        return 3.14159 * a * a  # Circle area using π approximated
    elif c is None:  
        return a * b  # Rectangle area
    else:  
        return a * b * c  # Cuboid volume

print("Circle Area:", calculate_area(5))
print("Rectangle Area:", calculate_area(4, 6))
print("Cuboid Volume:", calculate_area(3, 4, 5))

Is it a Prime Number?

Prime Number Python Funtion Problem
Imagine you are building a number analysis tool for a math class project. One of the requirements is to implement a function that checks whether a given number is prime or not. A prime number is a number greater than 1 that has no divisors other than 1 and itself. This function will help students quickly determine if a number is prime, which is essential for understanding factors, divisibility, and prime factorization.

Test Case:
Input:
Enter a number: 11
Expected Output:
Is 11 prime? True

Explanation:
This code checks whether a number is prime or not.

  • First, it defines a function called is_prime(), which takes one number n to check if it’s prime.
  • Inside the function:
    • If n is less than 2, it immediately returns False because numbers less than 2 are not prime.
    • Then, it uses a for loop to check if n is divisible by any number between 2 and the square root of n (rounded down). This is done using range(2, int(n**0.5) + 1).
    • If n is divisible by any of these numbers (i.e., n % i == 0), it returns False, meaning the number is not prime.
    • If no divisors are found, the function returns True, meaning the number is prime.
  • In the main part of the code, input() asks the user for a number. Since input() takes text, int() converts it into an integer.
  • Finally, is_prime(num) checks if the number is prime, and print() displays whether the number is prime or not.
def is_prime(n):
    if n < 2:
        return False  # Numbers less than 2 are not prime
    for i in range(2, int(n**0.5) + 1):
        if n % i == 0:  # If divisible by any number other than 1 and itself
            return False
    return True

num = int(input("Enter a number: "))  # Ask the user to input a number
print(f"Is {num} prime? {is_prime(num)}")  # Check if the number is prime

Generate Multiplication Table

Generate Multiplication Table Python Funtion Problem
You are helping your younger sibling prepare for a math quiz by creating a simple multiplication table generator. Instead of manually writing out tables, you decide to write a Python function that takes any number as input and displays its multiplication table up to 10. This tool will make it easier for your sibling to practice and learn multiplication quickly.

Test Case:
Input:
Enter a number: 5
Expected Output:
5 x 1 = 5  
5 x 2 = 10  
5 x 3 = 15  
5 x 4 = 20  
5 x 5 = 25  
5 x 6 = 30  
5 x 7 = 35  
5 x 8 = 40  
5 x 9 = 45  
5 x 10 = 50 

Explanation:
This code prints the multiplication table of a given number.

  • First, it defines a function called multiplication_table(), which takes one number n as input.
  • Inside the function, a for loop runs from 1 to 10 using range(1, 11).
  • In each loop, the program multiplies n by i to get the table values and prints the result using print(f"{n} x {i} = {n * i}").
  • In the main part of the code, input() asks the user for a number. Since input() takes text, int() converts it into a number.
  • Then, multiplication_table(num) is called to print the table of that number.
def multiplication_table(n):
    for i in range(1, 11):  # Loop from 1 to 10
        print(f"{n} x {i} = {n * i}") 

num = int(input("Enter a number: ")) 
multiplication_table(num) 

Digit Payment System

Digit Payment System Python Funtion Problem
You are developing a secure and flexible digital payment system for an online shopping platform. Since users prefer different payment methods, your system needs to handle various options:
Card Payment: When users enter only the amount, it is processed as a standard card payment.
Card Payment with CVV: If users provide the amount and a CVV, an extra security check is performed.
Online Wallet Payment: If users pay via an online wallet, they must enter their email and transaction ID for verification.
For smooth transactions, you create a function that processes payments based on the number of arguments provided.

Test Case:
Input:
Select Payment Method: 
1. Card Payment
2. Card Payment with CVV
3. Online Wallet
Enter choice (1-3): 3
Enter payment amount: 200
Enter wallet email: user@example.com
Enter transaction ID: TXN987654
Expected Output:
Payment of $200 processed via Wallet (user@example.com) with transaction ID TXN987654.

Explanation:
This code processes payments using different methods: Card, Card with CVV, or Online Wallet.

  • First, it defines a function called process_payment(*args), which takes a variable number of arguments (*args).
  • Inside the function:
    • If there is one argument, it assumes a card payment and returns "Payment of $amount processed using Card."
    • If there are two arguments, it assumes a card payment with CVV and returns "Payment of $amount processed using Card with CVV."
    • If there are three arguments, it assumes an online wallet payment and returns "Payment of $amount processed via Wallet with transaction ID."
    • If the number of arguments does not match these cases, it returns "Invalid payment method."
  • In the main part of the code, input() asks the user to select a payment method:
    • If the user selects 1, they enter an amount, and process_payment(amount) is called.
    • If the user selects 2, they enter an amount and a CVV, then process_payment(amount, cvv) is called.
    • If the user selects 3, they enter an amount, wallet email, and transaction ID, then process_payment(amount, email, txn_id) is called.
    • If the user enters an invalid choice, it prints "Invalid choice! Please select a valid payment method."
def process_payment(*args):
    if len(args) == 1:
        return f"Payment of ${args[0]} processed using Card."
    elif len(args) == 2:
        return f"Payment of ${args[0]} processed using Card with CVV {args[1]}."
    elif len(args) == 3:
        return f"Payment of ${args[0]} processed via Wallet ({args[1]}) with transaction ID {args[2]}."
    else:
        return "Invalid payment method."

payment_method = int(input("Select Payment Method: \n1. Card Payment\n2. Card Payment with CVV\n3. Online Wallet\nEnter choice (1-3): "))

if payment_method == 1:
    amount = float(input("Enter payment amount: "))
    print(process_payment(amount))

elif payment_method == 2:
    amount = float(input("Enter payment amount: "))
    cvv = int(input("Enter CVV: "))
    print(process_payment(amount, cvv))

elif payment_method == 3:
    amount = float(input("Enter payment amount: "))
    email = input("Enter wallet email: ")
    txn_id = input("Enter transaction ID: ")
    print(process_payment(amount, email, txn_id))

else:
    print("Invalid choice! Please select a valid payment method.")

Give the Toll Tax

Give the Toll Tax Python Funtion Problem
Suppose you are traveling on a highway and approach a toll plaza. The toll charges vary depending on the type of vehicle. A car is charged $5, a truck is charged $10, and a bike is charged $2. The system should ask for the vehicle type and display the corresponding toll tax. If the vehicle type is incorrect, it should show an invalid vehicle type message.

Test Case:
Input:
Enter vehicle type (car/truck/bike): car
Expected Output:
Toll tax: $5

Explanation:
This code calculates the toll tax based on the type of vehicle.

  • First, it defines a function called toll_tax(), which takes vehicle_type as input.
  • Inside the function:
    • vehicle_type.lower() converts the input to lowercase to avoid case sensitivity issues.
    • If the vehicle_type is "car", it returns 5 as the toll tax.
    • If it is "truck", it returns 10.
    • If it is "bike", it returns 2.
    • If the input does not match any of these, it returns "Invalid vehicle type".
  • In the main part of the code, input() asks the user to enter a vehicle type.
  • The function toll_tax(vehicle) is called to get the toll tax for the entered vehicle type.
  • Finally, print() displays the toll tax amount.
def toll_tax(vehicle_type):
    vehicle_type = vehicle_type.lower()  # Convert input to lowercase for consistency
    
    if vehicle_type == "car":
        return 5
    elif vehicle_type == "truck":
        return 10
    elif vehicle_type == "bike":
        return 2
    else:
        return "Invalid vehicle type"

vehicle = input("Enter vehicle type (car/truck/bike): ")
tax = toll_tax(vehicle)

print(f"Toll tax: ${tax}")

2D Matrix Sum

2D Matrix Sum Python Funtion Problem
You are working on a data analysis project that involves processing a 2D matrix containing numerical data. One of the tasks requires calculating the sum of all elements in the matrix to analyze the total value. You need to write a function that takes a 2D list (matrix) as input and returns the sum of all its elements.

Test Case:
Input:
Enter number of rows: 2  
Enter number of columns: 3  
Enter the matrix elements row by row:  
Element [1,1]: 1  
Element [1,2]: 2  
Element [1,3]: 3  
Element [2,1]: 4  
Element [2,2]: 5  
Element [2,3]: 6  
Expected Output:
Entered Matrix:
[1, 2, 3]
[4, 5, 6]

Sum of all elements: 21

Explanation:
This code calculates the sum of all elements in a matrix.

  • First, it defines a function sum_matrix(matrix) that takes a matrix as input.
  • Inside the function:
    • A variable total is initialized to zero.
    • A loop goes through each row of the matrix.
    • Another loop inside it goes through each element in the row and adds it to total.
    • Finally, the function returns the total sum.
  • In the main part of the code, the user is asked to enter the number of rows and columns of the matrix.
  • An empty list called matrix is created to store the matrix elements.
  • A loop runs for each row, and another loop inside it takes integer inputs for each column. The values are stored in a list and added to matrix.
  • After all inputs are taken, the matrix is displayed by printing each row.
  • The function sum_matrix(matrix) is called to calculate the sum, and the result is printed.
def sum_matrix(matrix):
    total = 0
    for row in matrix:  # Loop through each row
        for num in row:  # Loop through each element in the row
            total += num  # Add element to total
    return total

# Taking input for matrix dimensions
rows = int(input("Enter number of rows: "))
cols = int(input("Enter number of columns: "))

# Initializing an empty matrix
matrix = []

# Taking user input for the matrix
print("Enter the matrix elements row by row:")
for i in range(rows):
    row = []
    for j in range(cols):
        row.append(int(input(f"Element [{i+1},{j+1}]: ")))  # Take integer input
    matrix.append(row)

print("\nEntered Matrix:")
for row in matrix:
    print(row)

print(f"\nSum of all elements: {sum_matrix(matrix)}")

Smart Expense Manager

Smart Expense Manager Python Funtion Problem
For instance you want to build a simple expense tracker that helps you record daily expenses. The program should:
Add expenses by taking the item name and amount spent.
Calculate the total expenses manually without using built-in sum functions.
Find the most expensive item without using predefined functions like max().
This will allow you to track your spending habits and identify where most of your money goes.

Test Case:
Input:
Enter number of expenses: 3  
Enter item name: Laptop  
Enter amount spent on Laptop: $1200  
Enter item name: Coffee  
Enter amount spent on Coffee: $5  
Enter item name: Headphones  
Enter amount spent on Headphones: $150  
Expected Output:
Total expenses: $1355.00  
Most expensive item: Laptop

Explanation:
This code helps track expenses by storing item names, their costs, calculating the total expenses, and finding the most expensive item.

  • The add_expense() function takes lists items and amounts along with an item name and its amount.
    • It adds the item name to items and its amount to amounts.
  • The calculate_total() function calculates the total expenses.
    • It starts with total = 0, then loops through all values in amounts, adding each value to total.
    • Finally, it returns the total sum.
  • The most_expensive_item() function finds the most expensive item.
    • It assumes the first item is the most expensive by setting max_index = 0.
    • Then, it loops through the amounts list and updates max_index if a higher value is found.
    • It returns the item name at max_index.
  • In the main part of the code, two empty lists items and amounts are created to store item names and their costs.
  • The user enters the number of expenses (n).
  • A loop runs n times, asking for an item name and its amount, which are stored using add_expense().
  • Finally, calculate_total(amounts) is called to get the total expenses, and most_expensive_item(items, amounts) is used to find the costliest item.
  • Both results are printed.
# Function to add an expense
def add_expense(expenses, items, amounts, item, amount):
    items.append(item)   # Store item name
    amounts.append(amount)  # Store item cost

# Function to calculate total expenses manually
def calculate_total(amounts):
    total = 0
    for amount in amounts:  # Loop through all expense amounts
        total += amount  # Add amount to total
    return total

# Function to find the most expensive item
def most_expensive_item(items, amounts):
    max_index = 0  # Assume first item is the most expensive
    for i in range(1, len(amounts)):  # Iterate through amounts list
        if amounts[i] > amounts[max_index]:  # Compare values
            max_index = i  # Update index if a higher value is found
    return items[max_index]  # Return the most expensive item's name

items = []  # List to store item names
amounts = []  # List to store expense amounts

n = int(input("Enter number of expenses: "))

for _ in range(n):
    item = input("Enter item name: ")
    amount = float(input(f"Enter amount spent on {item}: $"))
    add_expense(items, amounts, item, amount)

print(f"\nTotal expenses: ${calculate_total(amounts):.2f}")
print(f"Most expensive item: {most_expensive_item(items, amounts)}")

Ride Fare Split

Ride Fare Split Python Funtion Problem
A group of friends goes out for dinner and takes a taxi home. They decide to split the taxi fare among themselves, including a tip for the driver. However, one of them offers to pay extra upfront, so the others need to adjust their shares to settle the amount fairly.
The program will:
Calculate the total fare, including the tip.
Divide the total cost equally among all passengers.
Adjust payments if someone has already paid extra.

Test Case:
Input:
Enter the taxi fare: $50  
Enter tip percentage: 10  
Enter number of passengers: 4  

Did anyone pay extra? yes  
Enter the name of the person who paid extra: Alice  
How much extra did Alice pay? $20  
Expected Output:
Total fare (including tip): $55.00  
Each person should pay: $13.75  

Alice should get back $6.25 from others.

Explanation:
This code calculates the total taxi fare, including a tip, splits it among passengers, and adjusts payments if someone paid extra.

  • The calculate_fare() function takes base_fare and tip_percent, calculates the tip using (base_fare * tip_percent) / 100, and adds it to base_fare to get the total fare.
  • The split_fare() function divides the total_fare equally among num_people and rounds the result to 2 decimal places.
  • The extra_payment_adjustment() function calculates each passenger’s fair share by dividing total_fare by num_people.
    • It then subtracts the extra_paid amount and rounds the result to 2 decimal places.
  • The program starts by taking input for the base_fare, tip_percent, and num_people.
  • It then calculates the total_fare (including the tip) using calculate_fare() and determines how much each passenger should pay using split_fare().
    • Both values are printed.
  • The program then checks if anyone paid extra by asking the user.
    • If “yes,” it takes the name of the person and the extra_paid amount.
    • It then calls extra_payment_adjustment() to check if the person should receive money back or still needs to pay more.
  • Finally, it prints whether the person should get back money from others or still owes an amount.
# Function to calculate total fare with tip
def calculate_fare(base_fare, tip_percent):
    tip_amount = (base_fare * tip_percent) / 100  # Calculate tip amount
    return base_fare + tip_amount  # Add tip to base fare

# Function to split the fare equally among passengers
def split_fare(total_fare, num_people):
    return round(total_fare / num_people, 2)  # Divide and round to 2 decimal places

# Function to adjust payments if someone paid extra
def extra_payment_adjustment(total_fare, extra_paid, num_people):
    each_share = total_fare / num_people  # Calculate individual share
    return round(each_share - extra_paid, 2)  # Adjust for extra payment

base_fare = float(input("Enter the taxi fare: $"))
tip_percent = float(input("Enter tip percentage: "))
num_people = int(input("Enter number of passengers: "))

# Calculate total fare and equal split
total_fare = calculate_fare(base_fare, tip_percent)
equal_split = split_fare(total_fare, num_people)

print(f"\nTotal fare (including tip): ${total_fare:.2f}")
print(f"Each person should pay: ${equal_split}")

# Check if someone paid extra
extra_person = input("\nDid anyone pay extra? (yes/no): ").strip().lower()
if extra_person == "yes":
    name = input("Enter the name of the person who paid extra: ")
    extra_paid = float(input(f"How much extra did {name} pay? $"))
    adjusted_amount = extra_payment_adjustment(total_fare, extra_paid, num_people)

    if adjusted_amount < 0:
        print(f"{name} should get back ${-adjusted_amount} from others.")
    else:
        print(f"{name} still needs to pay ${adjusted_amount}.")

Game Scoring System

Game Scoring System Python Function Problem
You are developing a scoring system for an online multiplayer game. Players earn points based on their actions in each round:
Kills give high points.
Assists contribute to teamwork.
Completing objectives gives the most points.
However, to make the game more competitive and fair, additional rules apply:
A streak multiplier is given if a player performs 3 or more consecutive actions.
A penalty is applied if a player is inactive (does nothing) for a round.
The program calculates the final score based on these rules.

Test Case:
Input:
Enter actions: kill kill assist objective  
Enter streak count: 3  
Enter number of inactive rounds: 1  
Expected Output:
Final Score: 550.00

Explanation:
This program calculates a player’s final score based on actions performed in a game, applying bonuses for streaks and penalties for inactivity.

  • The calculate_score() function takes a list of actions and initializes score to 0. It loops through each action and adds points:
    • "kill" adds 100 points
    • "assist" adds 50 points
    • "objective" adds 150 points
      The function returns the total score.
  • The apply_streak_bonus() function checks if streak_count is 3 or more.
    • If true, it applies a 50% bonus by multiplying score by 1.5;
    • otherwise, it returns the original score.
  • The apply_inactivity_penalty() function deducts 50 points per inactive round.
    • If the new score goes below 0, it resets it to 0.
    • This prevents negative scores.
  • The program takes user input:
    • actions as a space-separated string, which is split into a list.
    • streak_count as an integer.
    • inactive_rounds as an integer.
  • It calculates the base score using calculate_score().
  • It applies a streak bonus using apply_streak_bonus().
  • It applies an inactivity penalty using apply_inactivity_penalty().
  • Finally, it prints the Final Score rounded to two decimal places.
# Function to calculate base score from actions
def calculate_score(actions):
    score = 0
    for action in actions:
        if action == "kill":
            score += 100
        elif action == "assist":
            score += 50
        elif action == "objective":
            score += 150
    return score

# Function to apply streak bonus
def apply_streak_bonus(score, streak_count):
    if streak_count >= 3:
        return score * 1.5  # 50% bonus for streaks
    return score

# Function to apply inactivity penalty without using max()
def apply_inactivity_penalty(score, inactive_rounds):
    penalty = inactive_rounds * 50  # 50 points deducted per inactive round
    new_score = score - penalty  # Subtract penalty
    if new_score < 0:  # Ensure score doesn't go below 0
        new_score = 0
    return new_score

actions = input("Enter actions (kill/assist/objective) separated by space: ").split()
streak_count = int(input("Enter streak count: "))
inactive_rounds = int(input("Enter number of inactive rounds: "))

# Score Calculation
score = calculate_score(actions)
score = apply_streak_bonus(score, streak_count)
score = apply_inactivity_penalty(score, inactive_rounds)

print(f"Final Score: {score:.2f}")

Checking for Duplicate Items in a List

Duplicate Items in a List Python Funtion Problem
Suppose you are managing a warehouse inventory system where each product has a unique ID. Before updating the stock records, you must verify that no duplicate product IDs exist in the list. If any duplicates are found, they should be reported; otherwise, confirm that all product IDs are unique.

Test Case:
Input:
Enter product IDs: A101 B202 C303 A101 D404 C303  
Expected Output:
Duplicate product IDs found: A101, C303

Explanation:
This program finds and prints duplicate product IDs from a list entered by the user.

  • The find_duplicates() function takes a list of items (product IDs) as input.
  • It creates two empty lists:
    • seen to track unique product IDs.
    • duplicates to store duplicate product IDs.
  • The function loops through each item in the list:
    • It checks if the item is already in the seen list using a nested loop.
    • If the item is found in seen, it marks it as a duplicate using is_duplicate = True.
    • If the item is a duplicate, another loop checks if it’s already in the duplicates list to avoid adding the same duplicate twice.
    • If the item is not already in duplicates, it gets added to the list.
    • If the item is not a duplicate, it is added to the seen list.
  • After checking all items, the function returns the duplicates list.
  • In the main part of the code:
    • input() asks the user to enter product IDs, separated by spaces.
    • split() converts the input string into a list of product IDs.
    • find_duplicates(items) is called to get the list of duplicates.
    • If the length of duplicates is greater than 0, it prints the duplicate product IDs. Otherwise, it prints "No duplicate product IDs found."
# Function to find duplicate product IDs
def find_duplicates(items):
    seen = []  # List to track seen items
    duplicates = []  # List to store duplicate items

    for item in items:
        is_duplicate = False
        # Check if item is already seen
        for seen_item in seen:
            if item == seen_item:
                is_duplicate = True
                break
        # If duplicate, add to duplicates list if not already added
        if is_duplicate:
            already_in_duplicates = False
            for dup in duplicates:
                if item == dup:
                    already_in_duplicates = True
                    break
            if not already_in_duplicates:
                duplicates.append(item)
        else:
            seen.append(item)  # Add item to seen list
    
    return duplicates  # Return list of duplicate items

items = input("Enter product IDs separated by space: ").split()
duplicates = find_duplicates(items)

if len(duplicates) > 0:
    print("Duplicate product IDs found: " + ", ".join(duplicates))
else:
    print("No duplicate product IDs found.")

Movie Theater Seat Booking

Movie Theater Seat Booking Python FUntion Problem
Imagine you are designing a seat booking system for a movie theater. The theater has 5 rows and 5 columns of seats. Some seats are already booked, and these are marked with “X”, while available seats are marked with “O”.
Users should be able to:
View the current seating arrangement.
Enter a row and column number to check if a seat is available.
Book multiple seats in one session until they decide to stop.
See the updated seating chart after each booking.
Construct the scenario using functions in Python.

Test Case:
Input:
Current Seating Arrangement:  
O X O O X  
O O X O O  
X O O X O  
O O X O X  
O X O X O  

Enter row (0-4): 2  
Enter column (0-4): 1  

Do you want to book another seat? (yes/no): yes  

Enter row (0-4): 3  
Enter column (0-4): 2  

Do you want to book another seat? (yes/no): no  
Expected Output:
Seat booked successfully!  

Sorry, this seat is already booked.  

Final Seating Arrangement:  
O X O O X  
O O X O O  
X X O X O  
O O X O X  
O X O X O  

Thank you for using the seat booking system!

Explanation:
This program simulates a simple seat booking system where users can select and book available seats in a 5×5 seating arrangement.

  • The display_seats() function prints the seating arrangement. It loops through each row and prints the seat status (O for available, X for booked).
  • The is_seat_available() function checks if a selected seat is available by verifying if it contains "O".
  • The book_seat() function first checks if the seat is available using is_seat_available(). If it is, the seat is marked as "X" (booked), and the function returns True. Otherwise, it returns False.
  • The seating list is a 5×5 matrix representing the seating chart, where "O" means available, and "X" means booked.
  • The while loop allows multiple seat bookings. It first displays the current seating arrangement, then asks the user to enter a row and column number (0-4).
  • The program validates the input to ensure it is within the correct range. If not, it displays an error and restarts the loop.
  • If the seat is available, it is marked as booked, and a success message is displayed. Otherwise, a message is shown stating the seat is already booked.
  • The user is then asked if they want to book another seat. If they enter “yes”, the loop continues; otherwise, it ends.
  • Finally, the updated seating arrangement is displayed, and the program thanks the user.
# Function to display the seating arrangement
def display_seats(seats):
    print("\nCurrent Seating Arrangement:")
    for row in seats:
        for seat in row:
            print(seat, end=" ")  # Print seats in a row
        print()  # Move to the next line

# Function to check if a seat is available
def is_seat_available(seats, row, col):
    if seats[row][col] == "O":
        return True
    return False

# Function to book a seat
def book_seat(seats, row, col):
    if is_seat_available(seats, row, col):
        seats[row][col] = "X"
        return True
    return False

# Initialize the seating chart (O = available, X = booked)
seating = [
    ["O", "X", "O", "O", "X"],
    ["O", "O", "X", "O", "O"],
    ["X", "O", "O", "X", "O"],
    ["O", "O", "X", "O", "X"],
    ["O", "X", "O", "X", "O"]
]

# Main program loop to allow multiple bookings
while True:
    display_seats(seating)

    # User inputs row and column for booking
    row = int(input("\nEnter row (0-4): "))
    col = int(input("Enter column (0-4): "))

    # Validate input range
    if row < 0 or row >= 5 or col < 0 or col >= 5:
        print("Invalid seat selection. Please enter values between 0 and 4.")
        continue  # Restart loop

    # Try to book the seat
    if book_seat(seating, row, col):
        print("Seat booked successfully!")
    else:
        print("Sorry, this seat is already booked.")

    # Ask user if they want to continue
    choice = input("Do you want to book another seat? (yes/no): ").strip().lower()
    if choice != "yes":
        break  # Exit loop

display_seats(seating)
print("\nThank you for using the seat booking system!")

The Dice Game

The Dice Game Python Funtion Problem
Imagine playing a dice game with friends where you roll two dice (1-6). Your score is the sum of both dice, but if you roll the same number, it’s a double, and you get a bonus message! Write a function roll_dice to generate two random dice rolls, calculate their sum, and print “You rolled a double!” if both numbers match.

Test Case:
Input: 
(Generated Dice Rolls: 3, 3)
Output:
You rolled a double!
Your total score: 6

Explanation:
The program simulates rolling two dice and calculates their total.

  • The random module is imported to generate random numbers.
  • The roll_dice() function rolls two dice:
    • random.randint(1, 6) generates a random number between 1 and 6 for each dice.
    • The sum of both dice values is stored in total.
  • If both dice have the same number (dice1 == dice2), it prints "You rolled a double!".
  • The function returns the total score of both dice.
  • Finally, the program calls roll_dice() and prints the total score.
import random  # Import the random module for dice rolling

def roll_dice():
    dice1 = random.randint(1, 6)  # Roll first dice
    dice2 = random.randint(1, 6)  # Roll second dice
    total = dice1 + dice2  # Calculate sum of dice
    
    if dice1 == dice2:  # Check for double
        print("You rolled a double!")  
    
    return total  # Return total score

print("Your total score:", roll_dice())  

For more engaging and informative articles on Python, check out our Python tutorial series at Syntax Scenarios.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top