Return none python что это

Функции и их аргументы

В этой статье я планирую рассказать о функциях, именных и анонимных, инструкциях def, return и lambda, обязательных и необязательных аргументах функции, функциях с произвольным числом аргументов.

Именные функции, инструкция def

Определим простейшую функцию:

Инструкция return говорит, что нужно вернуть значение. В нашем случае функция возвращает сумму x и y.

Теперь мы ее можем вызвать:

Функция может быть любой сложности и возвращать любые объекты (списки, кортежи, и даже функции!):

Функция может и не заканчиваться инструкцией return, при этом функция вернет значение None:

Аргументы функции

Функция может принимать произвольное количество аргументов или не принимать их вовсе. Также распространены функции с произвольным числом аргументов, функции с позиционными и именованными аргументами, обязательными и необязательными.

Функция также может принимать переменное количество позиционных аргументов, тогда перед именем ставится *:

Функция может принимать и произвольное число именованных аргументов, тогда перед именем ставится **:

В переменной kwargs у нас хранится словарь, с которым мы, опять-таки, можем делать все, что нам заблагорассудится.

Анонимные функции, инструкция lambda

Анонимные функции могут содержать лишь одно выражение, но и выполняются они быстрее. Анонимные функции создаются с помощью инструкции lambda. Кроме этого, их не обязательно присваивать переменной, как делали мы инструкцией def func():

lambda функции, в отличие от обычной, не требуется инструкция return, а в остальном, ведет себя точно так же:

Источник

Что делает return в Python?

Функция print() записывает, то есть «печатает», строку или число на консоли. Оператор return не выводит значение, которое возвращается при вызове функции. Это, однако, приводит к немедленному завершению или завершению функции, даже если это не последний оператор функции.

Во многих других языках функция, которая не возвращает значение, называется процедурой.

В данном коде значение, возвращаемое (то есть 2) при вызове функции foo(), используется в функции bar(). Эти возвращаемые значения печатаются на консоли только тогда, когда используются операторы печати, как показано ниже.

Пример

Вывод

Мы видим, что когда foo() вызывается из bar(), 2 не записывается в консоль. Вместо этого он используется для вычисления значения, возвращаемого из bar().

Пример оператора return Python

Давайте посмотрим на простой пример сложения двух чисел и возврата суммы вызывающему абоненту.

Мы можем оптимизировать функцию, указав выражение в операторе возврата.

Каждая функция что-то возвращает

Давайте посмотрим, что возвращается, когда функция не имеет оператора возврата.

Что произойдет, если в операторе ничего нет?

Когда оператор return не имеет значения, функция возвращает None.

Может иметь несколько операторов

Функция может возвращать несколько типов значений

В отличие от других языков программирования, функции Python не ограничиваются возвратом значений одного типа. Если вы посмотрите на определение функции, в нем нет никакой информации о том, что она может вернуть.

Давайте посмотрим на пример, в котором функция возвращает несколько типов значений.

Возврат нескольких значений в одном операторе

Мы можем вернуть несколько значений из одного оператора возврата. Эти значения разделяются запятой и возвращаются вызывающей программе в виде кортежа.

С блоком finally

Как работает оператор return внутри блока try-except? Сначала выполняется код блока finally перед возвратом значения вызывающей стороне.

Если в блоке finally есть оператор return, то предыдущий оператор return игнорируется и возвращается значение из блока finally.

Источник

Функция return в Python

Оператор возврата в python используется для возврата значений из функции. Мы можем использовать оператор return только в функции. Его нельзя использовать вне функции Python.

Функция без оператора возврата

Каждая функция в Python что-то возвращает. Если функция не имеет никакого оператора возврата, она возвращает None.

Пример return

Мы можем выполнить некоторую операцию в функции и вернуть результат вызывающей стороне с помощью оператора return.

return с выражением

У нас могут быть выражения также в операторе return. В этом случае выражение оценивается и возвращается результат.

Логическое значение

Давайте посмотрим на пример, в котором мы вернем логическое значение аргумента функции. Мы будем использовать функцию bool(), чтобы получить логическое значение объекта.

Строка

