Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/286.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python将子例程定义转移到另一个子例程_Python - Fatal编程技术网

python将子例程定义转移到另一个子例程

python将子例程定义转移到另一个子例程,python,Python,是否可以将定义从一个子例程转移到另一个子例程?我找不到一种方法将dealthehand转换为playthegame而不说“deckchoice未定义”” 其思想是从函数返回一个值,以便调用代码可以访问结果 def dealthehand(): deck2=[1, 2, 3, 4, 5, 6, 7, 8, 9] deckchoice=random.choice(deck2) deckchoice2=random.choice(deck2) deckchoice3=

是否可以将定义从一个子例程转移到另一个子例程?我找不到一种方法将
dealthehand
转换为
playthegame
而不说“
deckchoice未定义”

其思想是从函数返回一个值,以便调用代码可以访问结果

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)
通过索引元组访问手中的单个卡片,例如,第三张卡片将是
hand[2]
(索引从0开始)


构造返回值(本例中为元组)相当麻烦。最好使用一个复数变量将已发牌组合成一手牌。您可以使用元组、列表、字典或您自己的自定义类来实现这一点—这取决于您需要如何使用它

下面是一个使用列表表示一手6张牌的示例:

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

这使用列表理解来创建一个包含6张随机卡的列表。

返回结果。
deck2=[123456789]
在这里没有任何意义我在哪里使用“返回”?
def dealthehand():
    cards = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    return [random.choice(cards) for i in range(6)]