简体   繁体   English

从函数返回变量

[英]Return variable from a function

This section of a program I am writing is supposed to take the random choice and then print it outside the function (I can't print from within as I need the variable later). 我正在编写的程序的这一部分应该采用随机选择,然后在函数外部进行打印(由于以后需要变量,因此无法从内部进行打印)。 I am sure there is a simple solution to this, but I am unsure what it is. 我敢肯定有一个简单的解决方案,但是我不确定是什么。

#python2
def CompTurn():
  RandTurn = [Column1,Column2,Column3,Column4]
  Choice = random.choice(RandTurn)
  return(Choice)
print Choice

Thank you. 谢谢。

Add the line 添加行

Choice = CompTurn()

before your print statement. 在您的打印对帐单之前。 Because the variables you declare within the function are not known outside of it, you have to store (or print directly, but then you cannot store it) the returned variable in a new variable. 由于在函数内声明的变量在函数外不为人所知,因此必须将返回的变量存储(或直接打印,但随后无法存储)在新变量中。

You have defined your function correctly, but you never executed it! 您已经正确定义了函数,但从未执行过! (You'll see that if you make it print something as a diagnostic.) You must run it to get the result: (如果将其打印出来作为诊断内容,则会看到它。)必须运行它才能得到结果:

chosen = CompTurn()
print chosen

Note that I used a different variable name. 请注意,我使用了不同的变量名。 You could use the same variable name as a variable in your function, but it's still a different variable than the one in your function. 可以在函数中使用与变量相同的变量名,但它仍然与函数中的变量不同。

It is also important to realize that your function returns a value, not a variable. 同样重要的是要认识到您的函数返回一个值,而不是一个变量。 You can assign the value to a variable (as above) or print it immediately. 您可以将值分配给变量(如上所述)或立即打印。

print CompTurn()

About your program, you don't need the brackets for return . 关于你的程序,你不需要括号return It's s statement, not a function. 这是声明,不是函数。

def CompTurn():
  RandTurn = [Column1,Column2,Column3,Column4]
  Choice = random.choice(RandTurn)
  return Choice 

Shorter: 更短:

def CompTurn():
      RandTurn = [Column1,Column2,Column3,Column4]
      return random.choice(RandTurn)

To print the return value, You can save it in a variable and print it 要打印返回值,可以将其保存在变量中并打印

ret = CompTurn()
print ret

Or print directly: 或直接打印:

print CompTurn()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM