Search code examples
pythonmethodsscopecall

Calling a method in main.py / understanding scope


How do I fix the scope of the following scenario? The main code of my program (within main.py) was not in a method initially. I want to put it into a method and as soon as I put it in a method and called it, errors came up everywhere.

How do I make it so that when I put my main block of code into a method that it runs just as if it wasn't in a method.

I'm a novice when it comes to python and programming in general, so please excuse my ignorance and please be as simple as possible when you answer. Thanks! import Customer import Account import Transaction

def populate():
    z1 = Customer.Customer("1234","XXXXX","XXXXXXX","XXXXXX","XXXXXX","XXXXXX","XXXXX")
    dict[z1.getCNumber()] = z1
    a1 = Account.Account("4321",True,0.00,700.00)
    dict[z1.getCNumber()].AddAccount(a1)

def printInfo():
    z1.description()
    a1.description()

populate()
printInfo()

This makes errors in the printInfo() method. c1 and a1 variables. I don't understand how to fix it.

Errors include: global name 'z1' is not defined

When I place z1 = "" and a1 = "" at the top, this is the error I get:

z1.description()
AttributeError: 'str' object has no attribute 'description'

all of this works if it is outside of a method


Solution

  • a1 and z1 only exist until the end of the populate function. After that, poof, they're deleted out of the computer's memory. This means that populate does virtually nothing (except maybe spin up the processor a bit). Consider returning the values of a1 and z1 and then giving them as parameters to printInfo. Or if printInfo will always be called after populate maybe just put the code inside the populate function.

    On another note, in the code you've posted it doesn't look like you're even calling printInfo, but rather printBank, which would throw an error as that's not defined.

    To return them as a tuple, you would add this line at the end of populate:

    return (a1, z1)
    

    Then when you call it you could say:

    (a, z) = populate()
    

    Then you would change the header of printInfo to:

    printInfo(a1, z1):
    

    So you would call it like:

    printInfo(a,z)