Function can return results to the rest of the script, where other function can take them for further operations.
This simple function will run, but because no further operations will be done, nothing will be printed in shell.
def external(num_1):
add = num_1 + num_1
return add
external(10)
But now, results are placed into variable "container" so we can print it on dedicated line, with a little bit of custom report:
def external(num_1):
add = num_1 + num_1
return add
container = external(10)
print("Result: ", container)
Result:
Result: 20
>>>
Or, you can use function with different arguments on individual lines:
def external(num_1):
add = num_1 + num_1
return add
print("Result: ", external(20))
print("Result: ", external(40))
print("Result: ", external(60))
Result:
Result: 40
Result: 80
Result: 120
>>>
It's awesome that in Python we can have multiple returns, in this case, "add", and "mul".
Multiple returns are packet into tuple:
def external(num_1):
add = num_1 + num_1
mul = num_1 * num_1
return add, mul
print("Result: ", external(20))
print("Return Type: ", type(external(20)))
Result:
Result: (40, 400)
Return Type: <class 'tuple'>
>>>
And now we are using individual parts of tuple:
def external(num_1):
add = num_1 + num_1
mul = num_1 * num_1
return add, mul
x, y = external(20)
print("Result of Add: ", x)
print("Result of Mul: ", y)
Result:
Result of Add: 40
Result of Mul: 400
>>>
Sometimes we care only about one index from tuple:
def external(num_1):
add = num_1 + num_1
mul = num_1 * num_1
return add, mul
print("Result of Add: ", external(10)[0])
print("Result of Mul: ", external(10)[1])
Result:
Result of Add: 20
Result of Mul: 100
>>>
Ok, in next tutorial we will learn about Iterations.
No comments:
Post a Comment