0

我在函数中设置了一个名为“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.

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

提前致谢 - TGSpike

4

1 回答 1

0

你应该把线

return charge

在函数的末尾,然后当你调用函数时,做

charge = service(x, y, z)

(使用x y zset 但是你正在使用它们)。这会将 的值返回charge给您的主程序,并将其放入变量中charge。如果你想用多个变量来做这个,你可以做

return x, y

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

这称为元组解包。

于 2013-06-10T17:19:21.037 回答