Давайте посмотрим на пример, в котором наша функция вернет строковое представление аргумента. Мы можем использовать функцию str(), чтобы получить строковое представление объекта.

Кортеж

Иногда нам нужно преобразовать несколько переменных в кортеж. Давайте посмотрим, как написать функцию для возврата кортежа из переменного числа аргументов.

Функция, возвращающая другую функцию

Мы также можем вернуть функцию из оператора return. Это похоже на Currying, которое представляет собой метод перевода оценки функции, которая принимает несколько аргументов, в оценку последовательности функций, каждая из которых имеет один аргумент.

Функция, возвращающая внешнюю функцию

Мы также можем вернуть функцию, которая определена вне функции, с помощью оператора return.

Возврат нескольких значений

Если вы хотите вернуть несколько значений из функции, вы можете вернуть объект кортежа, списка или словаря в соответствии с вашими требованиями.

Однако, если вам нужно вернуть огромное количество значений, то использование последовательности – это слишком большая операция по перегрузке ресурсов. В этом случае мы можем использовать yield, чтобы возвращать несколько значений одно за другим.

Резюме

Оператор return в python используется для возврата вывода из функции. Мы узнали, что мы также можем вернуть функцию из другой функции. Кроме того, выражения оцениваются, а затем функция возвращает результат.

Источник

The Python return Statement: Usage and Best Practices

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Using the Python return Statement Effectively

The Python return statement is a key component of functions and methods. You can use the return statement to make your functions send Python objects back to the caller code. These objects are known as the function’s return value. You can use them to perform further computation in your programs.

Using the return statement effectively is a core skill if you want to code custom functions that are Pythonic and robust.

In this tutorial, you’ll learn:

With this knowledge, you’ll be able to write more readable, maintainable, and concise functions in Python. If you’re totally new to Python functions, then you can check out Defining Your Own Python Function before diving into this tutorial.

Free Bonus: 5 Thoughts On Python Mastery, a free course for Python developers that shows you the roadmap and the mindset you’ll need to take your Python skills to the next level.

Getting Started With Python Functions

Most programming languages allow you to assign a name to a code block that performs a concrete computation. These named code blocks can be reused quickly because you can use their name to call them from different places in your code.

Programmers call these named code blocks subroutines, routines, procedures, or functions depending on the language they use. In some languages, there’s a clear difference between a routine or procedure and a function.

Sometimes that difference is so strong that you need to use a specific keyword to define a procedure or subroutine and another keyword to define a function. For example the Visual Basic programming language uses Sub and Function to differentiate between the two.

In general, a procedure is a named code block that performs a set of actions without computing a final value or result. On the other hand, a function is a named code block that performs some actions with the purpose of computing a final value or result, which is then sent back to the caller code. Both procedures and functions can act upon a set of input values, commonly known as arguments.

In Python, these kinds of named code blocks are known as functions because they always send a value back to the caller. The Python documentation defines a function as follows:

A series of statements which returns some value to a caller. It can also be passed zero or more arguments which may be used in the execution of the body. (Source)

Even though the official documentation states that a function “returns some value to the caller,” you’ll soon see that functions can return any Python object to the caller code.

In general, a function takes arguments (if any), performs some operations, and returns a value (or object). The value that a function returns to the caller is generally known as the function’s return value. All Python functions have a return value, either explicit or implicit. You’ll cover the difference between explicit and implicit return values later in this tutorial.

To write a Python function, you need a header that starts with the def keyword, followed by the name of the function, an optional list of comma-separated arguments inside a required pair of parentheses, and a final colon.

Читайте также:  снять квартиру на темернике 2 комнатную

The second component of a function is its code block, or body. Python defines code blocks using indentation instead of brackets, begin and end keywords, and so on. So, to define a function in Python you can use the following syntax:

When you’re coding a Python function, you need to define a header with the def keyword, the name of the function, and a list of arguments in parentheses. Note that the list of arguments is optional, but the parentheses are syntactically required. Then you need to define the function’s code block, which will begin one level of indentation to the right.

