Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Return Keyword in Python – A Simple Illustrated Guide
1
Return Keyword in Python – A Simple Illustrated Guide

[Image: return-1-1024x576.jpg]

Python’s
Code:
return
keyword
commands the execution flow to exit a function immediately and return a value to the caller of the function. You can specify an optional return value—or even a return expression—after the
Code:
return
keyword. If you don’t provide a return value, Python will return the default value
Code:
None
to the caller.

Python Return Keyword Video



Return Keyword Followed by Return Value

Here’s an example of the return keyword in combination with a return value:

Code:
def f(): return 4 print(f()) # OUTPUT: 4

Within function
Code:
f()
, Python returns the result 4 to the caller. The
Code:
print()
function then prints the output to the shell.

Return Keyword Followed by Return Expression

Here’s an example of the return keyword in combination with a return expression:

Code:
def f(): return 2+2 print(f()) # OUTPUT: 4

Within function
Code:
f()
, Python evaluates the expression
Code:
2+2=4
and returns the result 4 to the caller. The
Code:
print()
function then prints the output to the shell.

Return Keyword Followed by No Value

Here’s an example of the return keyword without defining a return value:

Code:
def f(): return print(f()) # OUTPUT: None

Within function
Code:
f()
, Python returns the default value
Code:
None
to the caller. The
Code:
print()
function then prints the output to the shell.

Interactive Code Shell

Run the following code in your browser:

https://trinket.io/embed/python/e0d733e100

Exercise: Change the three return values to 42, 42, and ‘Alice’ in the interactive code shell!

The post Return Keyword in Python – A Simple Illustrated Guide first appeared on Finxter.
Reply

Users browsing this thread:
1 Guest(s)


Forum Jump: