Writing your own functions
A function that ends without return gives back None, which is why print(print("hi")) shows hi and then None.
Two functions that look the same on screen
Most beginners believe that showing a value and handing it back are the same thing. Here are two functions that both seem to "give" the area of a rectangle. def starts a function definition: a name, the inputs in brackets, a colon, and an indented body. Run the program and both lines of output look alike.
def show_area(w, h):
print(w * h)
def area(w, h):
return w * h
show_area(4, 3)
print(area(4, 3))12
12Now try to use the results in a calculation. The difference appears at once.
def show_area(w, h):
print(w * h)
def area(w, h):
return w * h
a = show_area(4, 3)
b = area(4, 3)
print(a, b)
print(b * 2)12
None 12
24show_area prints 12 to the screen and then ends. It hands nothing back, and a function that hands nothing back returns the special value None. So a is None. area prints nothing; it returns 12 to the line that called it, and that 12 can be stored, printed, or doubled. Printing is for people looking at the screen. Returning is for the rest of the program. If you want to use a result later, return it.
Parameters are the names, arguments are the values
In def area(w, h):, w and h are parameters: names that exist only inside the function. In area(4, 3), 4 and 3 are arguments: the values that fill those names for that one call. They are matched by position, so the first argument goes to the first parameter. Call the function with the wrong number of arguments and Python stops with a TypeError that names the missing parameter.
A parameter can have a default value, written with = in the definition. Callers can leave that argument out, and the default is used. The Python tutorial shows defaults in its section on defining functions, and they are everywhere in the built-in functions. print itself has one: its end parameter defaults to a new line.
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
print(greet("Mina"))
print(greet("Jun", "Hi"))
print("no new line", end=" ")
print("here")Hello, Mina!
Hi, Jun!
no new line herereturn ends the function straight away
A function stops at the first return it reaches, even if there are more lines below. That makes early returns a tidy way to handle special cases. The function below uses the ticket rule from the unit on if, now packaged so any part of a program can ask for a price.
def ticket_price(age):
if age < 7:
return 0
if age <= 18:
return 3000
return 5000
family = [40, 15, 5]
total = 0
for age in family:
total += ticket_price(age)
print(total)8000Variables created inside a function are local: they exist while the function runs and disappear when it ends. A variable named total inside one function has nothing to do with a total outside it. This is what lets you reuse a function without worrying about which names the rest of the program happens to use.
| def | Starts a function definition |
| parameter | A name in the definition: w in def area(w, h) |
| argument | A value passed in a call: 4 in area(4, 3) |
| return | Hands a value back and ends the function |
| None | What a function returns when it has no return |
| local variable | A variable that exists only inside a function |
- What does this print?
def double(x): return x * 2 print(double(7)) - What does this print?
def hello(): print("hi") result = hello() print(result)hi
hihi
NoneNonehi
- What does this print?
def add(a, b): return a + b print(add(2, 3) * add(1, 1)) - What does this print?
def f(x): return x + 1 print("never") print(f(1)) - What does this print?
def greet(name, greeting="Hello"): return greeting + " " + name print(greet("Bo")) - What does this print?
def sign(n): if n > 0: return "plus" if n < 0: return "minus" return "zero" print(sign(-4), sign(0)) - What does this print?
print("a", end="-") print("b") - What does this print?
def total_of(nums): t = 0 for n in nums: t += n return t print(total_of([4, 5, 6])) - In def area(w, h):, what are w and h called?
- Arguments
- Parameters
- Return values
- Keywords
- Put the lines in order so the program prints 25.Output
25
- "A function that prints the answer has returned it." Printing only shows the value. The function still returns None, so x = show_area(4, 3) leaves x as None and x * 2 stops with TypeError: unsupported operand type(s) for *: 'NoneType' and 'int'.
- "I can call a function above the line where I define it." Python runs from the top, so at that point the name does not exist yet: NameError: name 'area' is not defined. Put the def above the first call.
- "Leaving out an argument just makes it zero." Without a default, Python stops: area(4) gives TypeError: area() missing 1 required positional argument: 'h'.
- def name(params): starts a function; the body is indented.
- return hands a value back and ends the function.
- print shows a value; it does not return it. No return means None.
- Arguments fill parameters by position; defaults fill missing ones.
- Variables made inside a function are local to it.
Sources for this course (6)
- Python Software Foundation, The Python Tutorial for Python 3.12 (docs.python.org/3.12/tutorial: 2 Using the Python Interpreter, 3 An Informal Introduction to Python (numbers, text, lists), 4 More Control Flow Tools (if, for, range, break and continue, defining functions, default argument values, 4.10 coding style: 4-space indentation), 5 Data Structures (list methods, 5.5 dictionaries, insertion order), 8 Errors and Exceptions (syntax errors, exceptions, reading the traceback, handling exceptions), 15 Floating-Point Arithmetic (0.1 + 0.2))
- Built-in Functions (docs.python.org/3.12/library/functions.html: print, input, len, int, float, str, type, round (round half to even: round(0.5) and round(-0.5) are 0, round(1.5) is 2), range, sum, min, max, sorted)
- Built-in Types (str methods upper, lower, replace, strip; dict.get; list.append, pop, remove, sort returning None)
- General Python FAQ (docs.python.org/3.12/faq/general.html: Guido van Rossum began Python in the 1989 Christmas holidays, posted it to USENET in February 1991, named it after Monty Python's Flying Circus)
- Curriculum for the Korean pages: 교육부 고시 제2022-33호 [별책 10] 정보과 교육과정 (PDF read 2026-10-19: 중학교 정보 [9정03-05] 리스트 등 데이터를 순차적으로 저장하는 구조, [9정03-06] 논리 연산과 중첩 제어 구조, [9정03-07] 함수 활용과 디버거로 오류 수정, [9정03-08] 실생활 문제를 프로그래밍으로 해결, 적용 시 고려 사항 「학생의 수준을 고려하여 적합한 프로그래밍 언어를 선정」; 고등학교 정보 [12정03-04] 자료형, [12정03-05] 표준입출력, [12정03-07] 제어 구조)
- Bug story only: Smithsonian National Museum of American History, Log Book With Computer Bug, 1947, Harvard Mark II, "first actual case of bug being found", probably not Hopper's log book (americanhistory.si.edu/collections/object/nmah_334663, read 2026-10-19)
Checked: 2026-10-19