Search code examples
pythonlistposition

How do I print the position of each item in the list?


I would like for the positions I selected to be printed out. I made this (with the help from here) to help me. This code is for me to easily work out level rewards. People tell me what level they're at and I enter those levels one by one, I'll then add points to their accounts using the command (>add-money...). When writing out the reward I'm giving I want to be able to easily write what levels the rewards are from (i.e. what position in the list)

How can I make it so that I can print each position in the list I used?

My list:

rewards = [0, 150, 225, 330, 500, 1000, 1500, 2250, 3400, 5000, 10000, 13000, 17000, 22000, 29000, 60000]
#          0   1    2    3    4     5    6      7     8     9     10    11      12      13    14     15

def rewardz():
    # Running totals.
    lists = []
    total = 0
    user=input('User -> ')

    while True:
        # Get reward level from the user.  If not a valid reward level, stop.
        level = input('-> ')
        try:
            level_num = int(level)
        except ValueError:
            break
        if level_num not in range(len(rewards)):
            break

        # Add the reward to the lists and the total.
        reward = rewards[level_num]
        lists.append(reward)
        total += reward

    # Final output.
    print(lists)
    print(total, total*1000)
    print()
    print(" + ".join(str(i) for i in lists))
    print('>add-money bank',user, total*1000)
    print("\n-----########------\n\n")
    rewardz()
rewardz()

What (or similar to what) I want the result to be:

[2, 4, 7, 1, 4, etc]

Solution

  • Since you are asking the user to input the level you already have the level saved in level_num. If you want to return it you could do lists.append((reward, level_num)) or for a possibly cleaner solution use a dictionary.

    lists = {"rewards": [],
             "level": []}
    

    And then to append to it you can do:

    lists["rewards"].append(reward)
    lists["index"].append(level_num)
    

    Now in lists["index"] you have the list you want as an output and in lists["rewards"] you get your values.

    Alternatively you can open a new list and append to that as well:

    levels = []
    levels.append(level_num) # In your while loop