Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Yang Hu
Yang Hu
7,782 Points

Problem working with multiple files.

Hi all, I made a very simple program for testing, it's like this:

player_name = "Jack"
def print_name():
    print(player_name)
print_name()

Now I move my function to another file, so file 1 becomes:

from file_2 import print_name
player_name = "Jack"
print_name()

file_2:

def print_name():
    print(player_name)

Ok, now if I run file 1, I'll get a name error saying that player_name is not defined. So it seems to me that the import statement does not simply add the code of file 2 to file 1. So is there a way to have file 2 acknowlege the player_name variable in file 1, so I don't have to set and pass in parameters this:

from file_2 import print_name
player_name = "Jack"
print_name(player_name)
def print_name(player_name):
    print(player_name)

You should be able to create a separate file named player_name with whatever you need in it, then import that at the beginning of your other files with "import player_name"