I'm just learning python so sorry for what is probably a simple question.
Following Zed Shaw's 'learn python the hard way' I made a little text game (ex36). It defines the functions start() and litroom(), then runs start(), which in turn runs litroom() depending on user input.
How would I import only the litroom() function to another file? If I try
from ex36 import litroom
it seems to import the lot and run start().
Thanks for any help!
1 Answer 1
When you import from ex36, it will read the whole file and execute any code not inside function.
If you have
def start():
print ("hello")
def litroom():
start()
start()
in your ex36 file, your statement import ex36 or from ex36 import litroom will execute start. You should fix the code like that:
def start():
print ("hello")
def litroom():
start()
if __name__=='__main__':
# magix trick : name value is the name of the file
# unless run as the "main" script where it's __main__
start()
You can see What does if __name__ == "__main__": do?
ex36in the magicif __name__=='__main_':so it does not get executed at import