In the above example, you use a pass statement. This kind of statement is useful when you need a placeholder statement in your code to make it syntactically correct, but you don’t need to perform any action. pass statements are also known as the null operation because they don’t perform any action.

Note: The full syntax to define functions and their arguments is beyond the scope of this tutorial. For an in-depth resource on this topic, check out Defining Your Own Python Function.

To use a function, you need to call it. A function call consists of the function’s name followed by the function’s arguments in parentheses:

You’ll need to pass arguments to a function call only if the function requires them. The parentheses, on the other hand, are always required in a function call. If you forget them, then you won’t be calling the function but referencing it as a function object.

To make your functions return a value, you need to use the Python return statement. That’s what you’ll cover from this point on.

Understanding the Python return Statement

The Python return statement is a special statement that you can use inside a function or method to send the function’s result back to the caller. A return statement consists of the return keyword followed by an optional return value.

In the next two sections, you’ll cover the basics of how the return statement works and how you can use it to return the function’s result back to the caller code.

Explicit return Statements

An explicit return statement immediately terminates a function execution and sends the return value back to the caller code. To add an explicit return statement to a Python function, you need to use return followed by an optional return value:

If you define a function with an explicit return statement that has an explicit return value, then you can use that return value in any expression:

Since return_42() returns a numeric value, you can use that value in a math expression or any other kind of expression in which the value has a logical or coherent meaning. This is how a caller code can take advantage of a function’s return value.

Note that you can use a return statement only inside a function or method definition. If you use it anywhere else, then you’ll get a SyntaxError :

When you use return outside a function or method, you get a SyntaxError telling you that the statement can’t be used outside a function.

Note: Regular methods, class methods, and static methods are just functions within the context of Python classes. So, all the return statement concepts that you’ll cover apply to them as well.

You can use any Python object as a return value. Since everything in Python is an object, you can return strings, lists, tuples, dictionaries, functions, classes, instances, user-defined objects, and even modules or packages.

For example, say you need to write a function that takes a list of integers and returns a list containing only the even numbers in the original list. Here’s a way of coding this function:

A common practice is to use the result of an expression as a return value in a return statement. To apply this idea, you can rewrite get_even() as follows:

The list comprehension gets evaluated and then the function returns with the resulting list. Note that you can only use expressions in a return statement. Expressions are different from statements like conditionals or loops.

Note: Even though list comprehensions are built using for and (optionally) if keywords, they’re considered expressions rather than statements. That’s why you can use them in a return statement.

For a further example, say you need to calculate the mean of a sample of numeric values. To do that, you need to divide the sum of the values by the number of values. Here’s an example that uses the built-in functions sum() and len() :

Implicit return Statements

Returning vs Printing

If you’re working in an interactive session, then you might think that printing a value and returning a value are equivalent operations. Consider the following two functions and their output:

Both functions seem to do the same thing. In both cases, you see Hello, World printed on your screen. There’s only a subtle visible difference—the single quotation marks in the second example. But take a look at what happens if you return another data type, say an int object:

There’s no visible difference now. In both cases, you can see 42 on your screen. That behavior can be confusing if you’re just starting with Python. You might think that returning and printing a value are equivalent actions.

Now, suppose you’re getting deeper into Python and you’re starting to write your first script. You open a text editor and type the following code:

Try it out by yourself. Save your script to a file called adding.py and run it from your command line as follows:

If you run adding.py from your command line, then you won’t see any result on your screen. That’s because when you run a script, the return values of the functions that you call in the script don’t get printed to the screen like they do in an interactive session.

Returning Multiple Values

You can use a return statement to return multiple values from a function. To do that, you just need to supply several return values separated by commas.

Here’s a possible implementation of your function:

The built-in function divmod() is also an example of a function that returns multiple values. The function takes two (non-complex) numbers as arguments and returns two numbers, the quotient of the two input values and the remainder of the division:

The call to divmod() returns a tuple containing the quotient and remainder that result from dividing the two non-complex numbers provided as arguments. This is an example of a function with multiple return values.

Using the Python return Statement: Best Practices

In this section, you’ll cover several examples that will guide you through a set of good programming practices for effectively using the return statement. These practices will help you to write more readable, maintainable, robust, and efficient functions in Python.

