2025, Nov 30 07:00
Why Your Python Variable Doesn't Change: Assign the Function Return (Text Adventure Example)
Learn why calling a Python function won't update your variable unless you assign its return. See a text adventure movement bug and the fix to update state.
When you build simple text adventures or command parsers, a common pitfall is expecting a function call to update a variable by itself. If the function returns a value but you don’t capture that value, nothing changes outside the function. Ни magic, ни hidden side effects — just an unassigned return.
The setup: moving between areas
Below is a minimal example that tries to move a player between connected areas. The logic is sound: parse a command like “go north”, validate it against the map, compute a new location, and return it. Yet the displayed location never changes.
zones = {
'geysers': {'north': 'caves', 'south': 'fields', 'east': 'swamps', 'west': 'treetops', 'item': 'start'},
'caves': {'south': 'geysers', 'east': 'cliffs', 'item': 'sword'},
'fields': {'north': 'geysers', 'east': 'temple', 'item': 'bandages'},
'swamps': {'north': 'pond', 'west': 'geysers', 'item': 'tranquilizer'},
'treetops': {'east': 'geysers', 'item': 'blowtorch'},
'cliffs': {'west': 'caves', 'item': 'shield'},
'pond': {'south': 'swamps', 'item': 'javelin'},
'temple': {'west': 'fields', 'item': 'villain'}
}
active_spot = 'geysers'
def bad_shift():
print('Move not valid. Try again.')
user_cmd = input('Enter your move:\n>').lower().split()
def step_actor(place, cmd):
fresh_place = place
if cmd[0] == 'go':
if cmd[1] in zones[place] and cmd[1] != 'item':
fresh_place = zones[place][cmd[1]]
else:
bad_shift()
else:
bad_shift()
return fresh_place
step_actor(active_spot, user_cmd)
print(active_spot)
What’s actually going on
The function computes a new location and returns it via return. But the call result is ignored. As a result, the outer variable that holds the current location remains unchanged, and print(active_spot) shows the original value.
You’re calling move_player() but you’re not saving the returned variable anywhere. Presumably you meant to do current_location = move_player(...)
The fix
Assign the returned value back to the variable that tracks the current location. That’s the entire issue.
active_spot = step_actor(active_spot, user_cmd)
print(active_spot)
If you need to keep the previous location for any reason, store it separately before overwriting.
Why this matters
When a function returns a value, nothing outside changes unless you explicitly capture that return. Forgetting to assign the result leads to confusing no-op calls that look correct at a glance, especially in game loops and command handlers.
Takeaway
If a function returns the updated state, bind it to a variable. Either update the original variable or keep both the old and new values depending on what you need. In this case, set active_spot = step_actor(active_spot, user_cmd) so the location on screen reflects the move you just computed.