8-3. Void Functions and Value Returning Functions

In Python, functions can be categorized into two main types: void functions and value-returning functions. Void functions are designed to perform specific tasks without returning any value to the caller. They typically execute a series of statements, such as printing output, modifying global variables, or writing to files, and are ideal for tasks where the outcome is not needed beyond the function's scope.

On the other hand, value-returning functions perform a task and then return a result using the return statement. These functions are essential for operations where the result is needed for further computations or decision-making processes. By returning a value, they enable the calling code to capture and use the result, making them versatile for calculations, data processing, and other operations. Understanding the distinction between these two types of functions is crucial for writing effective and efficient Python code.

Void Functions

Void functions are functions that perform an action but do not return any value. They might print something, modify a global variable, or write to a file, but they do not use the return keyword.

 

Example 1:

Let's write a simple void function that prints a greeting:

 

Explanation:

  • The function greet takes one parameter, name.
  • Inside the function, it prints a greeting message.
  • When you call greet("Alice"), it prints "Hello, Alice!".

This function does something (prints a message) but does not return any value.

Value-Returning Functions

Value-returning functions are functions that perform an action and then return a value using the return keyword. These functions can be used to compute a result and give it back to the caller.

 

Example 2:

Let's write a simple value-returning function that adds two numbers and returns the result:

 

Explanation:

  • The function add takes two parameters, a and b.
  • Inside the function, it returns the sum of a and b.
  • When you call add(3, 5), it returns the value 8, which is then stored in the variable result.
  • Finally, we print the value of result, which is 8.

This function does something (adds two numbers) and returns the result to the caller.