Dedicated variable vs function


What’s the difference, in terms of uses case, between these two ways of using a method:

a) For making the hero say something, I create a dedicated variable distance1:

enemy1 = "Smasher"
distance1 = hero.distanceTo(enemy1)

This is the method used in the level’s sample code.

b) I don’t create an extra variable but just use the function for determining its value instead:

enemy2 = "Gort"

Both ways accomplish the task, but which is preferable (under what circumstances), and why?

Btw this is the task from range finder level


They have the same effect but the 2nd option saves one line of code, but if you are going to use hero.distanceTo(enemy2) often, then it’s best to define it.


I wonder if 1 line of code is all that it saves. Is the variable only about code reuse?
won’t the variable also occupy an amount of memory while it lives (that space reamining free if the function is used instead)?


wdym “an amount of memory”


I mean, I have this notion that the footprint of the program will be bigger if a variable is used, because Python reserves a space in memory for it. Of course I have no idea how big that space will be - probably depend on its type and value…?


The memory space is insignificant. What is significant is the speed of the language. Python is considered a slow language for a couple of reasons. Simplicity and streamlining it is never a bad idea.

To learn more: