我在函数中设置了一个名为“ 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.我是新手,仅尝试简单的代码。如果需要高级功能,请解释一下该功能,因为我不太可能知道它,
1 回答

catspeake
TA贡献1111条经验 获得超0个赞
你应该把线
return charge
在函数的末尾,然后在调用函数时,执行
charge = service(x, y, z)
(x
y
z
但已设置,但您正在使用它们)。这将把值返回charge
到您的主程序,并将其放在变量中charge
。如果要使用多个变量执行此操作,则可以执行
return x, y
和
x, y = service(x, y, z)
这称为元组拆包。
添加回答
举报
0/150
提交
取消