4

I'm a newbie programmer trying to make a program, using Python 3.3.2, that has a main() function which calls function1(), then loops function2() and function3().

My code generally looks like this:

def function1():
    print("hello")

def function2():
    name = input("Enter name: ")

def function3():
    print(name)

def main():
    function1()
    while True:
        funtion2()
        function3()
        if name == "":
            break

main()

Currently, I get the following error when I run the program and enter a name:

NameError: global name 'name' is not defined

I understand that this is because name is only defined within function2(). How do I make it so that name is defined as a 'global name', or somehow be able to use it within function3() and main().

Thanks in advance.

2 Answers 2

5

Don't try to define it a global variable, return it instead:

def function2():
    name = input("Enter name: ")
    return name

def function3():
    print(function2())

If you want to use variables defined in function to be available across all functions then use a class:

class A(object):

   def function1(self):
       print("hello")

   def function2(self):
       self.name = input("Enter name: ")

   def function3():
       print(self.name)

   def main(self):  
       self.function1()
       while True:
          funtion2()
          function3()
          if not self.name:
              break

A().main()
Sign up to request clarification or add additional context in comments.

2 Comments

I tried this but now it returns this error: Traceback (most recent call last): File "I:\School\ITEC 1150-02\Address book group assignment\TEAMLAB2.py", line 43, in <module> A().main() File "I:\School\ITEC 1150-02\Address book group assignment\TEAMLAB2.py", line 37, in main function2() NameError: global name 'function2()' is not defined
Nevermind, I got it to work; used self.function2() instead of just function2(). Thanks a bunch!
3

Define the variable outside of your functions, and then declare it first as global inside with the global keyword. Although, this is almost always a bad idea because of all of the horrendous bugs you'll end up creating with global state.

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.