C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Note: Clarity of code is important. Sometimes, having more symmetry in a method (where "return" is used for all paths) is a clearer design.
Python program that returns no value
def printname(first, middle, last):
# Validate middle initial length.
if len(middle) != 1:
print("Middle initial too long")
return
# Display.
print(first + " " + middle + ". " + last)
# Call method.
printname("Jake", "R", "Chambers")
Output
Jake R. Chambers
Python program that returns None
def example(x):
# Return a value only if argument is greater than zero.
if x > 0:
return x
print(example(0))
print(example(1))
Output
None
1
Python program that returns multiple values
def get_names_uppercase(a, b):
# This method returns 2 strings in a tuple.
return (a.upper(), b.upper());
# Get tuple from the method.
result = get_names_uppercase("vidiadhar", "naipaul")
print(result)
# Extract first and second return values.
first = result[0]
second = result[1]
print(first)
print(second)
Output
('VIDIADHAR', 'NAIPAUL')
VIDIADHAR
NAIPAUL