In Python I have a list of entries. I need to get the sum of expenses, the sum of income, and the profit. I’ve been able to get the expenses and income. Looking to break out the profit. I know I’m missing something simple but can’t figure it out.
JavaScript
x
29
29
1
entries = entries = [
2
{'date': '2021-01-01', 'transaction': 'Expense', 'amount': '50', 'note': 'Lemons'},
3
{'date': '2021-01-02', 'transaction': 'Income', 'amount': '100', 'note': 'Sales'}
4
]
5
6
#Print Income
7
for entry in entries:
8
if entry['transaction'].lower() == 'income':
9
income = 0
10
income += int(entry['amount'])
11
print(f"The total income is ${income}")
12
13
# Print Expense
14
for entry in entries:
15
if entry['transaction'].lower() == 'expense':
16
expense = 0
17
expense += int(entry['amount'])
18
print(f"The total expenses are ${expense}")
19
20
# Print Profit
21
for entry in entries:
22
profit = 0
23
if entry['transaction'].lower() == 'expense':
24
profit -= int(entry['amount'])
25
elif entry['transaction'].lower() == 'income':
26
profit += int(entry['amount'])
27
28
print(profit)
29
Advertisement
Answer
Looks like you just want to calculate the profit/expenses/income for the entire list, so you shouldn’t set “profit = 0” after every iteration, instead just set it in the beginning.
JavaScript
1
29
29
1
entries = entries = [
2
{'date': '2021-01-01', 'transaction': 'Expense', 'amount': '50', 'note': 'Lemons'},
3
{'date': '2021-01-02', 'transaction': 'Income', 'amount': '100', 'note': 'Sales'}
4
]
5
6
#Print Income
7
income = 0
8
for entry in entries:
9
if entry['transaction'].lower() == 'income':
10
income += int(entry['amount'])
11
print(f"The total income is ${income}")
12
13
# Print Expense
14
expense = 0
15
for entry in entries:
16
if entry['transaction'].lower() == 'expense':
17
expense += int(entry['amount'])
18
print(f"The total expenses are ${expense}")
19
20
# Print Profit
21
profit = 0
22
for entry in entries:
23
if entry['transaction'].lower() == 'expense':
24
profit -= int(entry['amount'])
25
elif entry['transaction'].lower() == 'income':
26
profit += int(entry['amount'])
27
28
print(profit)
29