Dedicated variable vs function


#1

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)
hero.say(distance1)

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

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

enemy2 = "Gort"
hero.say(hero.distanceTo(enemy2))

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

Btw this is the task from range finder level


#2

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.


#3

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)?


#4

wdym “an amount of memory”


#5

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…?


#6

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:

https://www.quora.com/Why-is-Python-slower-than-other-languages