试图调用在函数中分配的字符串

2024-03-29 14:52:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我在函数中设置了一个名为“charge”的字符串,但是当我在主体中调用“charge”时,我得到一个回溯调用,说“charge”没有定义。我想知道是否有可能从函数外部调用字符串,如果没有,是否有其他方法来获取电荷内的数据?你知道吗

def service (x, y, z):
    print ('How many animals are being provided for?')
    nodogs = input ('-----> ')

    if nodogs == '1':
        charge = 'x'

    elif nodogs == '2':
        charge = 'y'

    elif nodogs == '3':
        charge = 'z'

    x = int (x)
    y = int (y)
    z = int (z)

# the call for the string is later on but I think that part is irrelevant.
#If it is not, please say and I will post it.

我是一个新手,只是尝试简单的代码。如果需要高级功能,请解释该功能,因为我不太可能已经知道了

提前谢谢-谢谢


Tags: the方法函数字符串功能for定义is
1条回答
网友
1楼 · 发布于 2024-03-29 14:52:27

你应该放线

return charge

在函数末尾,然后在调用函数时

charge = service(x, y, z)

(使用xyz设置,不管您如何使用它们)。这将把charge的值返回到主程序,并将其放入变量charge。如果你想用多个变量,你可以这样做

return x, y

以及

x, y = service(x, y, z)

这称为元组解包。你知道吗

相关问题 更多 >