Returning None Explicitly

Some programmers rely on the implicit return statement that Python adds to any function without an explicit one. This can be confusing for developers who come from other programming languages in which a function without a return value is called a procedure.

There are situations in which you can add an explicit return None to your functions. In other situations, however, you can rely on Python’s default behavior:

If your function performs actions but doesn’t have a clear and useful return value, then you can omit returning None because doing that would just be superfluous and confusing. You can also use a bare return without a return value just to make clear your intention of returning from the function.

If your function has multiple return statements and returning None is a valid option, then you should consider the explicit use of return None instead of relying on the Python’s default behavior.

These practices can improve the readability and maintainability of your code by explicitly communicating your intent.

Here’s how this works in practice:

Whether or not to return None explicitly is a personal decision. However, you should consider that in some cases, an explicit return None can avoid maintainability problems. This is especially true for developers who come from other programming languages that don’t behave like Python does.

Читайте также:  Кольца палля что это такое простыми словами

Remembering the Return Value

When writing custom functions, you might accidentally forget to return a value from a function. In this case, Python will return None for you. This can cause subtle bugs that can be difficult for a beginning Python developer to understand and debug.

You can avoid this problem by writing the return statement immediately after the header of the function. Then you can make a second pass to write the function’s body. Here’s a template that you can use when coding your Python functions:

If you get used to starting your functions like this, then chances are that you’ll no longer miss the return statement. With this approach, you can write the body of the function, test it, and rename the variables once you know that the function works.

This practice can increase your productivity and make your functions less error-prone. It can also save you a lot of debugging time.

Avoiding Complex Expressions

As you saw before, it’s a common practice to use the result of an expression as a return value in Python functions. If the expression that you’re using gets too complex, then this practice can lead to functions that are difficult to understand, debug, and maintain.

For example, if you’re doing a complex calculation, then it would be more readable to incrementally calculate the final result using temporary variables with meaningful names.

Consider the following function that calculates the variance of a sample of numeric data:

The expression that you use here is quite complex and difficult to understand. It’s also difficult to debug because you’re performing multiple operations in a single expression. To work around this particular problem, you can take advantage of an incremental development approach that improves the readability of the function.

Take a look at the following alternative implementation of variance() :

In general, you should avoid using complex expressions in your return statement. Instead, you can break your code into multiple steps and use temporary variables for each step. Using temporary variables can make your code easier to debug, understand, and maintain.

Returning Values vs Modifying Globals

Functions that don’t have an explicit return statement with a meaningful return value often preform actions that have side effects. A side effect can be, for example, printing something to the screen, modifying a global variable, updating the state of an object, writing some text to a file, and so on.

Modifying global variables is generally considered a bad programming practice. Just like programs with complex expressions, programs that modify global variables can be difficult to debug, understand, and maintain.

When you modify a global variables, you’re potentially affecting all the functions, classes, objects, and any other parts of your programs that rely on that global variable.

To understand a program that modifies global variables, you need to be aware of all the parts of the program that can see, access, and change those variables. So, good practice recommends writing self-contained functions that take some arguments and return a useful value (or values) without causing any side effect on global variables.

Additionally, functions with an explicit return statement that return a meaningful value are easier to test than functions that modify or update global variables.

The following example show a function that changes a global variable. The function uses the global statement, which is also considered a bad programming practice in Python:

To avoid this kind of behavior, you can write a self-contained increment() that takes arguments and returns a coherent value that depends only on the input arguments:

Note: For a better understanding of how to test your Python code, check out Test-Driven Development With PyTest.

In general, it’s a good practice to avoid functions that modify global variables. If possible, try to write self-contained functions with an explicit return statement that returns a coherent and meaningful value.

Using return With Conditionals

Python functions are not restricted to having a single return statement. If a given function has more than one return statement, then the first one encountered will determine the end of the function’s execution and also its return value.

A common way of writing functions with multiple return statements is to use conditional statements that allow you to provide different return statements depending on the result of evaluating some conditions.

Here’s a possible implementation for this function:

Take a look at the following call to my_abs() using 0 as an argument:

