MCS-201 · Unit 11

Functions and File Handling in Python

Section 4 of 8

Block 3 · Unit 11Functions and File Handling in Python7 min · Section 4 of 8

11.4Returning Values

Covers IGNOU MCS-201 §11.5

Parameters bring values into a function; return sends a result out. A function that returns its result, rather than printing it, can be reused in calculations, conditions and other function calls.

The return statement

Syntax
def function_name(parameters):
    ...
    return expression
  • return expression ends the function immediately and gives the value of the expression to the caller.
  • Statements after an executed return do not run.
  • A function without return, or with a bare return, returns None.
  • return a, b returns one tuple (a, b), which the caller can unpack: s, avg = stats(...).

Key takeaways

  • return ends the function and passes back a value.
  • return a, b returns one tuple; unpack it with x, y = f().
  • Any number of return statements are allowed; the first reached wins.
  • Without return, a function returns None.

Practice questions

Answer on paper first, then check. The explanation matters more than the letter you chose.

Question 1 · multiple choice

What does a function return if it has no return statement?

Show answer

Answer: C. None

Every function returns something; the default is None.

Question 2 · multiple choice

What is the type of the value returned by def f(): return 1, 2?

Show answer

Answer: B. tuple

The comma makes a tuple (1, 2); it is one object containing two values.

Question 3 · multiple choice

What does this program print?

Python · quiz_return.py
def f():
    for i in range(1, 10):
        if i == 4:
            return i * 10
    return -1

print(f())
Show answer

Answer: D. 40

When i reaches 4, return i * 10 ends the function at once with 40; the final return -1 is never reached.

Question 4 · multiple choice

What does this program print?

Python · quiz_none.py
def greet(name):
    print("Hi", name)

result = greet("Nav")
print(result)
Show answer

Answer: B. Hi Nav, then None

The call prints “Hi Nav” and returns None, which is then printed.

Question 5 · multiple choice

Which statement is true?

Show answer

Answer: D. A function may contain several return statements, but only one runs per call

The first return reached ends the call, so later ones in that call are skipped.

Question 6 · short answer

Write a function min_max(values) that returns both the smallest and largest value of a list, and show how to call it.

Show worked answer

def min_max(values): return min(values), max(values). Call: low, high = min_max([7, 2, 9, 4]), which sets low = 2 and high = 9. The function returns one tuple (2, 9), which the assignment unpacks into the two names.

↑ ↓ move↵ openTab switch type