Python Functions and Parameters
Master Python functions and parameters: define functions with def, pass arguments, use default and keyword parameters, return values, and understand scope. Runnable code, a worked example and a quiz.
Key takeaways
- A function is a named, reusable block of code defined with def
- Parameters are placeholders in the definition; arguments are the real values you pass
- return sends a result back to the caller; print only displays text
- Default values let arguments be optional, and keyword arguments make calls clearer
- Variables created inside a function are local and disappear when it ends
Why functions exist
Imagine writing the same ten lines of code in five different places. If you later find a mistake, you have to fix it five times — and you'll probably miss one. A function solves this by letting you write a block of code once, give it a name, and run it whenever you like just by calling that name.
You've already met built-in functions like print(), len() and input(). In this lesson you'll learn to build your own. If you're comfortable with variables and conditionals, you have everything you need.
Defining your first function
You create a function with the def keyword:
def greet():
print("Hello!")
print("Welcome to the program.")
greet()
greet()
Reading it line by line:
def greet():starts the definition.defmeans "define,"greetis the name you chose, the empty()means it takes no inputs, and the:opens the block.- The two indented
printlines are the body — the code that runs when the function is called. greet()on the last lines calls the function. Each call runs the body again, soHello!andWelcome to the program.print twice.
Defining a function does not run it. Nothing happens until you call it by name with parentheses.
Parameters and arguments
A function becomes far more useful when you can feed it information. The placeholders you list in the definition are parameters; the real values you supply when calling are arguments.
def greet(name):
print(f"Hello, {name}!")
greet("Amir")
greet("Priya")
nameindef greet(name):is a parameter — an empty slot.- When you call
greet("Amir"), the argument"Amir"is copied intoname, so the function printsHello, Amir!. - The second call fills
namewith"Priya"instead.
One definition, many different results — that's the power of parameters.
You can have several parameters, separated by commas:
def describe(animal, sound):
print(f"The {animal} says {sound}.")
describe("dog", "woof")
describe("cat", "meow")
The arguments line up with the parameters in order: the first argument fills the first parameter, the second fills the second.
Returning a value
So far our functions only print. Often you want a function to calculate something and hand the answer back so the rest of your program can use it. That's what return does.
def add(a, b):
return a + b
total = add(3, 4)
print(total) # 7
print(add(10, 20)) # 30
return a + bcomputes the sum and sends it back to wherever the function was called.total = add(3, 4)captures that returned value (7) in a variable.- You can also use the result directly, as in
print(add(10, 20)).
This is a crucial difference: print shows text to a human; return gives a value to your program. A function that only prints can't be used in further calculations.
When a function reaches return, it stops immediately — any lines after it are skipped. And if a function has no return at all, it quietly returns the special value None.
Default parameter values
You can make a parameter optional by giving it a default value in the definition. If the caller leaves it out, the default is used.
def greet(name, greeting="Hello"):
print(f"{greeting}, {name}!")
greet("Lena") # Hello, Lena!
greet("Lena", "Welcome") # Welcome, Lena!
greeting="Hello"sets the default.- The first call supplies only
name, sogreetingstays"Hello". - The second call overrides the default by passing
"Welcome".
A rule to remember: parameters with defaults must come after parameters without them in the definition.
Keyword arguments
When a function takes several arguments, it's easy to lose track of which is which. Keyword arguments let you name them at the call site, making your code self-explanatory and order-independent:
def make_box(width, height, colour):
print(f"A {colour} box, {width} by {height}.")
make_box(width=5, height=2, colour="red")
make_box(colour="blue", width=8, height=3)
Because each value is labelled, the second call can list them in a different order and still work correctly. This is especially helpful for functions with many parameters.
Scope: where variables live
Variables created inside a function are local — they exist only while the function runs and vanish afterwards. They cannot be seen from outside.
def calculate():
result = 42 # local variable
return result
print(calculate()) # 42
# print(result) # would cause an error: result is not defined out here
result lives only inside calculate. Trying to print it outside causes a NameError. This "walled garden" is a good thing: it means functions don't accidentally trample on each other's variables, and you can reuse common names like i or total without conflict.
Worked example: a tip calculator
Let's pull it all together into a small, realistic program.
def calculate_tip(bill, percent=15):
tip = bill * percent / 100
return round(tip, 2)
def total_with_tip(bill, percent=15):
tip = calculate_tip(bill, percent)
return bill + tip
print(calculate_tip(50)) # 7.5
print(calculate_tip(50, 20)) # 10.0
print(total_with_tip(50)) # 57.5
print(total_with_tip(80, percent=10)) # 88.0
How it works:
calculate_tiptakes abilland apercentthat defaults to 15. It works out the tip, thenround(tip, 2)neatens it to two decimal places before returning it.total_with_tipcalls another function (calculate_tip) to get the tip, then returns the bill plus that tip. Functions calling functions is completely normal and keeps each one focused on a single job.- The print lines show different combinations: using the default 15%, overriding it to 20%, and using a keyword argument for clarity.
Notice how each function does one thing well and returns a value — so the results can be combined.
Try it yourself
Build a small set of cooperating functions:
- Write
area_of_rectangle(width, height)that returnswidth * height. - Write
area_of_square(side)that callsarea_of_rectangleto avoid repeating the maths. - Write
describe_shape(name, area)that returns a sentence like"The garden has an area of 12 square metres.". - Give one function a default parameter, and call another using keyword arguments.
When your functions are returning the right values, see how they slot into bigger programs in python loops and lists, where you can call a function on every item of a list.
Quick quiz
Test yourself and earn XP
Which keyword defines a function in Python?
Python uses def, followed by the function name and parentheses, to define a function.
What is the difference between a parameter and an argument?
Parameters appear in the def line as names. Arguments are the concrete values you supply when you call the function.
What does this return? ``` def double(n): return n * 2 x = double(5) ```
double(5) runs n * 2 with n = 5, returning 10, which is stored in x.
What does a function return if it has no return statement?
A function with no return statement automatically returns the special value None.
In `def greet(name, greeting="Hi")`, what is `greeting="Hi"`?
Assigning a value in the definition gives that parameter a default, so the caller can leave it out.
FAQ
print displays text in the console for a human to read, but it does not give a value back to your program. return hands a value back to whatever called the function, so you can store it, do maths with it, or pass it on. A function can print and return, but they do completely different jobs.
Functions follow the DRY principle: Don't Repeat Yourself. Writing logic once and calling it many times means less typing, fewer bugs, and a single place to fix mistakes. They also give chunks of code clear names, which makes programs far easier to read.
Keep exploring
More in Coding