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


George S-T
George S-T
6,624 Points

How to properly use return in Python?

Hi. Im trying to create my own dungeon game before getting on to the video.

Here is a snippet of my code:

def set_positions():
  monster = random.choice(cells)
  door = random.choice(cells)
  player = random.choice(cells)

  if player == monster:
  elif monster == door:
  elif door == player:
    print('coords set')
    return player, door, monster

def move_right():
  #I would like to use the values of player, door and monster (from set_positions()) in this function
  #current_position = player ?

My question is: how do I use the player, door and monster position from my set_positions() function in the move_right() function?


1 Answer

Chris Freeman
Chris Freeman
Treehouse Moderator 68,423 Points

I don't think you want to use the values returned by set_positions() directly with move_right(). This would mean calling set_positions() each time move_right() was called which would change all of the positions of player, door, and monster.

What you likely want is to capture the values from set_positions() into variables from some main function or loop, then operate on these captured values. Here is one way to structure your code:

def set_positions():
    # ... snip
    # return positions as list
    return [player, door, monster]

def move_right(positions):
    #I would like to use the values of player, door and monster (from set_positions()) in this function
    # access player position from first item in positions list
    current_player_position = positions[0]
    positions[0] = (current_player[0] + 1, current_player[1])

# Main loop
while playing_game:
    # get positions as list
    positions = set_positions()

    # ...
    if move == "RIGHT":
        # pass positions list to move_right

Testing this in the Python REPL:

>>> positions = [(0, 0), (1, 3), (4, 5)]
>>> def move_player_right(positions):
...    current_player = positions[0]
...    positions[0] = (current_player[0] + 1, current_player[1])
>>> positions
[(0, 0), (1, 3), (4, 5)]
>>> move_player_right(positions)
>>> positions
[(1, 0), (1, 3), (4, 5)]

Post back if you are looking for something different. Good Luck!

George S-T
George S-T
6,624 Points

Perfect, thanks! Finished the game now :)