You've already used functions like print() and input(). But what if you could create your own custom commands? That's exactly what functions let you do! Think of a function as a recipe - you write it once, then use it whenever you need it.
Your First Function
Creating a function is easy! Here's how:
def say_hello():
print("Hello there!")
print("Welcome to Python!")
# Now use it:
say_hello()
The 'def' keyword means 'define a function'. The name is 'say_hello'. The parentheses () are important - don't forget them! Everything indented underneath is what the function does.
Functions with Inputs
Functions can take inputs (called parameters):
def greet(name):
print("Hello,", name + "!")
print("Nice to meet you!")
# Use it with different names:
greet("Alex")
greet("Sam")
greet("Jordan")
Now the function can greet anyone! The 'name' inside the parentheses is a parameter - it's a placeholder for whatever you pass in.
Functions that Return Values
Functions can also give back a result:
def add_numbers(a, b):
result = a + b
return result
# Use it:
answer = add_numbers(5, 3)
print("5 + 3 =", answer) # Prints: 5 + 3 = 8
The 'return' keyword sends the result back. You can then save it in a variable or use it directly.
Build a Simple Calculator
Let's put it all together:
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
# Test your calculator:
print("10 + 5 =", add(10, 5))
print("10 - 5 =", subtract(10, 5))
print("10 × 5 =", multiply(10, 5))
You just built a calculator using functions! Try adding a divide function on your own.
Fantastic! You now know how to create your own functions. This is a huge step in your coding journey! Functions help you organize code, avoid repetition, and make your programs easier to understand. Professional programmers use functions constantly - every app, game, and website is built with thousands of functions working together. Keep practicing by creating functions for things you do often!
E
Emma Chen
Age 12 · Malaysia · Coding Builder
Share this post

