JD2775
JD2775

Reputation: 3801

Appending multiple values to a list in Python while incrementing through another list

The goal of this is to enter an amount and date for each account on a regular basis. The accounts are static (but more could be appended). What I am trying to do is loop through each account and for each account enter the amount and date. I am doing something wrong, I think in the increment line, and possibly the append line

After that I'd like to print the results to the screen in a way that makes sense (I know what I have is not correct and won't display in a sensible way)

Any ideas? Thanks

account = ['401k', 'RothIRA', 'HSA']
amount = []
date = []

while True:
    print('Enter the amount for your ' + account[0] + ' account')
    act = input()
    amount.append(act)
    print('Enter the date for this total')
    dt = input()
    date.append(dt)
    account[] += 1
    if act == '':
        break


print(account, amount, date)

Upvotes: 0

Views: 112

Answers (2)

James Kang
James Kang

Reputation: 509

I think this is what you're trying to do:

i = 0

while i < len(account):
    print('Enter the amount for your ' + account[i] + ' account')
    act = input()
    amount.append(act)
    print('Enter the date for this total')
    dt = input()
    date.append(dt)
    i += 1

It's better to use for loop as follows.

for i in account:
    print ('Enter amount for your',i,'account')
    act = input()
    amount.append(act)
    print ('Enter date')
    dt = input()
    date.append(dt)

Also all your lists (account, amount, date) are linked by index. It's much cleaner to use dictionary as someone else posted.

Upvotes: 1

Alp
Alp

Reputation: 3105

After a slight change in your data structure:

account={ '401K': { 'amount' : 0, 'date': 0 },
          'ROthIRA': { 'amount':0, 'date': 0},
          'HSA': { 'amount': 0, 'date': 0} }

for eachKey in account.keys:
    account[eachKey]['amount'] = input()
    account[eachKey]['date'] = input()


print account

Upvotes: 1

Related Questions