1

I have a txt file with the following data:

buy apples 20
buy oranges 15
sold bananas 5
sold bananas 5
sold pears 8

I wrote a program to print out the total number of bananas sold, however I keep getting the error

cannot unpack non-iterable builtin_function_or_method object

How do I fix this issue?

with open("update.txt") as openfile:
        for line in openfile:
            action, fruit, quantity = line.split
            if action == 'sold':
                    print(f"{fruit} {quantity}")

The output should be:

bananas 10
pear    8
2
  • 2
    you need line.split(" ") Commented Mar 8, 2021 at 11:59
  • hi it works, however it prints bananas 5, bananas 5, pears 8... instead of bananas 10, pears 8 Commented Mar 8, 2021 at 12:38

1 Answer 1

2

For one, your need to call split as a function, i.e. with parentheses:

action, fruit, quantity = line.split()

Additionally, if you want to sum up the values for each fruit, you obviously cannot just print them as you read them. One way is e.g. to store each sold fruit in a dict and sum up the quantities. Then print them at the very end:

# initialize empty dictionary
sold_fruit = {}

with open("update.txt") as openfile:
    for line in openfile:
        action, fruit, quantity = line.split()
        if action == 'sold':
            # set value for key '<fruit>' to the sum of the old value (or zero if there is no value yet) plus the current quantity
            sold_fruit[fruit] = sold_fruit.get(fruit,0) + int(quantity)

for frt, qty in sold_fruit.items():
    print(f"{frt} {qty}")

Output:

bananas 10
pears 8
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.