Relabeling Functions in Python

What is the output of this code snippet?


def func(x):
    return x+1

f = func
print(f(2) + func(2))

Redundant code indicates poor programming style. An excellent way to avoid redundant code is given by functions.
Functions generalize a certain behavior and encapsulate a sequence of program instructions. The ideal function solves a single semantic high-level goal. For instance, you can encapsulate a complex task, such as searching the web, into a function. In this way, the complex task becomes a simple one-liner: calling the function. Functions enable others to reuse your code and allows you to reuse other people’s code. You are standing on the shoulders of giants.

You can define a function with the keyword def, followed by a name and the arguments of the function. The Python interpreter maintains a symbol table that stores all function definitions. In this way, the interpreter can relate each occurrence of the function name to the defined functionality.

It is possible to rename your function in the symbol table. This is as simple as assigning the function name to a new variable (e.g. f). Upon the function call, the Python interpreter will find the renamed function in the table and execute it. This makes your life easier when working with other people’s code which you are not allowed to change.


Are you a master coder?
Test your skills now!


Related Video




Leave a Comment

Your email address will not be published. Required fields are marked *