Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems putting a for loop into a function (Python3)

This post has been answered, read it if you like.

I have been attempting to write a card-game in python 3, and I have been using a for loop to transfer cards from a deck list to hand list. I'm attempting to put this into a function, but command prompt crashes. help?

from random import *
print("Sam's Casino")
cards = ['1','2','3','4','5','6','7','8','9','10','J',
'Q','K','1','2','3','4','5','6','7','8','9','10','J',
'Q','K','1','2','3','4','5','6','7','8','9','10','J',
'Q','K','1','2','3','4','5','6','7','8','9','10','J',
'Q','K']
shuffle(cards)
print(cards)
hand1 = []
hand2 = []
count = 0
def deal(cards):
    for card in cards:
        if count < 4:
            hand1.append(card)
            count += 1
        if count > 3 and count < 8:
            hand2.append(card)
            count += 1

deal(cards)
print(hand1)
print(hand2)
input('>')

Edit: No error is recieved, it simply closes.

like image 487
The Samstro Avatar asked Dec 17 '25 23:12

The Samstro


1 Answers

UnboundLocalError: local variable 'count' referenced before assignment

Put count inside the function deal

def deal(cards):
    count = 0
    for card in cards:
        if count < 4:
            hand1.append(card)
            count += 1
        if count > 3 and count < 8:
            hand2.append(card)
            count += 1

This works.

like image 171
Attersson Avatar answered Dec 20 '25 11:12

Attersson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!