简体   繁体   中英

“Append” in a while loop not working, Python

I want to add the last three items of the list "M.Carte" (length 40) in the list "self.CarteInMano", using a while loop:

class Mano:
    def __init__(self,Giocatore,Dimensioni=3):
        self.Giocatore=Giocatore
        self.CarteInMano=[]
        self.Dimensioni=Dimensioni

    def Pesca(self):
        a=0
        while a==self.Dimensioni:
            self.CarteInMano.append(M.Carte.pop())
            a=a+1

But, after:

M1=Mano(1)
M1.Pesca()

I get:

len(M.Carte)
40
len(M1.CarteInMano)
0

Why "Pesca" doesn't do what it has to do?

Your issue is here:

while a==self.Dimensioni:
    self.CarteInMano.append(M.Carte.pop())
    a=a+1

this will only run when a == 3 you should try this instead:

while a<=self.Dimensioni:
    self.CarteInMano.append(M.Carte.pop())
    a=a+1

The reason is that in the first code a will only run when it is EQUAL to dimensioni, and since it start at 0 and not 3 it will never be equal, and skips the code. If you use <= instead, you now run the code while a is less than or equal to 3

NOTE

If you want to get 3 elements, then use just < instead, using <= will get you 4 elements (since it works for 0, 1, 2, and 3).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM