Phase 1 · Programming Fundamentals
Functions
Package logic into reusable functions with parameters, return values, and clean defaults.
On this page
Defining and calling functions
A function is a named block of code. You define it with def, then call it by name with parentheses.
Use snake_case for function names: calculate_total, greet_user. Keep each function focused on one job.
def say_hello():
print("Hello, Learn AI!")
say_hello()
say_hello()Remember the colon after the header and indent the body—same rules as if and for.
Parameters & arguments
Parameters are names listed in the def line. Arguments are the values you pass when calling.
You can pass multiple arguments in order (positional) or by name (keyword).
def greet(name):
print(f"Welcome, {name}!")
greet("Ada")
greet("Grace")
def introduce(name, role):
print(f"{name} is a {role}.")
introduce("Ada", "engineer")
introduce(role="researcher", name="Grace")Keyword arguments make calls clearer when there are several parameters.
Returning values
print shows something; return sends a value back to the caller so you can store or reuse it.
A function without return (or with a bare return) gives back None.
def add(a, b):
return a + b
total = add(3, 5)
print(total) # 8
print(add(10, 2) * 2) # 24
def shout(text):
print(text.upper())
result = shout("hi")
print(result) # None — shout only printsPrefer return when the next step needs the result. Prefer print for display-only helpers.
Defaults & local scope
Default parameter values make arguments optional. Put parameters with defaults after required ones.
Variables created inside a function are local—they do not leak into the rest of your program.
def power(base, exponent=2):
return base ** exponent
print(power(5)) # 25 (square)
print(power(2, 8)) # 256def double(n):
result = n * 2
return result
print(double(4))
# print(result) # NameError — result exists only inside doubleAvoid mutable defaults like [] or {}—use None and create a new list/dict inside the function instead.
Practice
Mini challenge: tip calculator
Write a function calculate_tip(bill, percent=15) that returns the tip amount. Then write total_with_tip(bill, percent=15) that returns bill + tip. Ask the user for a bill and print both values.
def calculate_tip(bill, percent=15):
# TODO: return the tip amount
pass
def total_with_tip(bill, percent=15):
# TODO: return bill + tip (reuse calculate_tip)
pass
bill = float(input("Bill amount: "))
# print tip and total
Interactive
Try It in the browser
Powered by Pyodide
Write is_even(n) that returns True if n is even, otherwise False. Ask for a number and print the result.
Output
—
Errors
—
Check understanding
Lesson quiz
Score 4/5 or higher to mark this day complete.