0

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

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(). How can I do that

3 Answers 3

1

You define variable as local variable in main functions. Either you should use it as a global variable or your function() should take input named variable.

Sign up to request clarification or add additional context in comments.

Comments

0

Here is correct version of the code:

First of all you need to call global to make the local "scope" 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

Comments

0

You can pass the variable to your function and use this code

def function(variable):
  print(variable)

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

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

main()
main_2()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.