Void functions are created and used just like value-returning functions except they do not return a value after the function executes. In lieu of a data type, void functions use the keyword "void." A void function performs a task, and then control returns back to the caller--but, it does Show
return a value. You may or may not use the return statement, as there is no return value. Even without the return statement, control will return to the caller automatically at the end of the function. A good utilization of a void function would be to print a header/footer to a screen or file. Remember: there are two kinds of subprograms that the C++ language utilizes: value-returning functions and void functions. Both value-returning functions and void functions receive values through their parameter lists. A value-returning function can only return onevalue to the calling environment. The caller invokes (calls) a value-returning function by using its name and argument list in an expression (i.e., 1. assignment, 2. output, or as an 3. argument in another function call): //value-returning function call (assignment): y = 2.0 * sqrt(x);In contrast, a void function (method or procedure, in other languages) does not return a function value. Nor is it called from within an expression. Instead, the function call appears as a complete, stand-alone statement. One example is the get function associated with the istream and ifstream classes: //void function call: cin.get();Another example: //void function call: printName(name);Bjarne Stroustrup's C++ Glossary Note: Although the C++ language allows value-returning functions to have both value parameters and reference parameters, it is not recommended. By definition, a value-returning function returns a single value; this value is returned via the return statement. Use void functions with reference parameters to return (modify) more than one value. Stub functions may be used when testing programs. A stub function is a stripped-down, skeletal structure of the actual function. It does not implement the full details of the algorithm or function requirements. It does contain the parameter lists. Essentially, a stub is a dummy function with a limited body, usually just output statements that acknowledge the function was reached, and a return value (if any) of the correct type. Usually, the stub function's name and parameter list is the same as the function that will actually be called by the program being tested. Several functions with the same nameis called function overloading. Generally, function overloading is used when different data types will be used with the same function. As an illustration, one function may accept integer values, while another can receive char or float data. Of course, you could implement the same functionality using a different function name whose parameters would receive the various data types--or, you can employ function overloading. When overloading a function, dissimilar signatures (i.e., different "TON": type, order, or number) must be used for each overloaded version. A function signature consists of a list of data types of its parameters, as well as their order, and number (i.e., the number of parameters). Lastly, a function differing only by return type, OR different parameter namesis illegal (though, it is legalto use a different return type with a different parameter list--that is, different "TON." See below): 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 Using the 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. Getting Started With Python FunctionsMost 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 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:
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 The second component of a function is its code block, or body. Python defines code blocks using
indentation instead of brackets,
When you’re coding a Python function, you need to define a header with the In the above example, you use a 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 Understanding the Python return StatementThe Python
The return value of
a Python function can be any Python object. Everything in Python is an object. So, your functions can return numeric values ( You can omit the return value of a function
and use a bare In the next two sections, you’ll cover the basics of how the Explicit return StatementsAn explicit >>>
When you define If you define a function with an explicit >>>
Since Note that you can use a
>>>
When you use 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 >>>
The list comprehension gets evaluated and then the function returns with the resulting list. Note that you can only use expressions in a 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
>>>
In Implicit return StatementsA Python function will always have a return value. There is no notion of procedure or routine in Python. So, if you don’t explicitly use a return
value in a Say you’re writing a function that adds >>>
If you don’t supply an explicit An example of a function that returns >>>
The call to Regardless of how long and complex your functions are, any function without an explicit Returning vs PrintingIf 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 >>>
There’s no visible difference now. In both cases, you can see 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 If you run If you want that your script to show the result of calling
Now, when you run So, if you’re working in an interactive session, then Python will show the result of any function call directly to your screen. But if you’re writing a script and you want to see a function’s
return value, then you need to explicitly use Returning Multiple ValuesYou can use a For example, suppose you need to write a function that takes a
sample of numeric data and returns a summary of statistical measures. To code that function, you can use the Python standard module Here’s a possible implementation of your function:
In Once you’ve coded >>>
Here, you unpack the three return values of The built-in function
>>>
The call to Using the Python return Statement: Best PracticesSo far, you’ve covered the basics of how the Python In this section, you’ll cover several examples that will guide you through a set of good programming practices for effectively using the Returning None ExplicitlySome programmers rely on the implicit There are situations in which you can add an explicit
These practices can improve the readability and maintainability of your code by explicitly communicating your intent. When it comes to returning
Here’s how this works in practice: >>>
Whether or not to return Remembering the Return ValueWhen writing custom functions, you might accidentally forget to return a value from a function. In this case, Python will return You can avoid this problem by writing the
If you get used to starting your functions like this, then
chances are that you’ll no longer miss the 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 ExpressionsAs 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 >>>
In this second implementation of Temporary variables like In general, you should avoid using complex expressions in your Returning Values vs Modifying GlobalsFunctions that don’t have an explicit 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 The following example show a function that changes a global variable. The function uses the >>>
In this example, you first create a global variable, The result of calling To avoid this kind of behavior, you can write a self-contained >>>
Now the result of calling Additionally, when you need to update 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 Using return With ConditionalsPython functions are not restricted to having a single A common way of writing functions with multiple Suppose you need to code a function that takes a number and returns its absolute value. If the number is greater than Here’s a possible implementation for this function: >>>
Take a look at the following call to >>>
When you call To fix this problem, you can add a third
>>>
Now, Finally, you can implement >>>
In this case, your function hits the first If you’re using Returning True or FalseAnother common use case for the combination of For example, say you need to write a function that takes two integers, >>>
Sometimes you’ll write predicate functions that involve operators like the following:
In these cases, you can directly use a Boolean expression in your >>>
If On the other hand, if you try to use conditions that involve Boolean operators like >>>
In general, Suppose you want to write a predicate function that takes two values and returns >>>
Since
If you use the first
approach, then you can write >>>
The If, on the other hand, you use a Python conditional expression or ternary operator, then you can write your predicate function as follows: >>>
Here, you use a conditional expression to provide a return value for Finally, if you use >>>
Short-Circuiting LoopsA To emulate >>>
If any 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 Recognizing Dead CodeAs soon as a function hits a Consider the following function, which adds code after its >>>
The statement It’s worth noting that if you’re using conditional statements to provide multiple >>>
Even though the call to Returning Multiple Named-ObjectsWhen you’re writing a function that returns
multiple values in a single The initializer of
Using a
Inside You can create a Here’s how >>>
When you call Finally, you can also use an iterable unpacking operation to store each value in its own independent variable. Returning Functions: ClosuresIn 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 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:
The following implementation of >>>
Inside Note that you can freely reuse You can also use a
>>>
This implementation works just like the original example. In this case, the use of a Taking and Returning Functions: DecoratorsAnother way of using the 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: >>>
The syntax Python runs decorator functions as soon as you
import or run a module or a script. So, when you call In this case, you use
Other common examples of decorators in Python are Returning User-Defined Objects: The Factory PatternThe Python 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 (
This function creates an instance of
the concrete shape and returns it to the caller. Now you can use >>>
If you call Using return in try … finally BlocksWhen you use a >>>
When you call Using return in Generator FunctionsA Python function with a You can use a Here’s a generator that yields >>>
The first two calls to ConclusionThe Python In this tutorial, you’ve learned how to:
Additionally, you’ve learned some more advanced
use cases for the 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 What is the return type of the readLine method call?1. The readLine() method of Console class in Java is used to read a single line of text from the console. Parameters: This method does not accept any parameter. Return value: This method returns the string containing the line that is read from the console.
Under what circumstances can you return a reference from a method?Under what circumstances can you return a reference from a method? Only when it is safe to return, such as returning a reference from a method if the reference was passed into the method.
What is the purpose of a return statement in a function quizlet?What is the purpose of the Return statement in a function? The Return statement specifies the value that the function returns to the part of the program that called the function. When the Return statement is executed, it causes the function to terminate and return the specified value.
What type of statement can be used to make a single alternative decision?Chapter 03 Key Terms Review. |