Returning Values, Flow of Execution and Scope

50 min read Functions

This is a free course. Log in to run the code exercises and track your progress.

Returning Values, Flow of Execution and Scope

A function sends a result back with return. It can return several values at once; they travel as a tuple. A function without return returns None.

def stats(nums):
    return min(nums), max(nums), sum(nums) / len(nums)

lo, hi, avg = stats([4, 9, 2])   # 2 9 5.0

Flow of execution: Python runs a program top to bottom. A def only creates the function; its body runs when the function is called. At a call, control jumps into the function, runs it, and comes back to the statement that called it.

Scope is where a name can be used. A variable assigned inside a function is local to it and vanishes when the function returns. A variable created outside every function is global; a function can read it, but to assign to it the function must declare it with global.

count = 0             # global

def visit():
    global count      # without this, count += 1 raises UnboundLocalError
    count += 1

def show():
    count = 99        # a new local variable; the global is untouched
    return count

visit(); visit()
print(show(), count)  # 99 2
Python exercise

Write min_max_mean(nums) that returns the minimum, the maximum and the mean of a list as three values. The program prints them separated by spaces, with the mean to two decimals.

def min_max_mean(nums):
    return 0, 0, 0.0  # return the three values


nums = list(map(int, input().split()))
lo, hi, avg = min_max_mean(nums)
print(lo, hi, f"{avg:.2f}")

Log in to edit and run this code.