How to Print the Output of a Function in Python?

Estimated read time 2 min read

To print the output of a function in Python, you can simply call the function and pass its return value as an argument to the print() function. Here’s an example:

def add_numbers(a, b):
    return a + b

result = add_numbers(2, 3)
print(result)

In this example, we have a function called add_numbers that takes two parameters (a and b) and returns their sum. We then call the function with the arguments 2 and 3, and store the return value in a variable called result.

To print the output of the function to the console, we simply pass result as an argument to the print() function.

The output of this code would be:

5

If your function returns multiple values, you can pass them all as separate arguments to the print() function, like this:

def get_name_and_age():
    name = "Alice"
    age = 25
    return name, age

name, age = get_name_and_age()
print("Name:", name)
print("Age:", age)

In this example, we have a function called get_name_and_age that returns two values (name and age). We then call the function and store the return values in separate variables (name and age).

To print both values to the console, we pass them as separate arguments to the print() function, along with some descriptive text.

The output of this code would be:

Name: Alice
Age: 25

Note that when you pass multiple values to the print() function like this, they will be separated by spaces by default. If you want to use a different separator (such as a comma), you can pass the sep parameter to the print() function, like this:

print("Name:", name, "Age:", age, sep=", ")

This would produce the following output:

Name: Alice, Age: 25

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply