3

I understand that functions are useful for code which will be used multiple times so I tried creating a function to save myself time and make my code look neater. The function I had looks like this:

def drawCard():
    drawnCard = random.choice(cardDeck)
    adPos = cardDeck.index(drawnCard)
    drawnCardValue = cardValues[adPos]

However, I am not sure how to return these variables as they are local(?). Therefore, I can not use these variables outside the function. I am just wondering if someone could help edit this function in a way where I could use the drawnCard and drawnCardValue variables outside the function?

1
  • return Commented Mar 22, 2014 at 14:33

1 Answer 1

3

Use return:

def drawCard():
    drawnCard = random.choice(cardDeck)
    adPos = cardDeck.index(drawnCard)
    drawnCardValue = cardValues[adPos]
    return drawnCard, drawnCardValue

drawnCard, drawnCardValue = drawnCard()

Note, you could also write drawCard this way:

def drawCard():
    adPos = random.randrange(len(cardDeck))
    drawnCard = cardDeck[adPos]
    drawnCardValue = cardValues[adPos]
    return drawnCard, drawnCardValue

These two functions behave differently if cardDeck contains duplicates, however. cardDeck.index would always return the first index, so drawnCardValue would always correspond to the first item which is a duplicate. It would never return the second value (which in theory could be different.)

If you use adPos = random.randrange(len(cardDeck)) then every item in cardValue has an equal chance of being selected -- assuming len(cardValue) == len(cardDeck).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.