Exercise 45 - running the prototype doesn't give output

Hi guys.

I tried to run my code with only 1 scene to see if it works. Although I do not get an errorcode, it does not run anything.

What am I missing?

from fundamentals import engine
from sys import exit
from random import randint
from sys import argv


script, name = argv

player = {
        'name': name,
        'lvl' : 1,
        'xp' : 0,
        'lvlnext' : 25,
        'stats' : {'charisma' : 1}}

def level(char, stats):
    nchar = 0
    while player['xp'] >= player['lvlnext']:
        player['lvl'] += 1
        player['xp'] = player['xp'] - ['lvlnext']
        player['lvlnext'] = round(player['lvlnext'] * 1.5)
        stats['charisma'] += 1


class scene(object):

    def __init__(self, owner, opponent):
        self.owner = owner
        self.opponent = opponent

    def enter(self):
        pass
    exit(1)

class failure(scene):
    wrong = [
            "Sorry. That just won't cut it.",
            "Nice try..."
            "No. Just no."]

    print(failure.wrong[randint(0,2)])

class entrance(scene):

    def enter(self):
        print(f"""Hi there {name}. There is not a lot of time so i'll make it quick.
        You are entering the building of a top criminal who is throwing a party at his house.
        It is your job to find and escape with the intel and to do so unnoticed.

        There are 2 Guards at the door. What do you do?
        1. Wait for distraction.
        2. Talk your way in.
        3. Attack them.
        """)

        action = input("> ")

        if action == "1":
            print("You wait untill two hysteric lady's distract the guards and sneek by the guards.")

            return'ballroom'

        elif action == "2":
            print("""Ha. You still got it. You fooled that guards into thinking you are managing the diner.
                    That's a nice confidence booster""")

            return'ballroom'
            player['xp'] += 25

        elif action == "3":
            print("""You managed to knock both of them out roadhouse style.
                    However, this made to big of a scene. You cannot continue the mission.""")




class world(object):

    stages = {
        'entrance': entrance(),
        'ballroom': ballroom(),
        'privateroom': privateroom(),
        'secretdoorway': privateroom(),
        'carriage': carriage()
    }

    def __init__ (self, start_stage):

        self.stageobject = start_stage

        def next_stage(self, stage_name):
            next = world.stages.get(stage_name)
            return next

        def opening_stage(self):
            return self.next_stage(self.start_stage)

a_world = world('entrance')
a_game = fundamentals.engine(a_world)
a_game.play()

I import the engine from another file but is basicly the same as exercise 43:

class engine(object):

    def __init__ (self, stage_world):
        self.stage_world = stage_world

    def play(self):
        current_stage = self.stage_world.opening_stage()
        last_stage = self.stage_world.next_stage('carriage')

        while current_stage != last_stage:
            next_stage_name = current_stage.enter()
            current_stage = self.stage_world.next_stage(next_stage_name)


        current_stage.enter()

Aside from this. By watching some videos on youtube I tried to make a leveling system. If you look at my code, am I going about this the right way? Or will the player lose all its level and experience by switching between stages?

Your help is much appreciated!

You have a rogue exit() in the code of the scene class that is not part of any method (indentation). That causes the program to shut down the moment it hits this line when the class is first set up.

Your levelling system looks good to me, nice. Why don’t you make a player class of this?

1 Like

Yes, that exit(1) is evil. It’s not indented right so it looks like it’s fine but just 3 spaces and your script silently exits. Just remove all calls to exit() until you’re sure you want them.

Aha I see. It runs now. When it did, I had a lot of bugs to solve. So the working in smaller approach seems to be very wise. However, there is one bug which I find hard to solve.

I run this:

from fundamentals import engine
from sys import exit
from random import randint
from sys import argv


script, name = argv

player = {
        'name': name,
        'lvl' : 1,
        'xp' : 0,
        'lvlnext' : 25,
        'stats' : {'charisma' : 1}}

