In: Computer Science
You want to write a simple python program for a food delivery company that asks the office worker how many drivers they require to deliver their packages to different parts of town. When the user enters the number of drivers, the program will ask how many packages each driver will carry to its destination. It will then calculate the total number of packages and display the result on the screen as below.
Sample run: How many drivers do you need? 5
Packages for driver 1: 3
Packages for driver 2: 4
Packages for driver 3: 1
Packages for driver 4: 12
Packages for driver 5: 8
5 drivers delivered a total of 28 packages.
note: please do not use (break) or directories
Solution: We can resolve this problem by making use of python dictionaries. Have given the code below with output. Comments have been placed in the program to depict the functionality.
Hope that helps.
if __name__ == "__main__":
#Welcome Message
print("*** Welcome to the Company ***\n")
# Ask user for number of drivers
num_driver = int(input("How many drivers are required: "))
# Create an empty dictionary
driver_package = {}
# Create a variable to store the total packages
total_package = 0
# Add drivers and package information to the dictionary
for i in range(num_driver):
num_delivery = int(input(f"Packages for Driver {i+1} : "))
driver_package[i+1] = num_delivery
#Calculate the total packages
for i in driver_package.values():
total_package = total_package + i
print(f"\n{num_driver} drivers delivered a total of {total_package} packages.")
print("\n** Thank You **")
Output:
*** Welcome to the Company ***
How many drivers are required:
8
Packages for Driver 1 : 10
Packages for Driver 2 : 20
Packages for Driver 3 : 15
Packages for Driver 4 : 15
Packages for Driver 5 : 30
Packages for Driver 6 : 40
Packages for Driver 7 : 10
Packages for Driver 8 : 25
8 drivers delivered a total of 165 packages.
** Thank You **