How can I find the sum of a users input?

Viewed 117
print("Fazli's Vet Services\n")
print("Exam: 50")
print("Vaccinations: 25")
print("Trim Nails: 5")
print("Bath: 20\n")

exam = "exam"
vaccinations = "vaccinations"
trim_nails = "trim nails"
bath = "bath"
none = "none"

exam_price = 50
vaccination_price = 25
trim_nails_price = 5
bath_price = 20
none_price = 0

first_service = input("Select first service:")
second_service = input("Select second service:")

print("\nFazli's Vet Invoice")

if first_service == exam:
    print("Service 1 - Exam: " + str(exam_price))
elif first_service == vaccinations:
    print("Service 1 - Vaccinations: " + str(vaccination_price))
elif first_service == trim_nails:
    print("Service 1 - Trim Nails: " + str(trim_nails_price))
elif first_service == bath:
    print("Service 1 - Bath: " + str(bath_price))
elif first_service == none:
    print("Service 1 - None " + str(none_price))
else:
    print("Service 1 - None " + str(none_price))


if second_service == exam:
    print("Service 2 - Exam: " + str(exam_price))
elif second_service == vaccinations:
    print("Service 2 - Vaccinations: " + str(vaccination_price))
elif second_service == trim_nails:
    print("Service 2 - Trim Nails: " + str(trim_nails_price))
elif second_service == bath:
    print("Service 2 - Bath: " + str(bath_price))
elif second_service == none:
    print("Service 2 - None " + str(none_price))
else:
    print("Service 2 - None " + str(none_price))

Above is a code I have so far. It prints:

Fazli's Vet Services

Exam: 50
Vaccinations: 25
Trim Nails: 5
Bath: 20

Select first service: exam
Select second service: bath

Fazli's Vet Invoice
Service 1 - Exam: 50
Service 2 - Bath: 20

My goal is for the code to add up the two services and make a total price. My end goal should look like this:

Chanucey's Vet Services

Exam: 45
Vaccinations: 32
Trim Nails: 8
Bath: 15

Select first service: Exam
Select second service: none

Chauncey's Vet Invoice
Service 1 - Exam: 45
Service 2 - None: 0
Total: 45

Notice how the code added both prices and made a "Total." Is there any way I can do this? I'm a beginner computer science major, so we aren't too far into Python.

ALL CODE IS IN PYTHON

5 Answers

Instead of using just: input('What you want to ask'), use int(input('What you want to ask'))

first_service = int(input("Select first service:"))
second_service = int(input("Select second service:"))

Then you can simply run:

total = first_service + second_service
print("Total Cost: " + total)

I suggest you to do something like this:

Use Dictionary to store prices
Get, as many as, Services you want, not just two services

service_prices = {'exam':50,'vaccinations':25,'trim nails':5,'bath':20,'none':0}

