Defining functions
A function is a named, reusable machine: inputs go in (parameters) and a result comes out (return).
def area(width, height): return width * height
print(area(3, 4)) # 12
def only defines the machine. Nothing runs until you call it with parentheses. Parameters such as width receive the arguments supplied in the call. return ends the call and hands back its value. pass is a placeholder that does nothing; replace it with the function's real work.
print(area(3, 4)): an area() box appears holding width 3 and height 4, shows the return value 12, then disappears.See it run
def area(width, height): result = width * height return result big = area(3, 4) print(big)
Watch for a second box to appear: every function call gets its own.
Practice defining functions
Exercise 1
- Define
square(n)that returnsn * n. - Define
greet(name)that returns"Hi, NAME!"(e.g.greet("Bo")gives"Hi, Bo!").
Exercise 2
A picture framer needs perimeter(width, height) to return the distance around a rectangle and label(name, cm) to return text such as Oak: 18 cm. Zero dimensions are allowed. Do not print instead of returning.
Exercise 3
Split a cafe bill with two reusable functions. with_tip(amount, percent) returns amount plus that percentage tip. share(amount, people) returns each person's equal share. Compose them into each for a bill of 80, a 10% tip, and 4 people. Assume people is positive.
Exercise 4
Predict, then verify. Read this program before running it:
def double(x): result = x * 2 return result
def add_then_double(a, b): total = a + b return double(total)
answer = add_then_double(3, 4)
While double is running, what is x in its frame, and how many boxes does the Visualizer show (count Program variables too)? Guess, then run it, press Step through your code, and press Next until a double() box appears. Set x_value and boxes.
The explanation and tasks are public. Running this lesson requires an account with course access.
Practice
Loading Python…Visualizer Watch your code run line by line
Run your code, then choose Play to follow its execution.