def level(char, stats):
    nchar = 0
    while player['xp'] >= player['lvlnext']:
        player['lvl'] += 1
        player['xp'] = player['xp'] - ['lvlnext']
        player['lvlnext'] = round(player['lvlnext'] * 1.5)
        stats['charisma'] += 1


class scene(object):

    def __init__(self):
        pass

    def enter(self):
        pass


class failure(scene):
    wrong = [
            "Sorry. That just won't cut it.",
            "Nice try..."
            "No. Just no."]
    def enter():
        print(failure.wrong[randint(0,2)])

class entrance(scene):

    def enter(self):
        print(f"""Hi there {name}. There is not a lot of time so i'll make it quick.
        You are entering the building of a top criminal who is throwing a party at his house.
        It is your job to find and escape with the intel and to do so unnoticed.

        There are 2 Guards at the door. What do you do?
        1. Wait for distraction.
        2. Talk your way in.
        3. Attack them.
        """)

        action = input("> ")

        if action == "1":
            print("You wait untill two hysteric lady's distract the guards and sneek by the guards.")

        

        elif action == "2":
            print("""Ha. You still got it. You fooled that guards into thinking you are managing the diner.
                    That's a nice confidence booster""")

            
            player['xp'] += 25

        elif action == "3":
            print("""You managed to knock both of them out roadhouse style.
                    However, this made to big of a scene. You cannot continue the mission.""")
            return'failure'



class world(object):

    stages = {
        'entrance': entrance(),
    
        'failure' : failure(),
        
    }

    def __init__ (self, start_stage):
        self.start_stage = start_stage

    def next_stage(self, stage_name):
        next = world.stages.get(stage_name)
        return next

    def opening_stage(self):
        return self.next_stage(self.start_stage)

a_world = world('entrance')
a_game = engine(a_world)
a_game.play()

And I take the 3th option when I am asked for input to see if I get to the failure stage smoothly. But this is the error I get:

Traceback (most recent call last):
File “C:\Users\user\pythonlearn\ex45.py”, line 97, in
a_game.play()
File “C:\Users\user\pythonlearn\fundamentals.py”, line 13, in play
next_stage_name = current_stage.enter()
TypeError: enter() takes 0 positional arguments but 1 was given

It is as if returning the failure key at the end of option 3 is one argument too much. But this didn’t seem to be a problem in exercise 43. What am I missing?

Here is the engine file:

class engine(object):

    def __init__ (self, stage_world):
        self.stage_world = stage_world

    def play(self):
        current_stage = self.stage_world.opening_stage()
        last_stage = self.stage_world.next_stage('carriage')

        print(repr(current_stage))

        while current_stage != last_stage:
            next_stage_name = current_stage.enter()
            current_stage = self.stage_world.next_stage(next_stage_name)


        current_stage.enter()

failure.enter() needs to take self as argument: def enter(self): ....

When you get this working I think you should delete this code and do it again. I think if you do it a second time, but build it gradually and test every change, then you’ll learn quite a lot and make your skills at this stage very solid. You can also probably go get https://docs.pytest.org/en/stable/ and get into automated testing on this. I think if you took this code and wrote automated tests with pytest you would also learn so much.

Hello Again,

Sorry, I took a break for a week.

I am trying to get my head around how I make the playerclass and have the players level cross-over to each stage.

Here is all the code (the engine I import has not changed):

from fundamentals import engine
from sys import exit
import random
from random import randint
from sys import argv


script, name = argv

player = {
        'name': name,
        'lvl' : 1,
        'xp' : 0,
        'lvlnext' : 25,
        'secretcode' : False,
        'stats' : {'charisma' : 1}}

def level(char, stats):
    nchar = 0
    while player['xp'] >= player['lvlnext']:
        player['lvl'] += 1
        player['xp'] = player['xp'] - ['lvlnext']
        player['lvlnext'] = round(player['lvlnext'] * 1.5)
        stats['charisma'] += 1


class stage(object):

    def __init__(self):
        pass

    def enter(self):
        pass


