Return

Return

return sends a value back to the caller. The call itself then stands for that value:

def double(n):
    return n * 2

result = double(4)
print(result)

Output:

8

double(4) ran the body, hit return n * 2, and handed back 8. The caller stored it in the result variable.

A returned value can be used anywhere a value can, stored, passed to another call, or used in arithmetic:

print(double(10) + 1)

Output:

21

return also ends the function immediately. Lines after a return that runs are never reached.

Exercise

  1. Define a function named triple with one parameter, n. It returns n multiplied by 3.
  2. Keep the print(triple(4)) line at the bottom of the starter code. The output should be 12.

Run your code to see the output, then press Submit.

Tests

import unittest


class TestTriple(unittest.TestCase):
    def test_triple_of_4_is_12(self):
        self.assertEqual(triple(4), 12)

    def test_triple_of_0_is_0(self):
        self.assertEqual(triple(0), 0)

    def test_triple_of_negative_2_is_negative_6(self):
        self.assertEqual(triple(-2), -6)
def triple(n):
    return n * 3


print(triple(4))
Solution hidden. Give it a real try first.

Sign in to join the discussion.

No comments yet. Be the first to ask a question.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.