【问题标题】:How can I find the sum of a users input?如何找到用户输入的总和?
【发布时间】:2021-11-20 03:24:21
【问题描述】:
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))

上面是我到目前为止的代码。它打印:

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

我的目标是让代码将两项服务相加并得出总价格。我的最终目标应该是这样的:

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

请注意代码如何添加两个价格并生成“总计”。有什么办法可以做到这一点吗?我是计算机科学专业的初学者,所以我们对 Python 并不太了解。

所有代码都在 Python 中

【问题讨论】:

    标签: python conditional-statements


    【解决方案1】:
    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)
    
    

    这就是您正在尝试做的事情,我已尝试尽可能添加文档。我知道这不是最好的方法,但据我所知,我已经尝试过了。但如果你还是不明白,对此发表评论,我会尽力回复你。

    【讨论】:

      【解决方案2】:

      我建议你这样做:

      使用字典存储价格
      获取尽可能多的服务,而不仅仅是两项服务

      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}")
      

      这种方式的优点是,客户可以根据需要获得任意数量的服务。
      客户端应连续插入服务,并用空格分隔;例如:
      考试洗澡疫苗

      【讨论】:

      • 这似乎要写很多行。您可以将价格存储在字典中。
      • 是的,这是在字典中存储价格的好方法。
      • 客户端应该插入服务,如果不插入怎么办。
      • @PCM 总价为0
      • 这只会打印 - Exam 或 None。疫苗接种和其他事情呢......?
      【解决方案3】:

      不要只使用:input('What you want to ask'),而是使用int(input('What you want to ask'))

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

      然后你可以简单地运行:

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

      【讨论】:

        【解决方案4】:

        使用字典 -

        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)
        

        【讨论】:

        • 谢谢大家的建议。我知道字典,但我不知道如何在这种情况下正确使用它们。
        • 谢谢你,我明白你是怎么做到的,它让一切变得简单。不过字典应该是我的第一本!
        【解决方案5】:

        您可能想尝试dict 以使用循环简化您的if elifs 和prints。 但是,您可以将代码用于学习目的:

        
        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
        ...
        
        

        if elifstatements 的第一个和第二个块中。 毕竟你的ifs 只打印总数: print('Total: ', sum)

        【讨论】:

          猜你喜欢
          • 2017-03-17
          • 2015-06-05
          • 1970-01-01
          • 1970-01-01
          • 2022-01-09
          • 1970-01-01
          • 2021-09-05
          • 2019-09-04
          • 2022-11-21
          相关资源
          最近更新 更多