class failure(stage):
    wrong = [
            "Sorry. That just won't cut it.",
            "Nice try..."
            "No. Just no."]

    def enter(self):
        print(failure.wrong[randint(0, len(self.wrong)-1)])
        exit()

class entrance(stage):

    def enter(self):
        print(f"""Hi there {name}. There is not a lot of time so i'll make it quick.
        You are entering the building of a top criminal who is throwing a party at his house.
        It is your job to find and escape with the intel and to do so unnoticed.

        There are 2 Guards at the door. What do you do?
        1. Wait for distraction.
        2. Talk your way in.
        3. Attack them.
        """)

        action = input("> ")

        if action == "1":
            print("You wait untill two hysteric lady's distract the guards and sneek by the guards.")

            return'ballroom'

        elif action == "2":
            print("""
                    Ha. You still got it. You fooled the guards into thinking you are managing the diner.
                    That's a nice confidence booster.""")

            player['xp'] += round(25 * 1.5 * (player['stats']['charisma'] - 1))
            return'ballroom'

        elif action == "3":
            print("""You managed to knock both of them out roadhouse style.
                    However, this made to big of a scene. You cannot continue the mission.""")
            return'failure'

class ballroom(stage):

    def enter(self):
        print("""
                Great. You are in the ballroom. It is pretty crowded in here.
                You need to use the staircase, which is closed off for visitors.
                Find a way to get upstairs without bringing any attention to yourself.

                What do you do?
                1. Just go.
                2. Improvise an excuse to go upstairs.
                3. Find another way up.
                """)

        action = input("> ")

        if action == "1":
            print("Exactly. Sometimes it is best to not overthink things.")
            return'privateroom'

        elif action == "2":
            banter = random.randint(0,3)
            if player['stats']['charisma'] >= 2 and banter >= 1:
                print("You are too slick.")
                player['xp'] += round(25 * 1.5 * (player['stats']['charisma'] - 1))
                return'privateroom'

            elif player['stats']['charisma'] < 2 and banter >= 2:
                print("You are too slick.")
                player['xp'] += round(25 * 1.5 * (player['stats']['charisma'] - 1))
                return'privateroom'

            else:
                print("You get slapped across the face because you were being rude.")
                return'failure'

        elif action == "3":
            print("""
                    You get noticed while snooping around by a drunk partygoer.
                    What do you do?

                    1. Go back.
                    2. Take away suspision.
                     """)

            decision = input("> ")

            if decision == "1":
                player['stats']['charisma'] -= 1
                return'ballroom'

            elif decision == "2":
                delude = random.randint(0,3)

                if player['stats']['charisma'] >= 2 and delude >= 1:
                    print(f"""
                            You are too slick.
                            As you find another way up you find a note with 3 numbers on it.
                            """)
                    player['xp'] += round(25 * 1.5 * (player['stats']['charisma'] - 1))
                    player['secretcode'] == True
                    return'privateroom'

                elif player['stats']['charisma'] < 2 and delude >= 2:
                    print("You are too slick.")
                    player['xp'] += round(25 * 1.5 * (player['stats']['charisma'] - 1))
                    return'privateroom'

                else:
                    print("""
                            Whatever you said, the wanderer didn't like it and
                            is starting to gain the attention from some guards""")
                    return'failure'




class privateroom(stage):

    def enter(self):
        print("""
                You entered the privateroom but there is no sign of any intel.
                On the wall to your right, there is a device that requires a code.
                """)

        print("repr player", repr(player['stats']))

        if player['secretcode'] == True:
            print("You enter the 3 digits that were on the note that you found. Bingo!")
            return'secretdoorway'

        elif player['secretcode'] == False:
            guess = input("> ")
            guesses = 0
            code = f"{random.randint(0,9)}{random.randint(0,9)}{random.randint(0,9)}"

            while guesses != 9 and guess != code:
                guesses += 1
                print(f"Wrong, you've got {10 - guesses} left.")
                guess = input("> ")


            if guess == code:
                print("cracked the code!")
                return'secretdoorway'

            else:
                print("The alarm goes off. You're screwed")
                return'failure'


