Quantcast
Channel: Tech Tutorials
Viewing all articles
Browse latest Browse all 938

Python Functions : Returning Multiple Values

$
0
0

In Python a function can return multiple values, that is one of the difference you will find in a Python function and function (or method) in a language like C or Java.

Returning multiple values in Python

If you want to return multiple values from a function you can use return statement along with comma separated values. For example


return x, y, z

When multiple values are returned like this, function in Python returns them as a tuple. When assigning these returned values to a variable you can assign them to variables in sequential order or in a tuple. Let’s try to clarify it with examples.

Python function returning multiple values example

In the example there is a function that adds and multiplies the passed numbers and returns the two results.


def return_mul(a, b):
add = a + b
mul = a * b
# returning two values
return add, mul


# calling function
a, m = return_mul(5, 6)
print('Sum is', a)
print('Product is', m)

Output


Sum is 11
Product is 30

As you can see in the function two values are returned which are assigned to two variables in sequential order


a, m = return_mul(5, 6)

value of add to a and value of mul to m.

You can also assign the returned values into a tuple.


def return_mul(a, b):
add = a + b
mul = a * b
# returning two values
return add, mul


# calling function
t = return_mul(5, 6)
# getting values from tuple
print('Sum is', t[0])
print('Product is', t[1])

Output


Sum is 11
Product is 30

That's all for this topic Python Functions : Returning Multiple Values. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Global Keyword in Python With Examples
  2. Namespace And Variable Scope in Python
  3. Local, Nonlocal And Global Variables in Python
  4. Passing Object of The Class as Parameter in Python
  5. pass Statement in Python

You may also like-

  1. Multiple Inheritance in Python
  2. Python String split() Method
  3. User-defined Exceptions in Python
  4. Python Program to Find Factorial of a Number
  5. Java BufferedWriter Class With Examples
  6. How to Reverse a Doubly Linked List in Java
  7. How to Create Immutable Class in Java
  8. Spring Boot StandAlone (Console Based) Application Example

Viewing all articles
Browse latest Browse all 938

Trending Articles