How to Create a Python Function Without a Return Value?

Estimated read time 2 min read

To create a Python function that doesn’t return a value, you can define the function using the def keyword and any necessary parameters, but omit the return statement or use return None. Here’s an example:

def print_greeting(name):
    print("Hello, " + name + "!")

In this example, we define a function called print_greeting that takes one parameter name.

The function body consists of a single statement that uses the print function to display a personalized greeting message to the console, based on the value of the name parameter.

Since this function doesn’t need to return a value, we can omit the return statement. By default, if no return statement is specified, the function will return None.

To call the function, you can pass a string value as the name argument, like this:

print_greeting("Alice")  # Output: "Hello, Alice!"

In this example, we call the print_greeting function with the argument "Alice". The function prints the message “Hello, Alice!” to the console, but doesn’t return a value.

Note that functions that don’t return a value are often used for tasks that involve performing side effects, such as displaying output to the console or modifying the state of global variables or objects.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply