MathubLearn / Practice / Excel
CSCI 127 Joy and Beauty of Data · Unit 1: Data types · on Exam 1

1.3 Functions

Study notes for Functions in CSCI 127 Joy and Beauty of Data at Montana State University: the big ideas, code you should know, a worked example, common mistakes and an exam tip. The same topic has endless practice questions and flashcards in Mathub.

Big ideas

Code you should know

Return versus print
def area(w, h):
    """Area of a rectangle."""
    return w * h

def show(w, h):
    print("area is", w * h)

x = area(3, 4)      # 12 is stored
y = show(3, 4)      # prints, then y is None
print(x, y)
print(area(2, 5) + 1)
Output
area is 12
12 None
11
Defaults and keyword arguments
def greet(name, greeting="Hello", punct="!"):
    return f"{greeting}, {name}{punct}"

print(greet("Sam"))
print(greet("Sam", "Hi"))
print(greet(punct="?", name="Sam"))
Output
Hello, Sam!
Hi, Sam!
Hello, Sam?
Scope: locals disappear
total = 0

def add(n):
    total = n + 1      # a new local variable
    return total

print(add(5))
print(total)
Output
6
0

Worked example

What does this print?
def double(n):
    return n * 2

def quad(n):
    return double(double(n))

print(quad(3) + double(1))
Show the solution
14. quad(3) is double(double(3)) = double(6) = 12, and double(1) is 2.

Common mistakes

Exam tipTrace calls on paper with a table: parameter values in, returned value out. Most exam bugs are return-vs-print and argument order.

Keep going in Mathub

Mathub is free for Montana State students: an endless quizzer with worked explanations, one-question lessons, flashcards, exam prep checklists, the class calendar with every deadline, a grade calculator and a study board for CSCI 127.