To fix this problem, you can add a third return statement, either in a new elif clause or in a final else clause:

Finally, you can implement my_abs() in a more concise, efficient, and Pythonic way using a single if statement:

Note: There’s a convenient built-in Python function called abs() for computing the absolute value of a number. The function in the above example is intended only to illustrate the point under discussion.

If you’re using if statements to provide several return statements, then you don’t need an else clause to cover the last condition. Just add a return statement at the end of the function’s code block and at the first level of indentation.

Returning True or False

Another common use case for the combination of if and return statements is when you’re coding a predicate or Boolean-valued function. This kind of function returns either True or False according to a given condition.

Sometimes you’ll write predicate functions that involve operators like the following:

Note: Python follows a set of rules to determine the truth value of an object.

For example, the following objects are considered falsy:

Any other object will be considered truthy.

On the other hand, if you try to use conditions that involve Boolean operators like or and and in the way you saw before, then your predicate functions won’t work correctly. That’s because these operators behave differently. They return one of the operands in the condition rather than True or False :

Suppose you want to write a predicate function that takes two values and returns True if both are true and False otherwise. Here’s your first approach to this function:

If you use the first approach, then you can write both_true() as follows:

If, on the other hand, you use a Python conditional expression or ternary operator, then you can write your predicate function as follows:

bool() returns True if a and b are true and False otherwise. It’s up to you what approach to use for solving this problem. However, the second solution seems more readable. What do you think?

Short-Circuiting Loops

This function implements a short-circuit evaluation. For example, suppose that you pass an iterable that contains a million items. If the first item in that iterable happens to be true, then the loop runs only one time rather than a million times. This can save you a lot of processing time when running your code.

It’s important to note that to use a return statement inside a loop, you need to wrap the statement in an if statement. Otherwise, the loop will always break in its first iteration.

Recognizing Dead Code

As soon as a function hits a return statement, it terminates without executing any subsequent code. Consequently, the code that appears after the function’s return statement is commonly called dead code. The Python interpreter totally ignores dead code when running your functions. So, having that kind of code in a function is useless and confusing.

Consider the following function, which adds code after its return statement:

The statement print(«Hello, World») in this example will never execute because that statement appears after the function’s return statement. Identifying dead code and removing it is a good practice that you can apply to write better functions.

It’s worth noting that if you’re using conditional statements to provide multiple return statements, then you can have code after a return statement that won’t be dead as long as it’s outside the if statement:

Returning Multiple Named-Objects

When you’re writing a function that returns multiple values in a single return statement, you can consider using a collections.namedtuple object to make your functions more readable. namedtuple is a collection class that returns a subclass of tuple that has fields or attributes. You can access those attributes using dot notation or an indexing operation.

Читайте также:  жизнь в состоянии жертвы

The initializer of namedtuple takes several arguments. However, to start using namedtuple in your code, you just need to know about the first two:

Using a namedtuple when you need to return multiple values can make your functions significantly more readable without too much effort. Consider the following update of describe() using a namedtuple as a return value:

You can create a Desc object and use it as a return value. To do that, you need to instantiate Desc like you’d do with any Python class. Note that you need to supply a concrete value for each named attribute, just like you did in your return statement.

Here’s how describe() works now:

When you call describe() with a sample of numeric data, you get a namedtuple object containing the mean, median, and mode of the sample. Note that you can access each element of the tuple by using either dot notation or an indexing operation.

Finally, you can also use an iterable unpacking operation to store each value in its own independent variable.

Returning Functions: Closures

In Python, functions are first-class objects. A first-class object is an object that can be assigned to a variable, passed as an argument to a function, or used as a return value in a function. So, you can use a function object as a return value in any return statement.

A function that takes a function as an argument, returns a function as a result, or both is a higher-order function. A closure factory function is a common example of a higher-order function in Python. This kind of function takes some arguments and returns an inner function. The inner function is commonly known as a closure.

A closure carries information about its enclosing execution scope. This provides a way to retain state information between function calls. Closure factory functions are useful when you need to write code based on the concept of lazy or delayed evaluation.

