Python 3.x 如何根据用户输入菜单计算购物车到字典列表的总和?

Python 3.x 如何根据用户输入菜单计算购物车到字典列表的总和?,python-3.x,dictionary,Python 3.x,Dictionary,我创建了一个简单的菜单,可以根据用户输入添加内容 dictionary = {"Service A": 100, "Service B": 200} cart = [] def main(): while(True): print("1. List of Services") print("2. Payment") print("3. Exit&qu

我创建了一个简单的菜单,可以根据用户输入添加内容

dictionary = {"Service A": 100, "Service B": 200}
cart = []

def main():
    while(True):
        print("1. List of Services")
        print("2. Payment")
        print("3. Exit")
        print("\nServices you have added:", cart)

        a = input("Please enter a choice: ")
        if a=="1":
            Q1()
        elif a=="2":
            Q2()            
        elif a=="3":
            break

def Q1():
    print('1. Service A  :            $100/year')
    print('2. Service B  :            $200/year\n')
    service = input("Enter the service 1-2 that you would like to add: ")
    
    if not service.isnumeric():
        print('Please enter valid choice number!')

    elif service.isnumeric():
        print(f'\nYou have selected choice number {service} which is: ')

        if service == '1':            
            print ('\n''1. Service A: $100/year.''\n')
            cart.append ("Service A")

        if service == '2':
            print ('\n''2. Service B: $200/year.''\n')
            print('You will be return to main menu.')
            cart.append ("Service B")

def Q2():
    print("\nServices you have added:", cart)
    #total = sum(cart)
    #print('\nYour subscription will be a total of :',total)     

main()
del(cart)
print("Goodbye and have a nice day!")
    
我需要def Q2()方面的帮助: 我希望我添加到购物车中的服务引用字典列表以获得总金额。 我不知道确切的密码是什么。请对我放松点,我是初学者

def Q2():
    print("\nServices you have added:", cart)
    #total = sum(cart)
    #print('\nYour subscription will be a total of :',total)       
你好,谢谢你的提问


我在total=sum(cart)代码行之后添加了我的注释:因为添加到名为cart的列表中的用户是字符串而不是数字。因此,我们可以使用for循环将购物车中的每个字符串元素用作字典的键值,以对应于它的值,并对所有相应的值求和,最后声明一个名为total的区域变量并存储该和。

您需要什么帮助?你还没有解释这应该做什么。你到底有什么问题?
def Q2():
    print("\nServices you have added:", cart)
    total = 0
    for i in cart:
        total = total + dictionary[i]
        
    #total = sum(cart) #This line of code will only merge the selected strings, not the sum of the numbers we need. Because the user added to the list named cart is a string instead of a number
    print('\nYour subscription will be a total of :',total)