“Programming isn’t about what you know; it’s about what you can figure out.” With that in mind, let’s solve some real-world challenges where Python operators become your problem-solving toolkit.
We’ve created engaging, scenario-based questions that make learning Python fun and relatable. These scenarios will sharpen your coding skills and show you how Python operators are used in everyday solutions. Time to apply your skills and see how operators in Python work along with variables and data types.
Note: You can see the answer code along with its explanation by clicking on the question (or the drop down icon).
Pocket Money Calculator
You receive a fixed amount of pocket money each week and want to know how much you’ll have after saving for a certain number of weeks.
Create a program in Python that takes the amount of pocket money per week and the number of weeks as input and calculates the total amount saved.
Test Case:
Input:
Weekly Money: 20
Weeks: 5
Expected Output:
Total savings after 5 weeks: 100
Explanation:
- The program begins by asking the user to enter the amount of pocket money they receive each week and the number of weeks they want to save.
- Next, it calculates the total savings by multiplying the weekly pocket money by the number of weeks.
# Taking input from the user weekly_money = float(input("Enter your weekly pocket money: ")) weeks = int(input("Enter the number of weeks: ")) # Calculate total savings total_savings = weekly_money * weeks # Display the result print(f"Total savings after {weeks} weeks: {total_savings}")
Candy Distribution
You have a certain number of candies and want to share them equally among your friends.
Write a program in Python that takes the total number of candies and the number of friends as input and calculates how many candies each friend will get and how many will be left over.
Test Case:
Input:
Total Candies: 25
Friends: 4
Expected Output:
Each friend gets 6 candies.
Leftover candies: 1
Explanation:
- The program starts by asking the user to enter the total number of candies and the number of friends they want to share them with.
- It calculates how many candies each friend will get by dividing the total number of candies by the number of friends using integer division
(//)
. This gives the whole number of candies each friend will receive. - It then calculates the leftover candies using the modulus operator
(%)
. This finds the remainder after dividing the total candies by the number of friends, showing how many candies are left after distribution. - This approach ensures that candies are distributed fairly and any remaining candies are dealt with individually.
# Taking input from the user total_candies = int(input("Enter the total number of candies: ")) friends = int(input("Enter the number of friends: ")) # Calculate candies per friend and leftover candies candies_per_friend = total_candies // friends leftover_candies = total_candies % friends # Display the results print(f"Each friend gets {candies_per_friend} candies.") print(f"Leftover candies: {leftover_candies}")
Fuel Efficiency Estimator
You want to calculate how far you can travel with a certain amount of fuel in your car.
Develop a Python snippet that takes the distance your car can travel per liter of fuel (fuel efficiency) and the amount of fuel you have as input, and calculates the total distance you can travel.
Test Case:
Input:
Fuel Efficiency: 15 (km per liter)
Fuel Amount: 10 (liters)
Expected Output:
Total Distance: 150 km
Explanation:
- The program starts by asking the user for the fuel efficiency of their car (how many kilometers the car can travel per liter of fuel) and the total amount of fuel available in their tank.
- It then calculates the total distance that can be traveled by multiplying the fuel efficiency by the amount of fuel.
# Taking input from the user fuel_efficiency = float(input("Enter your car's fuel efficiency (km per liter): ")) fuel_amount = float(input("Enter the amount of fuel in your tank (liters): ")) # Calculate total distance total_distance = fuel_efficiency * fuel_amount # Display the result print(f"Total distance you can travel: {total_distance} km")
Movie Marathon
You’re planning a movie marathon and want to know how many movies you can watch in a day.
Write a program in Python that takes the duration of a single movie and the total time you have for the marathon as input and calculates how many full movies you can watch and how much time will be left.
Test Case:
Input:
Movie Duration: 120 (minutes)
Total Time: 500 (minutes)
Expected Output:
You can watch 4 full movies.
Time left after the marathon: 20 minutes
Explanation:
- The program begins by asking for the duration of one movie and the total time available for the marathon.
- It then calculates how many full movies can be watched by dividing the total time by the duration of one movie using integer division
(//)
. This operation gives the number of complete movies that fit into the available time. - The leftover time after watching the full movies is calculated using the modulus operator
(%)
. This finds the remainder of time after distributing it among the movies.
# Taking input from the user movie_duration = int(input("Enter the duration of one movie (in minutes): ")) total_time = int(input("Enter the total time available (in minutes): ")) # Calculate number of movies and leftover time movies_watched = total_time // movie_duration leftover_time = total_time % movie_duration # Display the results print(f"You can watch {movies_watched} full movies.") print(f"Time left after the marathon: {leftover_time} minutes")
Trip Budget Calculation
You’re planning a trip and want to calculate your total budget, including accommodation, food, and entertainment.
Develop a Python code that takes the daily costs for accommodation, food, and entertainment, and the number of days you’ll be staying, and calculates the total trip cost.
Input:
Daily Accommodation Cost: 100
Daily Food Cost: 50
Daily Entertainment Cost: 30
Number Of Days: 7
Expected Output:
The total trip cost is: 1260
Explanation:
- The program starts by asking for the daily costs for accommodation, food, and entertainment, as well as the number of days for the trip.
- It calculates the total cost for each category by multiplying the daily cost by the number of days.
- The overall trip budget is then found by adding the total costs for accommodation, food, and entertainment. Addition combines these expenses into a single total amount.
- Finally, the program displays the total trip cost, helping you understand the total budget needed for your trip.
# Taking input from the user daily_accommodation_cost = float(input("Enter the daily accommodation cost: ")) daily_food_cost = float(input("Enter the daily food cost: ")) daily_entertainment_cost = float(input("Enter the daily entertainment cost: ")) number_of_days = int(input("Enter the number of days you'll be staying: ")) # Calculate total costs for each category total_accommodation_cost = daily_accommodation_cost * number_of_days total_food_cost = daily_food_cost * number_of_days total_entertainment_cost = daily_entertainment_cost * number_of_days # Calculate overall trip budget total_trip_cost = total_accommodation_cost + total_food_cost + total_entertainment_cost # Display the result print(f"The total trip cost is: {total_trip_cost}")
Baking Ingredients Measure
You’re baking cookies and the recipe you have is for a certain number of cookies. However, you want to bake more or fewer cookies.
Write a program in Python that takes the amount of flour needed for the original recipe and the desired number of cookies as input, and calculates the amount of flour needed for the new number of cookies.
Test Case:
Input:
Original Flour: 200 grams
Original Cookies: 20
Desired Cookies: 30
Expected Output:
You need 300 grams of flour for 30 cookies.
Explanation:
- The program begins by asking for the amount of flour needed for the original recipe, the number of cookies the original recipe makes, and the number of cookies you want to bake.
- It calculates the amount of flour needed for the desired number of cookies by dividing the desired cookies by the original cookies and then multiplying by the original amount of flour. This division helps find the proportion of flour needed, and multiplication scales it up or down for the new number of cookies.
- This helps you adjust your ingredients accordingly.
# Taking input from the user original_flour = float(input("Enter the amount of flour needed for the original recipe (grams): ")) original_cookies = int(input("Enter the original number of cookies: ")) desired_cookies = int(input("Enter the desired number of cookies: ")) # Calculate the new amount of flour needed flour_needed = (desired_cookies / original_cookies) * original_flour # Display the result print(f"You need {flour_needed} grams of flour for {desired_cookies} cookies.")
Event Budget Planning
You’re organizing an event and need to plan the budget for different expenses such as venue, catering, and decorations.
Use Python code to calculate the cost for each expense category, the number of guests, and any additional charges per guest (like gifts or favors), and calculate the total event budget.
Test Case:
Input:
Venue Cost: 5000
Catering Cost: 3000
Decoration Cost: 1500
Number Of Guests: 100
Additional Cost per Guest: 20
Expected Output:
The total event budget is: 9500
Explanation:
- The program starts by asking for the cost of the venue, catering, and decorations, the number of guests, and any additional cost per guest.
- It calculates the total fixed costs by adding the venue, catering, and decoration costs together. This gives you the base cost of the event.
- Then, it calculates the total cost for guests by multiplying the number of guests by the additional cost per guest. This accounts for extras like gifts or favors.
- Finally, it adds the total fixed costs to the total guest-related costs to get the overall event budget, helping you plan your expenses effectively.
# Taking input from the user venue_cost = float(input("Enter the cost for the venue: ")) catering_cost = float(input("Enter the total catering cost: ")) decoration_cost = float(input("Enter the decoration cost: ")) number_of_guests = int(input("Enter the number of guests: ")) additional_cost_per_guest = float(input("Enter the additional cost per guest (e.g., gifts, favors): ")) # Calculate total fixed costs total_fixed_cost = venue_cost + catering_cost + decoration_cost # Calculate total guest-related costs total_guest_cost = number_of_guests * additional_cost_per_guest # Calculate overall event budget total_event_budget = total_fixed_cost + total_guest_cost # Display the result print(f"The total event budget is: {total_event_budget}")
Stock Market Investment Return
You’ve invested in a stock, and its value has increased over time.
Write a program in Python that takes the initial investment amount, the percentage increase in value, and the number of years you’ve held the stock as input, and calculates the final value of the investment.
Test Case:
Input:
Initial Investment: 1000
Annual Increase Percentage: 5
Years Held: 10
Expected Output:
The final value of the investment after 10 years is: 1500
Explanation:
- The program starts by asking for the initial investment amount, the annual percentage increase, and the number of years the investment has been held.
- It calculates the total increase in investment value by multiplying the initial amount by the annual percentage increase (converted to a decimal) and then by the number of years. This gives the total growth over the years.
- It adds this total increase to the initial investment to find the final value of the investment.
- Then it displays the final value, showing how much the investment is worth after the specified number of years.
# Taking input from the user initial_investment = float(input("Enter the initial investment amount: ")) annual_increase_percentage = float(input("Enter the annual percentage increase: ")) years_held = int(input("Enter the number of years: ")) # Calculate the total increase and final value total_increase = initial_investment * (annual_increase_percentage / 100) * years_held final_value = initial_investment + total_increase # Display the result print(f"The final value of the investment after {years_held} years is: {final_value}")
Home Loan Monthly Payment
You’re considering taking out a home loan and want to know how much you’ll need to pay monthly.
Develop a Python snippet that takes the total loan amount, the annual interest rate, and the loan duration in years as input, and calculates the monthly payment.
Test Case:
Input:
Loan Amount: 200000
Annual Interest Rate: 5
Loan Duration Years: 15 (years)
Expected Output:
The monthly payment is: 1666.67
Explanation:
- The program begins by asking for the total loan amount, the annual interest rate, and the loan duration in years.
- It calculates the total interest by multiplying the loan amount by the annual interest rate (converted to a decimal) and then by the loan duration in years.
- The total amount to be paid back is found by adding the initial loan amount to the total interest.
- It then calculates the monthly payment by dividing the total amount payable by the total number of months in the loan duration.
- Finally, it displays how much you’ll need to pay each month.
# Taking input from the user loan_amount = float(input("Enter the total loan amount: ")) annual_interest_rate = float(input("Enter the annual interest rate (percentage): ")) loan_duration_years = int(input("Enter the loan duration (years): ")) # Calculate total interest and monthly payment total_interest = loan_amount * (annual_interest_rate / 100) * loan_duration_years total_amount_payable = loan_amount + total_interest monthly_payment = total_amount_payable / (loan_duration_years * 12) # Display the result print(f"The monthly payment is: {monthly_payment}")
Currency Conversion for Vacation
You’re planning a vacation to a foreign country and need to convert your currency.
Write a program in Python that takes the amount in your local currency, the conversion rate to the foreign currency, and any conversion fees as input, and calculates the final amount you’ll have in the foreign currency.
Test Case:
Input:
Local Currency Amount: 1000
Conversion Rate: 0.85
Conversion Fee: 10
Expected Output:
The final amount in foreign currency is: 840
Explanation:
- The program starts by asking for the amount of money you have in your local currency, the conversion rate to the foreign currency, and any conversion fees.
- It calculates the amount in the foreign currency by multiplying the local currency amount by the conversion rate and then subtracting the conversion fee.
- Lastly, it displays the final amount you’ll have in the foreign currency, showing how much you’ll get after the conversion and fees are applied.
# Taking input from the user local_currency_amount = float(input("Enter the amount in your local currency: ")) conversion_rate = float(input("Enter the conversion rate to the foreign currency: ")) conversion_fee = float(input("Enter the conversion fee: ")) # Calculate the final amount in foreign currency foreign_currency_amount = (local_currency_amount * conversion_rate) - conversion_fee # Display the result print(f"The final amount in foreign currency is: {foreign_currency_amount}")
Walk & Lose
you’ve set a goal to lose a certain amount of weight by walking over a specific period. You know that on average, walking 1 kilometer burns approximately 60 calories, and to lose 1 kilogram of body weight, you need to burn about 7700 calories. Given your target weight loss and the number of days you have to achieve it, calculate how many kilometers you need to walk each day to reach your goal.
Write a Python program that takes your target weight loss (in kilograms) and the number of days you plan to achieve this goal. The program should calculate and output the number of kilometers you need to walk each day to reach your target.
Test Case:
Input:
Target Weight Loss: 5
Days To Achieve: 30
Expected Output:
You need to walk 2.14 kilometers each day to reach your goal.
Explanation:
- The program executes by entering the user’s target weight loss (in kilograms) and the number of days the user has to achieve it.
- Following that, it multiplies the target weight loss by 7700 to find out the total calories needed to be burned.
- Since walking 1 kilometer burns 60 calories, it divides the total calories by 60 to calculate the total distance the user needs to walk.
- Finally, the program divides this total distance by the number of days to find out how many kilometers to walk each day and display the output.
# Taking input from the user target_weight_loss = float(input("Enter your target weight loss (in kg): ")) days_to_achieve = int(input("Enter the number of days to achieve this goal: ")) # Constants calories_per_kg = 7700 # Calories needed to lose 1 kg calories_per_km = 60 # Calories burned per kilometer # Calculate total calories to burn total_calories_to_burn = target_weight_loss * calories_per_kg # Calculate total kilometers to walk total_km_to_walk = total_calories_to_burn / calories_per_km # Calculate daily kilometers daily_km_to_walk = total_km_to_walk / days_to_achieve # Displaying the result print(f"You need to walk {daily_km_to_walk:.2f} kilometers each day to reach your goal.")
Track Your College Reaching Time
You’re getting ready for college and need to determine if you’ll reach your class on time. To figure this out, you need to calculate the time it will take to travel to your college based on the distance, your average speed, and the time remaining until your class starts.
You are tasked to create a program in Python that will require you to input the distance to your college in kilometers, your average speed in kilometers per hour, the current time in 24-hour format (hours and minutes), and the time remaining until your class begins in minutes. Using these details, it will have to compute how long the journey will take, when you’ll arrive at college, and how much time you’ll have left before your class starts.
Test Case:
Input:
Distance To College: 20 (km)
Average Speed: 40 (km/h)
Current Hours: 08 (hours)
Current Minutes:15 (minutes)
Time Remaining: 45 (minutes)
Expected Output:
You will arrive at college at 09:15.
Time left before class: 15.00 minutes.
Explanation:
- The program starts by entering the distance to college in kilometers, the average speed in kilometers per hour, the current time (hours and minutes), and the time remaining until the class starts (in minutes).
- It then converts the time remaining to hours by dividing by 60.
- Next, it calculates the time it will take to travel to college by dividing the distance by the average speed.
- Now it adds the travel time to the current time to find out the arrival at college.
- After that, the total arrival time is converted into hours and minutes to get the exact arrival time.
- It calculates the time left before class by subtracting the travel time (in minutes) from the time remaining.
- The program’s output will show the exact time of arrival at college and how much time before the class starts.
# Taking input from the user distance_to_college = float(input("Enter the distance to your college (in km): ")) # Distance in kilometers average_speed = float(input("Enter your average speed (in km/h): ")) # Speed in kilometers per hour current_hours = int(input("Enter the current hour (24-hour format): ")) # Current hour in 24-hour format current_minutes = int(input("Enter the current minutes: ")) # Current minutes time_remaining = float(input("Enter the time remaining until your class starts (in minutes): ")) # Time in minutes # Convert time remaining to hours time_remaining_in_hours = time_remaining / 60 # Calculate travel time in hours travel_time_in_hours = distance_to_college / average_speed # Calculate arrival time in hours and minutes arrival_time_in_hours = current_hours + travel_time_in_hours arrival_time_in_minutes = current_minutes + (travel_time_in_hours * 60) arrival_hours = int(arrival_time_in_hours) arrival_minutes = int(arrival_time_in_minutes % 60) # Calculate time left before class in minutes time_left_before_class = time_remaining - (travel_time_in_hours * 60) # Display the results print(f"You will arrive at college at {arrival_hours:02}:{arrival_minutes:02}.") print(f"Time left before class: {time_left_before_class:.2f} minutes.")
Calculating Uber Bonus Earnings
As an Uber driver, you earn money based on the distance you drive, and you also receive a daily bonus calculated as a percentage of your total earnings. Your bonus is determined by including an extra amount, such as 50 units, with your earnings, and then adjusting this total using a factor related to 10. This percentage is then used to calculate the bonus, which is added to your basic earnings to find your final earnings.
Write a Python program that takes the rate per kilometer and the distance driven as inputs and performs the necessary calculations to determine your final earnings after including the bonus.
Test Case:
Input:
Rate per Km: 5
Distance Driven: 120 (km)
Expected Output:
Final earnings: 438000.00
Explanation:
- The program begins by entering the rate per kilometer and the total distance driven (in kilometers).
- It multiplies the rate per kilometer by the distance driven to calculate the basic earnings.
- Next, it adds 50 to the basic earnings and then divides the result by 10 to get the adjusted bonus percentage.
- It multiplies the basic earnings by this bonus percentage to calculate the bonus amount.
- Finally, it adds the bonus to the basic earnings to get the final earnings and display the output.
# Taking input from the user rate_per_km = float(input("Enter your rate per kilometer: ")) distance_driven = float(input("Enter the total distance driven (in km): ")) # Calculate basic earnings basic_earnings = rate_per_km * distance_driven # Calculate bonus percentage bonus_percentage = (basic_earnings + 50) / 10 # Calculate bonus bonus = basic_earnings * bonus_percentage # Calculate final earnings final_earnings = basic_earnings + bonus # Displaying the results print(f"Final earnings: {final_earnings:.2f}")
Secret Code Cracker
You’re a software engineer working on a special project to protect important information. You’ve found a secret message, but it’s been scrambled by reversing the digits of a 3-digit number. Your job is to figure out the original message by reversing the digits back to how they were.
To do this, write a Python program that will decode the 3-digit message for you.
Test Case:
Input:
Encoded Number: 1234
Expected Output:
The decoded number is: 4321
Explanation:
- The program asks you to enter the 3-digit encoded number.
- It extracts the last digit of the number using the modulus operator (
% 10
). - Then it derives the middle digit by first dividing the number by 10 to remove the last digit, then taking the modulus of the result with 10.
- Now obtain the first digit by dividing the number by 100.
- Afterward, it reconstructs the decoded number by placing the last digit in the hundreds place, the middle digit in the tens place, and the first digit in the units place.
- Finally, the program displays the decoded number as the result.
# Taking input from the user encoded_number = int(input("Enter the encoded 3-digit number: ")) # Extract each digit using modulus and integer division digit1 = encoded_number % 10 digit2 = (encoded_number // 10) % 10 digit3 = (encoded_number // 100) % 10 # Reconstruct the reversed number decoded_number = digit1 * 100 + digit2 * 10 + digit3 # Displaying the results print(f"The decoded number is: {decoded_number}")
Time Converter for Freelancers
You’re a freelancer working with clients from different time zones, and you’ve been asked to join an important meeting. However, the meeting time is given in UTC, and you’re unsure what time that would be in your local time zone.
To avoid any confusion, you decide to develop a Python program that will help you convert the UTC time to your local time based on the time difference
Test Case:
Input:
UTC hour: 15
Time difference: -5 (PST to UTC)
Expected Output:
The local time is 10:00.
Explanation:
- The program starts by entering the hour of the meeting in UTC and the time difference between UTC and the local time zone (in hours).
- Then it adds the time difference to the UTC hour to get the local hour. If the time difference is negative, it will subtract hours instead.
- It uses the modulus operator (
% 24
) to make sure the local hour is within a 24-hour format. - Finally, it displays the local time in the format
HH:00
to show when you should join the meeting in your local time.
# Taking input from the user utc_hour = int(input("Enter the hour in UTC (0-23): ")) time_difference = int(input("Enter the time difference from UTC (in hours): ")) # Calculate local time local_hour = (utc_hour + time_difference) % 24 # Displaying the results print(f"The local time is {local_hour:02d}:00")
Dual Boot Storage Strategy
You’re configuring a dual-boot setup on your laptop with a total storage capacity. The challenge is to allocate space not only for Windows and Linux (for instance Ubuntu) installations but also for their respective software, personal files, and system backups. Additionally, you want to ensure that each OS gets proportional space based on its usage needs.
To accomplish this, you’ll need to create a Python-based program to calculate the space allocation by considering the percentage of storage each OS will use and the space required for future backups. Finally, you need to ensure there is adequate free space left after all allocations.
Test Case:
Input:
Total Storage: 1000 (GB)
Windows Percentage: 45 (%)
Ubuntu Percentage: 35 (%)
Windows Backup: 50 (GB)
Ubuntu Backup: 40 (GB)
Expected Output:
Windows allocation: 450.00 GB
Ubuntu allocation: 350.00 GB
Total storage used (including backups): 890.00 GB
Free space remaining: 110.00 GB
Explanation:
- The program begins by providing the total storage capacity of the laptop (in gigabytes).
- Then it takes the percentage of total storage you want to allocate for Windows. Multiply this percentage by the total storage to calculate the space allocated for Windows.
- Similarly, it takes the percentage for Ubuntu and multiplies it by the total storage to find the space allocated for Ubuntu.
- For each OS, the program subtracts the allocated space from the total storage to see how much space is left.
- After that, it takes the specific amount of storage reserved for system backups for both Windows and Ubuntu. and add these backup spaces to their respective allocations.
- Next, it calculates the total used space by adding the space allocated for Windows, Ubuntu, and both backups.
- Finally, the program subtracts the total used space from the total storage capacity to determine the remaining free space on the laptop.
# Taking input from the user total_storage = float(input("Enter the total storage capacity of your laptop (in GB): ")) windows_percentage = float(input("Enter the percentage of storage allocated for Windows: ")) ubuntu_percentage = float(input("Enter the percentage of storage allocated for Ubuntu: ")) windows_backup = float(input("Enter the space reserved for Windows backup (in GB): ")) ubuntu_backup = float(input("Enter the space reserved for Ubuntu backup (in GB): ")) # Calculate storage allocation based on percentages windows_allocation = (windows_percentage / 100) * total_storage ubuntu_allocation = (ubuntu_percentage / 100) * total_storage # Calculate total used space including backups total_used_space = windows_allocation + ubuntu_allocation + windows_backup + ubuntu_backup # Calculate free space remaining free_space_remaining = total_storage - total_used_space # Display the results print(f"Windows allocation: {windows_allocation:.2f} GB.") print(f"Ubuntu allocation: {ubuntu_allocation:.2f} GB.") print(f"Total storage used (including backups): {total_used_space:.2f} GB.") print(f"Free space remaining: {free_space_remaining:.2f} GB.")
Social Media Reach Estimation
You’re managing a social media account and want to estimate the reach of your next post. Based on past data, you know that each follower will likely share your post with 10% of their followers. Given the number of followers you have and the average number of followers each of your followers have, calculate the estimated reach of your post after it’s shared once using Python.
Test Case:
Input:
Followers: 500
Followers per Person: 200
Expected Output:
Total Estimated Reach = 10,000
Explanation:
- The program asks for the number of followers and the average number of followers per person.
- Following that it multiplies the number of followers by the average number of followers per person.
- Then it multiplies this result by 0.10 to find 10%.
- Finally, it adds the original number of followers to the result from the previous step.
- Then it displays the total estimated reach.
followers = int(input("Enter the number of followers you have: ")) average_followers_per_person = int(input("Enter the average number of followers each of your followers has: ")) # Calculate the total followers your followers have total_followers_of_followers = followers * average_followers_per_person # Estimate the reach by calculating 10% of the total followers of your followers estimated_reach_from_shares = 0.10 * total_followers_of_followers # Add the original number of followers to the estimated reach total_estimated_reach = followers + estimated_reach_from_shares # Display the estimated reach print(f"Estimated Reach = {total_estimated_reach:.0f}")
Game XP Boost Tracker
You’re playing a game where each level needs more experience points (XP) to level up. The XP needed increases by a specific multiplier that changes with each level. Given the XP required for your current level and the multiplier for the next level, calculate how much more XP you’ll need. Also, include a bonus XP boost of 200 points that you get after every level-up.
You need to create a Python program to do these calculations.
Test Case:
Input:
Current Level XP = 1000
Multiplier = 1.5
Expected Output:
Additional XP Needed = 300
Explanation:
- The program starts by entering the XP required for the current level and the multiplier for the next level.
- Then it calculates the XP needed for the next level by multiplying the current XP by the multiplier.
- It adds the 200 XP bonus to the current XP to determine the total XP available after leveling up.
- Now it subtracts the total XP after leveling up from the next level’s XP to find out how much more XP you need.
- Lastly, the program displays the additional XP required.
# Taking input from the user current_xp = float(input("Enter the XP required for the current level: ")) multiplier = float(input("Enter the multiplier for the next level: ")) # Calculate the XP needed for the next level next_level_xp = current_xp * multiplier # Calculate the total XP available after leveling up (including the 200 XP bonus) total_xp_after_level_up = current_xp + 200 # Calculate the additional XP needed to reach the next level additional_xp_needed = next_level_xp - total_xp_after_level_up # Display the additional XP required print(f"Additional XP Needed = {additional_xp_needed:.0f}")
Budget Allocation for a Startup
You’ve just launched a startup and received a certain amount of funding from an incubation center. You need to divide this budget among three departments: marketing, development, and operations, based on a given ratio.
Write a Python program that calculates the budget allocation for each department based on the ratio provided.
Test Case:
Input:
Total budget: 10000
Marketing Ratio: 3
Development Ratio: 5
Operations Ratio: 2
Expected Output:
Marketing budget: 30000.00
Development budget: 50000.00
Operations budget: 20000.00
Explanation:
- The program starts by entering the total budget amount available.
- Next, it asks for the ratio the user wants to allocate to marketing, development, and operations.
- The total ratio is calculated by adding the ratios for marketing, development, and operations of the program.
- To find the budget for each department, the program divides the ratio for each area by the total ratio and multiplies it by the total budget.
- This calculates the amount of money allocated to marketing, development, and operations.
- Finally, the program displays the budget allocated for each department.
# Taking input from the user total_budget = float(input("Enter the total budget: ")) marketing_ratio = float(input("Enter the ratio for marketing: ")) development_ratio = float(input("Enter the ratio for development: ")) operations_ratio = float(input("Enter the ratio for operations: ")) # Calculate total ratio parts total_ratio = marketing_ratio + development_ratio + operations_ratio # Allocate budget marketing_budget = (marketing_ratio / total_ratio) * total_budget development_budget = (development_ratio / total_ratio) * total_budget operations_budget = (operations_ratio / total_ratio) * total_budget # Displaying the results print(f"Marketing budget: {marketing_budget:.2f}") print(f"Development budget: {development_budget:.2f}") print(f"Operations budget: {operations_budget:.2f}")
Streaming Subscription Savings
You have two streaming subscriptions and want to find out how much you spend each month and how much you could save if you switch to paying annually. Each subscription has a monthly cost and offers a discounted annual rate.
Write a Python program to calculate the total monthly cost for both subscriptions, the total annual cost if you continue paying monthly, and compare this with the annual rates you would pay if you switch to annual payments. Finally, show how much you could save by choosing the annual payment option.
Test Case:
Input:
Service 1 = $10/month
Service 2 = $12/month
Annual Discount for Service 1 = $100
Annual Discount for Service 2 = $120
Expected Output:
Monthly Total: $22.00
Total Annual Cost without Discount: $264.00
Total Annual Discounted Cost: $220.00
Total Savings: $44.00
Explanation:
- The program starts by entering the monthly cost of Service 1 and Service 2, as well as the annual cost of each service with a discount.
- It adds the monthly costs of both services to find the total monthly cost.
- The program then calculates the total annual cost by multiplying the total monthly cost by 12.
- Next, it adds the discounted annual costs of both services to find the total annual discounted cost.
- The program calculates the savings by subtracting the total annual discounted cost from the total annual cost without discounts.
- Finally, it displays the total monthly cost, the total annual cost without discounts, the total annual discounted cost, and the total savings.
# Taking input from the user service_1_monthly = float(input("Enter the monthly cost of Service 1: $")) service_2_monthly = float(input("Enter the monthly cost of Service 2: $")) annual_discount_service_1 = float(input("Enter the annual cost of Service 1 with discount: $")) annual_discount_service_2 = float(input("Enter the annual cost of Service 2 with discount: $")) # Calculate the total monthly cost total_monthly_cost = service_1_monthly + service_2_monthly # Calculate the total annual cost without discounts total_annual_cost = total_monthly_cost * 12 # Calculate the total annual cost with discounts total_annual_discounted_cost = annual_discount_service_1 + annual_discount_service_2 # Calculate the savings savings = total_annual_cost - total_annual_discounted_cost # Display the results print(f"Monthly Total: ${total_monthly_cost:.2f}") print(f"Total Annual Cost without Discount: ${total_annual_cost:.2f}") print(f"Total Annual Discounted Cost: ${total_annual_discounted_cost:.2f}") print(f"Total Savings: ${savings:.2f}")
As you’ve worked through these real-world scenarios, you’ve seen how Python operators can solve practical problems. Every challenge you’ve tackled has sharpened your coding skills and deepened your understanding of how these operators function in everyday situations. Remember, programming is as much about creativity as it is about logic.