How to randomly shuffle a deck of cards among players?

前端 未结 3 1435
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-28 02:33

I am having trouble using one function in another to deal cards. Here is what I have so far.

import random as rand 

def create(): 
     ranks = [\'2\', \'3\',          


        
3条回答
  •  孤街浪徒
    2021-01-28 03:01

    Forget about your two functions, since they're both correct, and look at your top-level code:

    import random as rand
    def ...
    def ...
    print(cards_dealt(5, 3, deck)) 
    

    Where does deck come from? Nowhere. Hence the exception.

    It's pretty obvious where you intended it to come from—you have a create function that ends with a return deck. You just aren't calling it anywhere.

    So you want:

    import random as rand
    def ...
    def ...
    deck = create()
    print(cards_dealt(5, 3, deck)) 
    

    … or, if you want to make it clearer that the global variable is unrelated to the two locals:

    import random as rand
    def ...
    def ...
    mydeck = create()
    print(cards_dealt(5, 3, mydeck)) 
    

    … or, if you want to make things more concise:

    import random as rand
    def ...
    def ...
    print(cards_dealt(5, 3, create())) 
    

    Beyond this problem, cards_dealt doesn't have a return, so it just returns None. When your function is complete, there might be something worth printing out, but for now, while you're debugging what you have so far, it's not very useful.

    Meanwhile, if you want to print the shuffled deck, which could be useful, you'd do something like this:

    import random as rand
    def ...
    def ...
    mydeck = create()
    cards_dealt(5, 3, mydeck)
    print(mydeck)
    

    When you later finish the function so it returns, say, a tuple of 3 lists of 5 cards, you'll probably want to store those return values for later as well as printing them, so it might go something like this:

    import random as rand
    def ...
    def ...
    mydeck = create()
    hands = cards_dealt(5, 3, mydeck)
    for hand in hands:
        print(hand)
    

提交回复
热议问题