I'm trying to make a program, that goes randomly through a stack of cards for 'i' amount of decks. However my while loop seems to stop after 1 run? How come it won't loop?
cards = ['Two of Hearts', 'Two of Diamonds', 'Two of Spades', 'Two of Clubs', 'Three of Hearts', 'Three of Diamonds', 'Three of Spades', 'Three of Clubs', 'Four of Hearts', 'Four of Diamonds', 'Four of Spades', 'Four of Clubs', 'Five of Hearts', 'Five of Diamonds', 'Five of Spades', 'Five of Clubs', 'Six of Hearts', 'Six of Diamonds', 'Six of Spades', 'Six of Clubs', 'Seven of Hearts', 'Seven of Diamonds', 'Seven of Spades', 'Seven of Clubs', 'Eight of Hearts', 'Eight of Diamonds', 'Eight of Spades', 'Eight of Clubs', 'Nine of Hearts', 'Nine of Diamonds', 'Nine of Spades', 'Nine of Clubs', 'Ten of Hearts', 'Ten of Diamonds', 'Ten of Spades', 'Ten of Clubs', 'Jack of Hearts', 'Jack of Diamonds', 'Jack of Spades', 'Jack of Clubs', 'Queen of Hearts', 'Queen of Diamonds', 'Queen of Spades', 'Queen of Clubs', 'King of Hearts', 'King of Diamonds', 'King of Spades', 'King of Clubs', 'Ace of Hearts', 'Ace of Diamonds', 'Ace of Spades', 'Ace of Clubs']
i = 0
while i <= 5:
cardsTemp = cards
for n in cardsTemp:
card = random.randint(1,len(cardsTemp)) - 1
print(cardsTemp[card])
print('cardsTempt len: ' str(len(cardsTemp)))
cardsTemp.remove(cardsTemp[card])
i = 1
CodePudding user response:
The while
loop iterates; you just never enter the for
loop, because cardsTemp = cards
does not make a copy of cards
. You are emptying cards
using cardsTemp.remove
, so eventually cardsTemp
is empty.
How long it takes to empty the list depends on the order in which cards are removed.
CodePudding user response:
Try copying the orignal cards into cards temp inside the while loop.
while i <= 5:
cardsTemp = cards.copy()
for n in cardsTemp:
card = random.randint(1,len(cardsTemp)) - 1
print(cardsTemp[card])
print('cardsTempt len: ' str(len(cardsTemp)))
cardsTemp.remove(cardsTemp[card])
i = 1