从另一个函数导入输出 [英] Importing an output from another function

查看:80
本文介绍了从另一个函数导入输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能是一个愚蠢的问题,但我是一个新手,这真让我感到生气

off。运行这个脚本:


随机导入


def Func1():

choice =(''A' ',''B'',''C'')

输出= random.choice(选择)


def Func2():

打印输出


Func1()

Func2()


并且:出现错误信息......它说:


Traceback(最近一次调用最后一次):

文件" ptls-demo.py",第11行, in?

Func2()

文件" how -the-hell-do-i-fix-this.py,第8行,在Func2中

打印输出

NameError:全局名称''输出''未定义


显然,我需要导入变量''output' '从Func1()进入

Func2(),但是如何?


提前致谢,

- / usr / bin / byte

解决方案

通常,定义到函数中的名称不能在其外部读取,

所以你必须返回n功能结果明确:


随机导入


def Func1():

choice =('' A'',''B'',''C'')

输出= random.choice(选择)

返回输出


def Func2(item):

打印商品


output1 = Func1()

Func2(output1)

再见,

熊宝宝


太棒了,谢谢


- / usr / bin / byte

blockquote>

现在如果Func1()有多个输出并且Func2()需要
我该怎么办?
他们都给出了自己的输出,如下:


随机导入


def Func1():

choice =('''',''B'',''C'')

输出= random.choice(选择)

output2 = random.choice(选择)

返回输出

返回输出2

def Func2(item1,item2):

打印item1,item2


output1 = Func1()

Func2(输出1)


提前致谢,

- / usr / bin /字节


Probably a stupid question, but I''m a newbie and this really pisses me
off. Run this script:

import random

def Func1():
choice = (''A'', ''B'', ''C'')
output = random.choice(choice)

def Func2():
print output

Func1()
Func2()

And: an error message...... It says:

Traceback (most recent call last):
File "ptls-demo.py", line 11, in ?
Func2()
File "how -the-hell-do-i-fix-this.py", line 8, in Func2
print output
NameError: global name ''output'' is not defined

Obviosly, I need to import the variable ''output'' from Func1() into
Func2(), but how?

Thanks in advance,
-- /usr/bin/byte

解决方案

Generally, a name defined into a function can''t be read outside of it,
so you have to return the function result explicitely:

import random

def Func1():
choice = (''A'', ''B'', ''C'')
output = random.choice(choice)
return output

def Func2(item):
print item

output1 = Func1()
Func2(output1)
Bye,
bearophile


Great, thanks

-- /usr/bin/byte


Now what do I do if Func1() has multiple outputs and Func2() requires
them all to give its own output, as follows:

import random

def Func1():
choice = (''A'', ''B'', ''C'')
output = random.choice(choice)
output2 = random.choice(choice)
return output
return output2

def Func2(item1, item2):
print item1, item2

output1 = Func1()
Func2(output1)

Thanks in advance,
-- /usr/bin/byte


这篇关于从另一个函数导入输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