Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/339.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_Python 3.x - Fatal编程技术网

Python 如何从函数中取出变量?

Python 如何从函数中取出变量?,python,python-3.x,Python,Python 3.x,我无法从函数内输出卡片值(它不会更新函数外的变量。我尝试过使用return,但没有效果) 当我运行它时,它的名称为“test”,值为0(我在开始时设置了它)。我如何使它更新 我希望能够在函数完成后打印cardName。返回两个值的元组。您甚至可以将它们立即解压为两个变量 >>> def f(): ... x = 5 ... y = 6 ... return (x,y) ... >>> f() (5, 6) >>> a

我无法从函数内输出卡片值(它不会更新函数外的变量。我尝试过使用return,但没有效果)

当我运行它时,它的名称为“test”,值为0(我在开始时设置了它)。我如何使它更新


我希望能够在函数完成后打印cardName。

返回两个值的元组。您甚至可以将它们立即解压为两个变量

>>> def f():
...     x = 5
...     y = 6
...     return (x,y)
... 
>>> f()
(5, 6)
>>> a, b = f()
>>> a
5
>>> b
6

我更新了您的示例,使其能够正常工作。您必须返回这两个变量,还可以在返回时分配它们:

cardName = "test"
cardValue1 = 0

def random_card():
    number = (random.choice(cardsList))
    suit = (random.choice(suitList))
    cardName = number + suit
    print (cardName)
    if cardName.startswith('A'):
        print ("Do you want this card to count as a 1 or 11?")
        oneOrEleven = input()
        if oneOrEleven == ("11"):
            cardValue1 = 11
        else:
            cardValue1 = 1
    elif cardName.startswith("2"):
        cardValue1 = 2
    elif cardName.startswith("3"):
        cardValue1 = 3
    elif cardName.startswith("4"):
        cardValue1 = 4
    elif cardName.startswith("5"):
        cardValue1 = 5
    elif cardName.startswith("6"):
        cardValue1 = 6
    elif cardName.startswith("7"):
        cardValue1 = 7
    elif cardName.startswith("8"):
        cardValue1 = 8
    elif cardName.startswith("9"):
        cardValue1 = 9
    elif cardName.startswith("1"):
        cardValue1 = 10
    elif cardName.startswith("K"):
        cardValue1 = 10
    elif cardName.startswith("Q"):
        cardValue1 = 10
    elif cardName.startswith("J"):
        cardValue1 = 10
    else:
        a = 1
    
    print ("Your card is '",cardName,"'","and it is worth",cardValue1)

    return cardValue1, cardName
    
    
cardName, cardValue1 = random_card()

print (cardName)
print (cardValue1)

您可以一次返回多个内容,只需用逗号分隔并跟踪索引即可

def hi():
    x, y = 5, 4
    return x, y

x, y = hi()

x,y=random\u card
函数内
return cardValue1,cardName
在同一函数内不能使用
return
语句两次。使用instead这是否回答了您的问题?设计建议:
random\u card
不必担心卡的值;它只需返回一张卡即可。这取决于无论是谁打电话给《随机卡》(random_card)来决定这张卡的价值(因为收到新卡后可能会发生变化)谢谢你,我一直在努力解决这个问题,通过将它添加到我的代码中,它帮助我理解了!Np,我想情况就是这样。