fendi
fendi

Reputation: 25

How do I calculate the total sum of my cart to my dictionary list based on user input menu?

I have created a simple menu to add things based on user input.

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

I need help in def Q2(): I want the services that I have added to my cart referencing to the dictionary list to get the total sum. I'm not sure what is the exact codes. Please go easy on me, I'm a beginner.

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

Upvotes: 0

Views: 166

Answers (1)

Yan Ming
Yan Ming

Reputation: 58

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)

Hello, thank you for your question.

I added my note after the line of total = sum(cart) code: Because the user added to the list named cart is a string instead of a number. So we can use the for loop to use each string element in the cart as the key value of the dictionary to correspond to its value, and sum all the corresponding values, and finally declare a regional variable named total and store the sum.

Upvotes: 1

Related Questions