Sindre
Sindre

Reputation: 193

NameError after importing a file

I have two files. One called "variables.py" with this function in:

def get_players():
    '''
    (NoneType) -> Dictionary
    Asks for player names
    '''
    loop = True
    players = {}
    while loop == True:
        player = input("Enter player names: ")
        player = player.strip()
        if player in players or player == "":
            print("Choose a different name!")
        elif "player1" in players:
            players["player2"] = [player, 0]
        elif player not in players:
            players["player1"] = [player, 0]
        if len(players) >= 2:
            loop = False
    return players

And another file in the same directory called "game.py" with this inside:

import variables
players = get_players()

When i try to run "game.py" i get this errorNameError: name 'get_players' is not defined why?! I have tried everything!

Upvotes: 0

Views: 128

Answers (3)

Claudiu
Claudiu

Reputation: 229331

With Python, when you import a module, a module variable is created of that name which is where all the imported module's variables live:

import variables
players = variables.get_players()

You can also import from a module which will just introduce that name by itself:

from variables import get_players
players = get_players()

You can also do the following to import all names from a module, but it is discouraged because it leads to hard-to-read code:

from variables import *
players = get_players()

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 599570

You have imported variables, not get_players. You can either keep the import as it is and call variables.get_players(), or do from variables import get_players and then call get_players().

This is a fairly fundamental thing in Python: looks like you could benefit from a basic tutorial.

Upvotes: 1

karthikr
karthikr

Reputation: 99620

It should be

players = variables.get_players()

Since you have imported only the module variables, and not the method get_players.

Or you could also do:

from variables import get_players

players = get_players()

Read more on importing modules here

Upvotes: 2

Related Questions