pythonloopsnestedinventoryreceipt

How to fix the repeating of the last element of the list and not showing the other elements of list?


cart = ['Fries','Nuggets','Chicken']
quantity = [1, 2, 3]
price = [123, 45, 65]
amount = 0

def Check_Inventory():
    print(f'Orders \t\t\t\t Qty. \t\t Price (php) \n')

    for count, mycart in enumerate(cart):
        while len(mycart) != 10:
            mycart += ' '

        else:
            carts = mycart

    for qty, prices in zip(quantity, price):
        print(f'{carts} \t\t\t {qty} \t\t {prices}')

    print(f'\n Total: \t\t\t\t\t {amount} \n')

Check_Inventory()

EXPECTED:

Orders                           Qty.            Price(php)

Fries                            1               123
Nuggets                          2               45
Chicken                          3               65

 Total:                                          0

GET INSTEAD:

Orders                           Qty.            Price(php)

Chicken                          1               123
Chicken                          2               45
Chicken                          3               65


Total:                                          0

Solution

  • The issue is that every time you loop through the cart, you are redefining the carts variable, so at the end, it only keeps what it was last defined.

    Yash Metha's answer is basically there, but assuming you also want aligned spacing, you just need to modify the string formatting a little bit:

    for crt,qty, prices in zip(cart,quantity, price):
            print(f'{crt:<10} \t\t\t {qty} \t\t {prices}')