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 trialBrecht Philips
8,863 PointsGlobals variables Dungeon game
Hi I changed the dungeon game sow that the monster alsow moves when the player moves! This part works but i also made the map size dynamical with a global size
Now i bumped on this is i set the map size to 5 everything works but when i play again cause i defeated the game and enter again 5 for map size it increments the global variable to 10
Can somebody help me??
My code is on github if anybody wants to look at it
https://github.com/brechtPhilips/Python/tree/master/MonsterGame
Ps: how do you tag Kenneth Love in this message?
1 Answer
Kenneth Love
Treehouse Guest TeacherCELLS
is mutable and you never reset it, so you're just adding five onto it each time (if you made the size 5 and then 3, I bet it would go to 8 the second run through).
Brecht Philips
8,863 PointsThanks kenneth Now it work's fine what aan stupid thing to look over ?
Kenneth Love
Treehouse Guest TeacherNot stupid at all! You'd be amazed at how many people get tripped up by using mutables as defaults.
For example, try this out:
def add_list(default=[]):
default.append(1)
return default
add_list()
add_list()
add_list()
What do you end up with? Why?
hamsternation
26,616 PointsI read something about functions being evaluated when they're defined and the mutable object is a part of the function and therefore retains its mutable nature within the function throughout calls. (kind of like how even though tuples are immutable, lists within tuples ARE mutable still. Here the function is kind of like the tuple, and the lists are kind of like the default parameter [a list])
So during every call, the default (mutable list) is appended and the default changes with every execution of the function.
Is there a way to reconstruct a function to reset the default parameter back to []? Or do you have to reconstruct the function?
I'm sure there's an answer on the interwebs somewhere, but how would you have a mutable default that resets? What are some practical scenarios that having a mutable default that resets be useful?
I just started python like a week ago, sorry if none of my question make sense. -_-
Alexander Davison
65,469 PointsAlexander Davison
65,469 PointsI can tag Kenneth Love for you :)
Also, Chris Freeman has some sweet answers on Python