class secretdoorway(stage):

    def enter(self):
        print("""
        While you walk to the secretdoorway to pick up the intel,
        The daughter of the criminal boss walks in on you.
        Girl: I already suspected something was wrong. You were looking very suspicious
        What do you do?

        1. Find an excuse?
        2. Try to take her out without hurting her?
        3. Charm the girl.
        """)

        action = input("> ")

        if action == 1:
            print("""
                    You give up the intel and convince the girl you are lost/
                    However, by doing so you lost the intel.""")
            return'failure'

        elif action == 2:
            print("""
                    Little did you know that the girl has a black belt in brazilian jiu jitsu.
                    You get slapped around and then captured.""")
            return'failure'

        elif action == 3:
            print("Very bold move.")

            if player['stats']['charisma'] == 1:
                print("""
                        It seems like you've lost your former charm with the lady's.
                        After some failed attempts to impress her you get a drink in your face
                        And the guards are called.""")
                return'failure'

            elif player['stats']['charisma'] == 2:
                print("""
                        By talking to the girl you find out that she does not like her dad at all.
                        You persuade her to let you go for the greater good.
                        """)
                return'carraige'

            elif player['stats']['charisma'] == 3:
                print("""
                        Damn. Your game is on fleek. You seduced the girl into coming with you.
                        """)

class carriage(stage):

    def enter(self):
        print("""
            You made it out with the intel.
            Great job! Surely the boss will promote you now""")

class carriage_and_girl(stage):

    def enter(self):
        print("""
            You made it out with the intel and the lovely lady.
            Great job! That 'll make for a great story""")

class world(object):

    stages = {
        'entrance': entrance(),
        'ballroom': ballroom(),
        'privateroom': privateroom(),
        'secretdoorway': privateroom(),
        'failure' : failure(),
        'carriage': carriage()
    }

    def __init__ (self, start_stage):
        self.start_stage = start_stage

    def next_stage(self, stage_name):
        next = world.stages.get(stage_name)
        return next

    def opening_stage(self):
        return self.next_stage(self.start_stage)

a_world = world('entrance')
a_game = engine(a_world)
a_game.play()

When I run this and I get to the privateroom stage, where I have my debugging line:

class privateroom(stage):

    def enter(self):
        print("""
                You entered the privateroom but there is no sign of any intel.
                On the wall to your right, there is a device that requires a code.
                """)

        print("repr player", repr(player['stats']))

It gives me the following output:

repr player {‘charisma’: 1}

This means that the xp gains are not carried over from scene to scene. How do I go about this? And would the way I go about this, change, if I were to make a class out of the player?

Thanks in advance.

PS: I read the pytest link, but am not sure how to implement it if I were to rebuild the code.

So I can’t see anything that would prevent the player variable from not updating. It’s a script level global and a dict, so if you change things inside they should change. I suggest you do this print out everywhere that you change it, before and after, and I think you’ll see where it’s not being updated. Also, look at how you’re using level(). Maybe you’re passing in the wrong thing for stats and you should just write player['stats']['charisma'] manually.

Thank you. The leveling system works now. One of the last bugs (hopefully) is telling me that it does not recognize stats on line 155.

Does a nested if statement not recognize a global variable?

I tried to find the representation with debugging but it errors everywhere except if I ask in the beginning. Then it says the following:

repr stats {‘charisma’: 1}
<main.entrance object at 0x00000217B880F310>

So it is a global object but assigned to the entrance stage?

This is going over my head, can you explain this to me and how to resolve this?

I’m afraid your description is too vague. Could you post the complete error messages?

No that shouldn’t be a problem.

Definetly:

Traceback (most recent call last):
  File "C:\Users\user\pythonlearn\ex45.py", line 320, in <module>
    a_game.play()
  File "C:\Users\user\pythonlearn\fundamentals.py", line 13, in play
    next_stage_name = current_stage.enter()
  File "C:\Users\user\pythonlearn\ex45.py", line 148, in enter
    print("repr stats",repr(stats))
