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
def name(parameters):defines a function; the indented body runs only when the function is called withname(arguments).return valuehands a result back to the caller and ends the function. A function with noreturnreturnsNone. Printing is not returning.- Parameters are local: variables created inside a function vanish when it ends. A function can read a global variable but should take what it needs as parameters.
- Default values (
def greet(name, punct="!")) make arguments optional. Keyword arguments (greet(punct="?", name="Al")) can come in any order. - Design: one job per function, a docstring that says what it does, and small functions that call each other. Test each one alone before wiring them together.
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
- Printing inside a function and then trying to use the value: you get
None. - Code after
returnnever runs. - Forgetting to call the function at all, or calling it before it is defined.
- Changing a global variable inside a function without
globalcreates a local copy instead.
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.