Chapter 3

What are functions, and when should we use them?

In programming, a function is the named section of the code that encapsulates a specific task and can be used relatively independently from the surrounding code. 

How can data be provided to functions?

Conceptually, code in a function can access data from outside. The best way to pass the data, however, is via arguments—special temporary variables used exactly for that.

What does indentation mean? Is it required?

Yes; in Python, indentation is required and defines the grouping of code. 

What should be covered in the docstring function? How can I read the docstring function?

Ideally, every module, function, and class should have a docstring. In all those cases, a docstring can be shown using the help function, or accessed programmatically via the __doc__ attribute.

When could it be useful to use type annotations?

Type annotations do not affect computation, per se (at least when it comes to standard Python), but could be helpful to identify incorrect usage of the code, or as a way to validate incoming data in different frameworks, such as the FastAPI framework.

How can a function be designed if I don't know the exact number of arguments or their names beforehand?

For that, we can use *args and **kwargs as arguments – both allow us to pass an arbitrary number of values, represented within the function as a list or dictionary, respectively.

What does "anonymous function" mean? When should they be used?

Anonymous functions are different types of functions—smaller in size and shorter in definition, they are great to be used, for example, as a one-time function to be passed as argument (as a key argument for sort function). You shouldn't use anonymous functions for something non-trivial as they are somewhat harder to debug.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.37.161