UnboundLocalError: local variable 'stats' referenced before assignment

Do note that I changed the nested dictionary into two seperate dictionaries because I thought that might have been a problem with my leveling system at first (Which it wasn’t :slight_smile:). So the code is slightly different.

Okay but then you need to show us the new code, too. We can’t find out why stats isn’t defined at that point by making guesses. :wink:

Haha fair enough. I was on my phone.

Here it is:

from fundamentals import engine
from sys import exit
import random
from random import randint
from sys import argv


script, name = argv

player = {
        'name': name,
        'lvl' : 1,
        'xp' : 0,
        'lvlnext' : 25,
        'secretcode' : False,
        'stats' : {'charisma' : 1}}

stats = {
'charisma' : 1
}

def level(char, stats):
    nchar = 0
    while player['xp'] >= player['lvlnext']:
        player['lvl'] += 1
        player['xp'] = player['xp'] - player['lvlnext']
        player['lvlnext'] = round(player['lvlnext'] * 1.5)
        stats['charisma'] += 1


class stage(object):

    def __init__(self):
        pass

    def enter(self):
        pass


class failure(stage):
    wrong = [
            "Sorry. That just won't cut it.",
            "Nice try..."
            "No. Just no."]

    def enter(self):
        print(failure.wrong[randint(0, len(self.wrong)-1)])
        exit()

class entrance(stage):

    def enter(self):
        print(f"""Hi there {name}. There is not a lot of time so i'll make it quick.
        You are entering the building of a top criminal who is throwing a party at his house.
        It is your job to find and escape with the intel and to do so unnoticed.

        There are 2 Guards at the door. What do you do?
        1. Wait for distraction.
        2. Talk your way in.
        3. Attack them.
        """)

        action = input("> ")

        if action == "1":
            print("You wait untill two hysteric lady's distract the guards and sneek by the guards.")

            return'ballroom'

        elif action == "2":
            print("""
                    Ha. You still got it. You fooled the guards into thinking you are managing the diner.
                    That's a nice confidence booster.""")

            player['xp'] += 25
            level(player, stats)

            return'ballroom'

        elif action == "3":
            print("""You managed to knock both of them out roadhouse style.
                    However, this made to big of a scene. You cannot continue the mission.""")
            return'failure'

class ballroom(stage):

    def enter(self):
        print("""
                Great. You are in the ballroom. It is pretty crowded in here.
                You need to use the staircase, which is closed off for visitors.
                Find a way to get upstairs without bringing any attention to yourself.

                What do you do?
                1. Just go.
                2. Improvise an excuse to go upstairs.
                3. Find another way up.
                """)

        action = input("> ")

        if action == "1":
            print("Exactly. Sometimes it is best to not overthink things.")
            return'privateroom'

        elif action == "2":

            banter = random.randint(0,3)

            if stats >= 2 and banter >= 1:
                print("You are too slick.")
                if player['lvl'] >= 2:
                    player['xp'] += round(25 * 1.5 * (stats - 1))
                    level(player,stats)
                elif player['lvl'] == 1:
                    player['xp'] += 25
                    level(player,stats)

                return'privateroom'

            elif stats < 2 and banter >= 2:
                print("You are too slick.")

                if player['lvl'] >= 2:
                    player['xp'] += round(25 * 1.5 * (stats - 1))
                    level(player,stats)

                elif player['lvl'] == 1:
                    player['xp'] += 25
                    level(player,stats)

                return'privateroom'

            else:
                print("You get slapped across the face because you were being rude.")
                return'failure'

        elif action == "3":
            print("""
                    You get noticed while snooping around by a drunk partygoer.
                    What do you do?

                    1. Go back.
                    2. Take away suspision.
                     """)

            decision = input("> ")

            if decision == "1":
                stats -= 1
                return'ballroom'

            elif decision == "2":
                delude = random.randint(0,3)

                if stats >= 2 and delude >= 1:
                    print(f"""
                            You are too slick.
                            As you find another way up you find a note with 3 numbers on it.
                            """)
                    if player['lvl'] >= 2:
                        player['xp'] += round(25 * 1.5 * (stats - 1))
                        level(player,stats)

                    elif player['lvl'] == 1:
                        player['xp'] += 25
                        level(player,stats)

                    player['secretcode'] == True
                    return'privateroom'

                elif player['stats']['charisma'] < 2 and delude >= 2:
                    print("You are too slick.")

                    if player['lvl'] >= 2:
                        player['xp'] += round(25 * 1.5 * (stats - 1))
                        level(player,stats)

                    elif player['lvl'] == 1:
                        player['xp'] += 25
                        level(player,stats)

                    return'privateroom'

                else:
                    print("""
                            Whatever you said, the wanderer didn't like it and
                            is starting to gain the attention from some guards""")
                    return'failure'




