LiterallyJohnny
LiterallyJohnny

Reputation: 43

Python: Unable to use variable from another file even though the file is imported

I am trying to write a game of rock, paper, scissors, and I am getting an error about a file I imported not having an attribute of "quitGame", even though I should have that variable imported along with the others.

Here is the function that has the quitGame variable (uneeded parts filtered out):

def playRps():
    game = "".join([playerAction, computerAction])
    global quitGame

    outcomes = {
        "rr": tied,
        "pp": tied,
        "ss": tied,
        "rp": playerLoss,
        "ps": playerLoss,
        "sr": playerLoss,
        "rs": playerWin,
        "pr": playerWin,
        "sp": playerWin,
    }

    if playerAction == "q":
        quitGame = True  # TODO: Figure out why this isn't working in the main.py file
    else:
        action = outcomes.get(game)
        if action:
            action()
        else:
            print("Invalid input!")

You can also find the entire functions.py file here.

Here is the main.py file that should runs the program (uneeded parts filtered out):

import functions  # Imports the functions.py file
while True:
    playGame = str(input('Would you like to play "Rock, Paper, Scissors"? (Y/n): '))

    if playGame == "y":
        while True:
            functions.playerChoice()
            functions.computerChoice()
            functions.playRps()
            if functions.quitGame == True:
                break

    elif playGame == "n":
        print("Terminating program...")
        quit()

    else:
        print("Unknown input. Please enter a valid answer.")
        continue

You can also find the entire main.py file here.

Here is the interaction that gave me the error I am trying to fix:

(.venv) johnny@lj-laptop:rock_paper_scissors$ /home/johnny/Projects/rock_paper_scissors/.venv/bin/python /home/johnny/Projects/rock_paper_scissors/main.py
Would you like to play "Rock, Paper, Scissors"? (Y/n): y

    Rock, paper, or scissors?
    Acceptable responses are...
    "r": Chooses rock.
    "p": Chooses paper.
    "s": Chooses scissors.

    "q": Quits the game.
    r
Tied! No points awarded.
Traceback (most recent call last):
  File "/home/johnny/Projects/rock_paper_scissors/main.py", line 18, in <module>
    if functions.quitGame == True:
AttributeError: module 'functions' has no attribute 'quitGame'

I find this very odd, because other variables such as playerScore and computerScore work as expected. I have functions. added before each variable and function, so it makes no sense as to why it's telling me I don't have it.

I even added global quitGame in the function that creates the variable. I don't see why this isn't working.

My question to you guys is:

Upvotes: 2

Views: 661

Answers (2)

gianoseduto
gianoseduto

Reputation: 194

You have to use global before the variables is "requested" not "declared".

So if you want quitGame to be global you have to declare it were do you prefer (for example in main.py) and then were do you want to use it (as the example in a function) use "global quitGame".

You can tell to your function to access to a global var called quiteGame, instead of declaring quiteGame as global.

Upvotes: 1

jaabberwocky128
jaabberwocky128

Reputation: 16

Cloned your repository and realised that I can play the game if I first chose "q" first, followed by answering "Y" then playing the game.

Would you like to play "Rock, Paper, Scissors"? (Y/n): y

    Rock, paper, or scissors?
    Acceptable responses are...
    "r": Chooses rock.
    "p": Chooses paper.
    "s": Chooses scissors.

    "q": Quits the game.
    q
Would you like to play "Rock, Paper, Scissors"? (Y/n): y

    Rock, paper, or scissors?
    Acceptable responses are...
    "r": Chooses rock.
    "p": Chooses paper.
    "s": Chooses scissors.

    "q": Quits the game.
    r
Tied! No points awarded.
Would you like to play "Rock, Paper, Scissors"? (Y/n): 

This is because your functions.quitGame global is only initialised when functions.playRps() is run. Before this, it does not exist and thus if you answered "r" right after choosing "y" to start the game, the functions.quitGame global does not exist yet. You can fix this by initialising the variable in your functions.py file beneath the declaration of computerScore:

playerScore = 0
computerScore = 0
quitGame = False

After this, you will then be able to play the game without any issue.

Upvotes: 0

Related Questions