Learn to code with step-by-step lessons. A place for students to work through programming fundamentals and build skills.
A function is a named block of code you can run whenever you need it. That keeps your program tidy and avoids repeating the same code.
Use def, the function name, brackets, and a colon. The code that runs when you call the function is indented:
def say_hello():
print("Hello!")
print("Welcome to coding club.")
Use the name and brackets:
say_hello()
say_hello()
Each call runs the whole block.
You can pass arguments into the function. The names in the brackets are parameters:
def greet(name):
print("Hello,", name)
greet("Alex")
greet("Sam")
You can have several parameters: def add(a, b): then add(3, 5).
Use return to send a value back. The caller can use it in an expression or assign it:
def double(n):
return n * 2
result = double(5) # result is 10
print(double(7)) # 14
After a return, the function stops. Code below it in the same function won’t run.
Take your Higher–Lower game and split it into functions, for example:
get_guess() — asks for a number and returns it (with a loop until they type a valid number if you like).check_guess(guess, secret) — returns "high", "low" or "correct".main() — picks secret, loops until correct, calls get_guess() and check_guess(), prints the message.Then at the bottom: main().
Next: 4.2 Scope and return values — where variables are visible and how to use return well.