class privateroom(stage):

    def enter(self):
        print("""
                You entered the privateroom but there is no sign of any intel.
                On the wall to your right, there is a device that requires a code.
                """)

        print("repr player", repr(stats))
        print("repr xp", repr(player['xp']))

        if player['secretcode'] == True:
            print("You enter the 3 digits that were on the note that you found. Bingo!")
            return'secretdoorway'

        elif player['secretcode'] == False:
            guess = input("> ")
            guesses = 0
            code = f"{random.randint(0,9)}{random.randint(0,9)}{random.randint(0,9)}"

            while guesses != 9 and guess != code:
                guesses += 1
                print(f"Wrong, you've got {10 - guesses} left.")
                guess = input("> ")


            if guess == code:
                print("cracked the code!")
                return'secretdoorway'

            else:
                print("The alarm goes off. You're screwed")
                return'failure'


class secretdoorway(stage):

    def enter(self):
        print("""
        While you walk to the secretdoorway to pick up the intel,
        The daughter of the criminal boss walks in on you.
        Girl: I already suspected something was wrong. You were looking very suspicious
        What do you do?

        1. Find an excuse?
        2. Try to take her out without hurting her?
        3. Charm the girl.
        """)

        action = input("> ")

        if action == 1:
            print("""
                    You give up the intel and convince the girl you are lost/
                    However, by doing so you lost the intel.""")
            return'failure'

        elif action == 2:
            print("""
                    Little did you know that the girl has a black belt in brazilian jiu jitsu.
                    You get slapped around and then captured.""")
            return'failure'

        elif action == 3:
            print("Very bold move.")

            if player['stats']['charisma'] == 1:
                print("""
                        It seems like you've lost your former charm with the lady's.
                        After some failed attempts to impress her you get a drink in your face
                        And the guards are called.""")
                return'failure'

            elif player['stats']['charisma'] == 2:
                print("""
                        By talking to the girl you find out that she does not like her dad at all.
                        You persuade her to let you go for the greater good.
                        """)
                return'carraige'

            elif player['stats']['charisma'] == 3:
                print("""
                        Damn. Your game is on fleek. You seduced the girl into coming with you.
                        """)
                return'carriage_and_girl'

class carriage(stage):

    def enter(self):
        print("""
            You made it out with the intel.
            Great job! Surely the boss will promote you now""")

class carriage_and_girl(stage):

    def enter(self):
        print("""
            You made it out with the intel and the lovely lady.
            Great job! That 'll make for a great story""")

class world(object):

    stages = {
        'entrance': entrance(),
        'ballroom': ballroom(),
        'privateroom': privateroom(),
        'secretdoorway': privateroom(),
        'failure' : failure(),
        'carriage': carriage()
    }

    def __init__ (self, start_stage):
        self.start_stage = start_stage

    def next_stage(self, stage_name):
        next = world.stages.get(stage_name)
        return next

    def opening_stage(self):
        return self.next_stage(self.start_stage)

a_world = world('entrance')
a_game = engine(a_world)
a_game.play()

