2017-10-29 1 views
0

定義をあるサブルーチンから別のサブルーチンに移すことは可能ですか?私はそれが呼び出し元のコードが結果にアクセスできるようにアイデアは、関数からの戻り値にある「deckchoice is not defined他のサブルーチンへのpython転送サブルーチン定義

def dealthehand(): 
    deck2=[123456789] 
    deckchoice=random.choice(deck2) 
    deckchoice2=random.choice(deck2) 
    deckchoice3=random.choice(deck2) 
    deckchoice4=random.choice(deck2) 
    deckchoice5=random.choice(deck2) 
    deckchoice6=random.choice(deck2) 



def playthegame(): 

    dealthehand() 
    print(deckchoice) 
+0

結果を '返す '。 –

+0

と 'deck2 = [123456789]'はここで意味をなさない –

+0

どこで 'return'を使うのですか? –

答えて

1

を言わずplaythegamedealthehandを転送する方法を見つけることができません。

def dealthehand(): 
    deck2=[1, 2, 3, 4, 5, 6, 7, 8, 9] 

    deckchoice=random.choice(deck2) 
    deckchoice2=random.choice(deck2) 
    deckchoice3=random.choice(deck2) 
    deckchoice4=random.choice(deck2) 
    deckchoice5=random.choice(deck2) 
    deckchoice6=random.choice(deck2) 

    return (deckchoice, deckchoice2, deckchoice3, deckchoice4, deckchoice5, deckchoice6) 

def playthegame(): 
    hand = dealthehand() 
    print(hand) # will print a tuple, e.g. (5, 8, 2, 2, 1, 3) 

タプルのインデックスを付けて、手の中の個々のカードにアクセスします。 3番目のカードはhand[2](インデックスは0から始まります)です。


戻り値(この場合はタプル)を作成するのはかなり面倒です。 1つの複雑な変数を使って、処理されたカードをまとめて1つの手にまとめる方がよいでしょう。これを行うには、タプル、リスト、辞書、または独自のカスタムクラスを使用することができます。使用方法によって異なります。

はここで6枚のカードの手を表現するリストを使用した例です:

def dealthehand(): 
    cards = [1, 2, 3, 4, 5, 6, 7, 8, 9] 
    return [random.choice(cards) for i in range(6)] 

これは6枚のランダムなカードのリストを作成するには、リスト内包表記を使用しています。

関連する問題