Search code examples
pythonfunctionnaming

Whether to make a new variable to be returned in a Python function



Looking for some guidance on whether to assign a new variable in a function before returning the result, as follows:

# create function to take in a number
# which is then taken to the power of another number
# make a new variable called result, and return that variable

def exponential(number, power):
    result = number**power
    return result

Or whether I can simply return the calculation all in one line:

def exponential(number, power):
    return number**power


I'm extremely new to programming, so I'm aware that there's likely mistakes everywhere. Any feedback on how I asked this question, anything else in the code, or any keywords that would have helped me find this in Google are also welcome.


Solution

  • There is no compelling reason to prefer one over the other.

    For nontrivial computations, assigning the value to a variable might make the code more readable as well as easier to debug (because you can print(...) or - better yet - logging.info(...) the value and otherwise examine and manipulate it before returning it) but where exactly to draw the line is entirely up to you and the intended audience.

    If it's completely your own code and you are completely familiar with the logic in this function, you probably don't need a variable. If this is shared code where future maintainers might not be familiar with the functionality, or where bugs have frequently required fixing in the past, correspondingly adjust in the opposite direction.