You’ve got repr(stats) trying to use stats, but if you scroll up through the previous lines do you have anything that’s setting stats? A function variable? See here:

    def enter(self):
        print("""
                You entered the privateroom but there is no sign of any intel.
                On the wall to your right, there is a device that requires a code.
                """)

        print("repr player", repr(stats))
        print("repr xp", repr(player['xp']))

Where’s stats? Also isn’t stats a part of the player dict? Why are you busting it out and where are you doing that. I think you should just use player[‘stats’] all over, and change level() to only take player, and then always access the stats via player[‘stats’] and it’ll probably be much more consistent.

Also, all this error means is you’re attempting to use a variable that python doesn’t know about because you never did:

stats = {}

Or:

def myfunc(stats):

Without those you get the error. You can also get this if you spell it wrong.

Okay what you should be aware of when using script level globals is that the moment you assign to a global within a function without previously declaring it as global Python believes you have a local variable of the same name in that function. And then it complains when you’re using that variable before assigning to it.

GLOBAL = 1

def using_global():
    print(GLOBAL)    # okay, MY_GLOBAL is the script level global

def defining_local():
    GLOBAL = 2       # GLOBAL is a different local variable
    print(GLOBAL)    # the script-level GLOBAL is unchanged

def using_and_assigning_to_global():
    print(GLOBAL)    # problem: Python thinks GLOBAL is a local
    GLOBAL = 2       # variable that you're accessing before defining it

def declaring_as_global():
    global GLOBAL    # solution: tell Python to use the global GLOBAL
    print(GLOBAL)
    GLOBAL = 2       # this changes the script-level GLOBAL

(It’s a funny effect when you write a single word so often that you end up wondering if it’s spelled correctly, or even what it means. :smiley: )

Thank you. That was very helpful.

So if you want to use a global variable in a local environment then you have to use the keyword:

global x

Got it.

Now something strange is happening howwever. I only used the global keyword + stats once in one local environment, and I do not seem to get another error for when stats is used in the other local evironments.

    if action == "1":
            print("Exactly. Sometimes it is best to not overthink things.")
            return'privateroom'

        elif action == "2":

            global stats

I used it like this. The rest of the code is the same. Does this mean that if you use the global keyword in one local variable, that python will understand the variable if you use it in another local environment?

Aside from this. When I now play the game and i go like this:

Decision 2, Decision 3, Decision 2.

To set the player[‘secretcode’] variable to True. I end up in a never ending while loop. This is the output I get over and over:

repr secret code True
repr xp 0
You enter the 3 digits that were on the note that you found. Bingo!

                You entered the privateroom but there is no sign of any intel.
                On the wall to your right, there is a device that requires a code.

repr secret code True
repr xp 0
You enter the 3 digits that were on the note that you found. Bingo!

                You entered the privateroom but there is no sign of any intel.
                On the wall to your right, there is a device that requires a code.

There are only two while loops in my code. The level system and the code which i copied from excecise 43. I suspect the problem to be the latter, but I don’t understand how I am entering the loop because before entering it, it asks for input, so it should stop and wait for my input. But it doesn’t.

Read this, that should answer all your questions concerning globals:

https://www.programiz.com/python-programming/global-local-nonlocal-variables

I’ll take a look at the other problem tonight, don’t have the time now.

Alright. It doesn’t exactly explain why the global variable works in all my other local environments after i mention it once in a local variable. But I guess I can proceed with this knowledge for now.

No stress about the other problem. I cannot thank you enough for the answers you have given so far!

You only have to declare it as global if you are assigning to it in the same function. Otherwise it’ll work as is.

I’m going to suggest something @BenSnaas that I think will help you in the future.

When you run into a problem, resist the urge to seek help until you’ve attempted to solve it on your own for at least 2 days of solid attempts. I feel that if you just put a little more effort into trying to solve these you’d figure it out, so asking for help too early isn’t improving your problem solving abilities. Eventually you’ll get to problems nobody can help you with and if you’ve never had to solve your own problems then you’ll be stuck. If you start now working on trying to solve your problems yourself first then you’ll be better prepared for the future when you’re stuck and nobody can help you.