Function Return Values

Single Return

  1. # return single value
  2. def square(x):
  3. return x ** 2
  4. result = square(5)
  5. #ans: 25

Multiple Return Values

  1. # return multiple values (tuple)
  2. def divide(a, b):
  3. quotient = a // b
  4. remainder = a % b
  5. return quotient, remainder
  6. q, r = divide(17, 5)
  7. #ans: q=3, r=2

Early Return

  1. # return exits function immediately
  2. def is_even(n):
  3. if n % 2 == 0:
  4. return True
  5. return False
  6. result = is_even(4)
  7. #ans: True

No Return (None)

  1. # function without return
  2. def print_msg(msg):
  3. print(msg)
  4. result = print_msg("Hi")
  5. #ans: Hi (printed)
  6. #ans: result is None

Return in Loop

  1. # return exits function and loop
  2. def find_first_even(numbers):
  3. for num in numbers:
  4. if num % 2 == 0:
  5. return num
  6. result = find_first_even([1, 3, 4, 5])
  7. #ans: 4

Exercises - Part 1

  1. # what is returned?
  2. def func():
  3. x = 5
  4. func()
  5. #ans: None

Exercises - Part 2

  1. # unpacking return values?
  2. def func():
  3. return 1, 2, 3
  4. a, b, c = func()
  5. #ans: a=1, b=2, c=3

Exercises - Part 3

  1. # what happens?
  2. def func():
  3. return 1, 2, 3
  4. x = func()
  5. #ans: x is (1, 2, 3) - a tuple

Exercises - Part 4

  1. # early return?
  2. def func(x):
  3. if x > 5:
  4. return "Big"
  5. return "Small"
  6. func(10)
  7. #ans: "Big"

Exercises - Part 5

  1. # return in else?
  2. def func(x):
  3. if x > 0:
  4. return "Positive"
  5. else:
  6. return "Non-positive"
  7. func(-5)
  8. #ans: "Non-positive"

Exercises - Part 6

  1. # multiple returns?
  2. def func(x):
  3. return x
  4. return x + 1
  5. func(5)
  6. #ans: 5 (second return never reached)

Exercises - Part 7

  1. # return nothing?
  2. def func():
  3. return
  4. func()
  5. #ans: None

Exercises - Part 8

  1. # return in try?
  2. def func():
  3. try:
  4. return 1
  5. finally:
  6. return 2
  7. func()
  8. #ans: 2 (finally overrides)

Exercises - Part 9

  1. # conditional return?
  2. def func(x):
  3. if x:
  4. return x * 2
  5. func(0)
  6. #ans: None (condition False, no return)

Exercises - Part 10

  1. # return expression?
  2. def func(a, b):
  3. return a + b if a > b else a - b
  4. func(5, 3)
  5. #ans: 8

Google tag (gtag.js)