简体   繁体   English

在不同的函数中使用一个变量的不同值

[英]Using different values of one variable in different functions

Suppose there is this program假设有这个程序

def function():
  print(variable)

def main():
  variable = "Hello"
  function()

def main_2():
  variable="Bye"
  function()

main()
main_2()

there's an error that variable is not defined有一个variable未定义的错误

I am going to use the function function() a lot, and I want it to use the variable defined in the function main() for only main() and the variable defined in main_2() in only main_2() .我将大量使用 function function() ,我希望它仅将 function main()中定义的variable用于main() ,将main_2()中定义的变量仅main_2() How can I do that我怎样才能做到这一点

You define variable as local variable in main functions.您在 main 函数中将variable定义为局部变量。 Either you should use it as a global variable or your function() should take input named variable .您应该将它用作全局变量,或者您的function()应该采用名为variable的输入。

Here is correct version of the code:这是代码的正确版本:

First of all you need to call global to make the local "scope" global :首先,您需要调用global来使local “作用域”成为global

Here is the snippet:这是片段:

def function():
    print(variable)


def main():
    global variable
    variable = "Hello"
    function()


def main_2():
    global variable
    variable = "Bye"
    function()

main()
main_2()

Hope so this information is useful and helpful希望这些信息有用和有帮助
Happy Coding快乐编码

You can pass the variable to your function and use this code您可以将变量传递给您的 function 并使用此代码

def function(variable):
  print(variable)

def main():
  variable = "Hello"
  function(variable)

def main_2():
  variable="Bye"
  function(variable)

main()
main_2()

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

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