'unexpected indent error inside a definition for a function

I have this code for the movement of a monster to move randomly between rooms but I get an unexpected intention error for the global value.

def monster(): """moves the monster randomly"""
    global monster_current_room
    if monster_current_room["name"] != current_room:
        print('The monster is currently in', monster_current_room["name"])
        exits = list(monster_current_room["exits"].values())
        if random.randint(1, 4) == 4:
            monster_current_room = rooms[random.choice(exits)]
    elif monster_current_room["name"] == current_room:
        game_over = True

if I unindent the global value it acts as the end of the definition and wants two lines between the definition and global value. when I try to run with the indent the program fails with the error.



Solution 1:[1]

You have misplaced the function comment:

def monster(): 
    """
    moves the monster randomly
    """
    global monster_current_room
    if monster_current_room["name"] != current_room:
        print('The monster is currently in', monster_current_room["name"])
        exits = list(monster_current_room["exits"].values())
        if random.randint(1, 4) == 4:
            monster_current_room = rooms[random.choice(exits)]
    elif monster_current_room["name"] == current_room:
        game_over = True

or if you prefer an inline comment you can do like that

def monster(): # moves the monster randomly
    global monster_current_room
    if monster_current_room["name"] != current_room:
        print('The monster is currently in', monster_current_room["name"])
        exits = list(monster_current_room["exits"].values())
        if random.randint(1, 4) == 4:
            monster_current_room = rooms[random.choice(exits)]
    elif monster_current_room["name"] == current_room:
        game_over = True

when you write a multiline string like

"""
moves the monster randomly
"""

it has to respect the rules of the classic sentences of the python code. So you can't place them whenever you want like comments.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Vittorio