serivces = [input().split()]
total_price = 0
for index, service in enumerate(services):
    if service in service_prices:
        print(f"Service {index} - {service}: {service_prices[service]}" )
        total_price += exam_price
    else:
        print(f"Service {index} - None: {service_prices[none]}"
    
print(f"Total: {total_price}")

The advantage of this way is, clients can have services, as many as, they want.
Client should insert services, continuously and separate them with spaces; for example:
exam bath vaccinations

Use dictionary -

print("Fazli's Vet Services\n")
print("Exam: 50")
print("Vaccinations: 25")
print("Trim Nails: 5")
print("Bath: 20\n")

dictionary = {'exam':50,'vaccinations':25,'trim nails':5,'bath':20,'none':0}

first_service = input("Select first service:").lower()
second_service = input("Select second service:").lower()

print("\nFazli's Vet Invoice")

if first_service in dictionary:
    price1 = int(dictionary[first_service])
    print(f'Service 1 - {first_service.capitalize()} : {price1}')
else:
    price1 = 0
    print(f'Service 1 - None : 0')

if second_service in dictionary:
    price2 = int(dictionary[second_service])
    print(f'Service 1 - {second_service.capitalize()} : {price2}')

else:
    price2 = 0
    print(f'Service 1 - None : 0')

print('Total : ',price1+price2)

You might want to try out dict to simplify your if elifs and prints using loops. However, with your code for learning purposes you can try this:


sum = 0
if second_service == exam:
    print("Service 2 - Exam: " + str(exam_price))
    sum += exam_price
elif second_service == vaccinations:
    print("Service 2 - Vaccinations: " + str(vaccination_price))
    sum += vacination_price
...

in your first and second block of if elifstatements. After all your ifs just print the total: print('Total: ', sum)

print("Fazli's Vet Services\n")
print("1. Exam: $50")  # I've changed the price to include a dollar sign ($), so people don't get confused what the "correlating number" is
print("2. Vaccinations: $25")
print("3. Trim Nails: $5")
print("4. Bath: $20")
print("5. Nothing: $0\n")
print("To select a service, please input the correlating number.\n\nFor Example:\nEnter '1' (without the quotation marks) for an Exam.\n")


services = {"Exam": 50,
            "Vaccinations": 25,
            "Nail trimmings": 5,
            "Bath": 20,
            "Nothing": 0}  # The dictionary simplifies it so the 'key'(s) (words like "Exam") have 'value'(s) (things like the number "50") related to them, so no need for multiple variables :)


first_service = input("Select first service: ")
second_service = input("Select second service: ")


while True:
    try:  # This is a 'try' statement. Anything inside it, Python will "try" to do, but if it can't, it'll throw an "Exception" (kind of like an error), which can tell us what went wrong
        first_service = int(first_service)
        second_service = int(second_service)
        if ((5 < first_service) or (first_service < 1)) or (5 < second_service) or (second_service < 5):  # Checking if the numbers entered was between 1 and 5
            raise ValueError("Number not between 1 and 5 (inclusive)")  # If they were not between 1 and 4, throw, or "raise" a "ValueError" Exception
    except ValueError:  # If something goes wrong in the "try" block that raises a "ValueError", which means that the value entered isn't compatible with what we're trying to do with it, in this case, turn a string into an integer, so if the value isn't a string or any other value compatible with the "int()" function, it'll throw a ValueError
        print("Please enter a valid number between 1 and 5 (inclusive)")
        first_service = input("Select first service: ")
        second_service = input("Select second service: ")
        continue  # Continue with the "while" loop, asking again
    else:
        break  # The inputs was successfully turned into integers, so break out of the while loop (it will keep asking for input until correct (integers) input is entered)


# Setting the services to their respective correlating names based on the numbers the user gave us by getting the 'key'(s) from the dictionary and finding the service using indexes from a list of the names of the services

first_service = list(services.keys())[first_service - 1]  # The '-1' is because list indexes start from 0, while our numbers start from 1, so just to sync them up
second_service = list(services.keys())[second_service - 1]  # 'list()' turns whatever is inside the brackets (the argument) into a list, the 'services.keys()' gets all the 'key'(s) from the dictionary called 'services', and the '[]' is for accessing an item inside the list we just made

total = services[first_service] + services[second_service]  # Adding the two prices for the services by looking them up int he dictionary

# Printing the invoice

print("\nFazli's Vet Invoice")
print(f"Service 1 - {first_service}: ${services[first_service]}")  # These are 'f-strings'. They can do something called 'string interpolation', which is a form of 'string formatting' available in Python 3, not Python 2
print(f"Service 2 - {second_service}: ${services[second_service]}")  # Basically, anything inside the '{}' is replacing that part of the string.
print(f"Total: ${total}")  # So here, the '{total}' is referencing the 'total' variable on line 39, and adding that into the string where the '{}' is (so it will print out: "Total: $75" if the total is $75)

This is what you are trying to do, and I've tried to add documentation wherever I can. I understand that this is by far not the best way to do this, but I've tried as far as I know. But if you still do not understand something, please comment on this and I will try my best to respond to you.

Related