Back

Question:

what is def, return, lambda?

How often asked: Constantly

Suggested by: ALittleMoron


Answer:

These are Python-reserved keywords for working with functions.

Def

def is written to declare regular functions. After it and the space is the name of the function.

Return

return is needed to return values from a function. You can return any variable declared in this function itself or any data type declared immediately after return. For example:

def say_hello(name: str) -> str:
    return f'Hello, {name}!'
    
print(say_hello("John")
>>> Hello, John!

Here, the resulting string is declared directly after return.

Lambda

lambda is needed to declare single-line anonymous functions. Most often, anonymous functions are passed to other functions. It is not recommended to assign them to variables, although Python does not prohibit this. Also, in such functions there is no return, because they immediately return a value from their body. say_hello in the example above can be rewritten as follows:

def hello_handler(name, func) -> None:
    hello_message = func(name)
    print(hello_message)

hello_handler("John", lambda name: f"Hello, {name}!")
>>> Hello, John!

Interview answer explanation:

This question is an introduction to the topic of functions. The interviewer asks a question in order to understand whether the candidate knows the very basics of language syntax. If the candidate cannot answer this question, further questions on the topic do not make sense.

Further, the interviewer often begins to delve into topics. Perhaps he will ask questions with a trick to make sure that the candidate understands this topic accurately. These questions include what-if-no-return-is-in-function