Suppose you need to write a helper function that takes a number and returns the result of multiplying that number by a given factor. You can code that function as follows:

by_factor() takes factor and number as arguments and returns their product. Since factor rarely changes in your application, you find it annoying to supply the same factor in every function call. So, you need a way to retain the state or value of factor between calls to by_factor() and change it only when needed. To retain the current value of factor between calls, you can use a closure.

The following implementation of by_factor() uses a closure to retain the value of factor between calls:

Note that you can freely reuse double and triple because they don’t forget their respective state information.

You can also use a lambda function to create closures. Sometimes the use of a lambda function can make your closure factory more concise. Here’s an alternative implementation of by_factor() using a lambda function:

Taking and Returning Functions: Decorators

Another way of using the return statement for returning function objects is to write decorator functions. A decorator function takes a function object as an argument and returns a function object. The decorator processes the decorated function in some way and returns it or replaces it with another function or callable object.

Decorators are useful when you need to add extra logic to existing functions without modifying them. For example, you can code a decorator to log function calls, validate the arguments to a function, measure the execution time of a given function, and so on.

The following example shows a decorator function that you can use to get an idea of the execution time of a given Python function:

In this case, you use time() to measure the execution time inside the decorator. time() lives in a module called time that provides a set of time-related functions. time() returns the time in seconds since the epoch as a floating-point number. The difference between the time before and after the call to delayed_mean() will give you an idea of the function’s execution time.

Returning User-Defined Objects: The Factory Pattern

The Python return statement can also return user-defined objects. In other words, you can use your own custom objects as a return value in a function. A common use case for this capability is the factory pattern.

The factory pattern defines an interface for creating objects on the fly in response to conditions that you can’t predict when you’re writing a program. You can implement a factory of user-defined objects using a function that takes some initialization arguments and returns different objects according to the concrete input.

Say you’re writing a painting application. You need to create different shapes on the fly in response to your user’s choices. Your program will have squares, circles, rectangles, and so on. To create those shapes on the fly, you first need to create the shape classes that you’re going to use:

Once you have a class for each shape, you can write a function that takes the name of the shape as a string and an optional list of arguments ( *args ) and keyword arguments ( **kwargs ) to create and initialize shapes on the fly:

This function creates an instance of the concrete shape and returns it to the caller. Now you can use shape_factory() to create objects of different shapes in response to the needs of your users:

If you call shape_factory() with the name of the required shape as a string, then you get a new instance of the shape that matches the shape_name you’ve just passed to the factory.

Using return in try … finally Blocks

When you use a return statement inside a try statement with a finally clause, that finally clause is always executed before the return statement. This ensures that the code in the finally clause will always run. Check out the following example:

Using return in Generator Functions

A Python function with a yield statement in its body is a generator function. When you call a generator function, it returns a generator iterator. So, you can say that a generator function is a generator factory.

Here’s a generator that yields 1 and 2 on demand and then returns 3 :

Conclusion

The Python return statement allows you to send any Python object from your custom functions back to the caller code. This statement is a fundamental part of any Python function or method. If you master how to use it, then you’ll be ready to code robust functions.

In this tutorial, you’ve learned how to:

Additionally, you’ve learned some more advanced use cases for the return statement, like how to code a closure factory function and a decorator function. With this knowledge, you’ll be able to write more Pythonic, robust, and maintainable functions in Python.

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Using the Python return Statement Effectively

Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

About Leodanis Pozo Ramos

Leodanis is an industrial engineer who loves Python and software development. He’s a self-taught Python developer with 6+ years of experience. He’s an avid technical writer with a growing number of articles published on Real Python and other sites.

Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:

Master Real-World Python Skills With Unlimited Access to Real Python

Join us and get access to hundreds of tutorials, hands-on video courses, and a community of expert Pythonistas:

Master Real-World Python Skills
With Unlimited Access to Real Python

Join us and get access to hundreds of tutorials, hands-on video courses, and a community of expert Pythonistas:

Real Python Comment Policy: The most useful comments are those written with the goal of learning from or helping out other readers—after reading the whole article and all the earlier comments. Complaints and insults generally won’t make the cut here.

What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.

Источник

Развивающий портал