2

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!

2
  • Import syntax is correct. Paste your code. Commented Nov 6, 2013 at 18:19
  • 5
    embed your code in ex36in the magic if __name__=='__main_': so it does not get executed at import Commented Nov 6, 2013 at 18:20

1 Answer 1

2

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?

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.