Basic

Putting calls inside calls

A call is a value once it returns, so a call can sit inside another call or inside an expression. Functions compose the way values do.

What you will see

32

About 1 min of reading

Quick check

Before this new lesson, one small question about the lesson you just finished. Recall it, do not look it up.

Try It

Compose calls together.

1

Define two one-step functions.

def double(n): return n * 2 def add_one(n): return n + 1

Before you run it, say out loud what it will print. Then open the answer.

What it prints
no output yet
2

Nest one inside the other.

print(add_one(double(3)))

Before you run it, say out loud what it will print. Then open the answer.

What it prints
7
3

Add two calls in one expression.

def half(n): return n / 2 print(half(10) + half(4))

Before you run it, say out loud what it will print. Then open the answer.

What it prints
7.0
4

Store one result and reuse it.

def square(n): return n * n base = square(4) print(base + base)

Before you run it, say out loud what it will print. Then open the answer.

What it prints
32

Put it in order

Before you write anything, put these lines back in the right order. Click a line to move it up one step. This support step is easier than writing code from scratch, and it is here to make the last example stick.

Data Flow

A call becomes its returned value, so calls can nest inside other calls and inside larger expressions.
1 inner call runs first
↓
2 its value fills the outer
↓
3 the outer call runs
↓
4 the result prints
Why this works
Composition

Because a call is a value, you can feed one function into another. Small functions that each do one step join into bigger ones.

Readability first

Deeply nested calls run fine but read badly. Naming each step in its own line costs nothing and helps the next reader.

Examples

Call inside a call

def double(n):
    return n * 2

def add_one(n):
    return n + 1

print(add_one(double(3)))

The inner call runs first, giving 6, then add_one turns it into 7. Reading inside out is how nested calls work.

Call inside an expression

def half(n):
    return n / 2

print(half(10) + half(4))

Each call becomes its value, so the line is really 5.0 + 2.0. Calls are just values in disguise.

Store then reuse

def square(n):
    return n * n

base = square(4)
print(base + base)

Storing the result once and using it twice is clearer than calling twice. Same value, one call.

Too deep is hard to read

def a(n):
    return n + 1

print(a(a(a(1))))

This works but is hard to read. Breaking it into named steps is the fix, and it is what real code does.

Words this lesson uses

Each one is defined here on this site. Open the entry for the full definition and the other words it points at.

← Passing different kinds of values
Previous Lesson
Passing different kinds of values
Next Lesson
A function that builds text
A function that builds text →