Home > Software engineering >  How to fix the repeating of the last element of the list and not showing the other elements of list?
How to fix the repeating of the last element of the list and not showing the other elements of list?

Time:01-19

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`

CodePudding user response:

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

CodePudding user response:

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 orders, qty, prices in zip(cart, quantity, price):
        while len(orders) != 10:
            orders  = ' '
        else:
            print(f'{orders} \t\t\t {qty} \t\t {prices}')

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

Check_Inventory()

CodePudding user response:

change this:

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

to this:

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

Updated part..

Your answer. if there is any name in the cart which has length greater than 10. The code tends to infinity.

You can do like

cart = ['Fries','Nuggets','Chickenfried','Donuts']
quantity = [1, 2, 3, 4]
price = [123, 45, 65, 40]
amount = 0

def Check_Inventory():
    print(f'Orders \t\t\t\t Qty. \t\t Price(php) \n')
    
    max_length=max([len(i) for i in cart]) #Finding the max length in the cart
    for orders, qty, prices in zip(cart, quantity, price):
        while len(orders) != max_length:
            orders=orders ' '*(max_length-len(orders)) #Making all cart name same length by adding empty character
        else:
            print(f'{orders}  \t\t  {qty} \t\t\t {prices}')

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

Check_Inventory()
  • Related