Parameters
Using the return statement, functions can return values (of any type). When a return statement is executed the function returns the appropriate value and ends its execution. A return statement immediately terminates a function execution and sends the return value.
Here is an example:
#Function
def my_func():
return(10)
a = my_func()
print(a)
def another_func():
return 10
return 20
b = another_func()
print(b)
In the second example above the another_func has 2 return commands. When the first return is executed, the function ends its execution and therefore b equals to 10.
Return Multiple Values
A function can return an arbitrary number of values.
- We can assign the values to a single variable. In this case the variable is assigned to a tuple that contains the appropriate values.
- We can assign the values to an equal number of variables. Each variable is assigned to a value respectively.
Here is an example:
#Example
def my_func():
return 1, 2, 3
tuple_result = my_func()
a, b, c = my_func()
print(tuple_result)
print(a)
print(b)
print(c)
a, b = my_func()
In the example above - assigning an inapropriate number of variables to the function raises en error!
Exercise
- Write a function that returns multiple values
- Assign the results to a single variable and print it
- Assign the results to an appropriate number of variables and print them
#Writ your code here: