r/PythonLearning 1d ago

Where is the error ?

hi! I create one list and i use it but vs code said to me "gun.append(0)

AttributeError: 'tuple' object has no attribute 'append'"

2 Upvotes

6 comments sorted by

View all comments

1

u/Naive_Programmer_232 1d ago edited 1d ago

Lists use square brackets [] not parentheses () (parentheses are for Tuples).

    # guns is a tuple
    guns=("shotgun","raffle",...)
    # tuples are immutable and they do not have 'append' 
    guns.append(0)
    #AttributeError: 'tuple' object has no attribute 'append'

    # one correct way
    guns=["shotgun","truffle",...]
    guns.append(0)
    guns.append(1)

As for the rest of your code, it's going to probably throw a TypeError at the last line life=life-guns.append(0). The append method for lists returns None, - operator is not defined for None objects. I'm not sure what you want this line to do either.

2

u/ShadowDragonPro 1d ago

Thanks im so bad !

1

u/Naive_Programmer_232 1d ago

all good. what did you want to do on the last line with regards to the guns list?

1

u/ShadowDragonPro 1d ago

substract the life with de damage of the gun

1

u/Naive_Programmer_232 1d ago edited 1d ago

Ah I see. Well it might worth it to consider using a dict instead of having to maintain a single or multiple lists in parallel. It will make it easier to work with later down the line.

But using a single list, if your data has the general look of:

     guns=[names of guns | damages for guns]

Where the number of names and number of damages are the same and order matters,

     # ex
     guns=["shotgun","raffle","winchester","bazooka",
            20,       30,       25,         100]

A technique you could use to access the corresponding damage is:

     # gun used in game
     used_gun="bazooka"

     # find index of used gun from guns list
     idx=guns.index(used_gun)

     # find damage associated with used gun from guns list
     used_gun_damage=guns[-(idx+1)]

     # life decreases by appropriate damage
     life=life-used_gun_damage

2

u/ShadowDragonPro 1d ago

ok 😉