猿问

尝试调用在函数内分配的字符串

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

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



慕仙森
浏览 198回答 1
1回答

catspeake

你应该把线return charge在函数的末尾,然后在调用函数时,执行charge = service(x, y, z)(x y z但已设置,但您正在使用它们)。这将把值返回charge到您的主程序,并将其放在变量中charge。如果要使用多个变量执行此操作,则可以执行return x, y和x, y = service(x, y, z)这称为元组拆包。
随时随地看视频慕课网APP

相关分类

Python
我要回答