A function is a set of steps you give a name, so you can run those steps whenever you want without writing them out again.
def greet(name):
return "Hello, " + name + "!"
print(greet("Sam"))
print(greet("Ada"))Written once, used twice. Change the greeting in one place and both calls update.
The three parts of a function#
- A name — what it does, usually a verb:
calculate_total,send_email. - Inputs (parameters) — the information it needs, in brackets.
- An output (return value) — the answer it hands back.
def area(width, height):
return width * height
print(area(3, 4)) # 12width and height are parameters — placeholder names. The 3 and 4 you pass in are arguments — the real values.
function area(width, height) {
return width * height;
}
console.log(area(3, 4)); // 12Return versus print — the one that confuses everyone#
print shows something to a person. return hands a value back to the code that called the function. They are not interchangeable.
def double_printed(n):
print(n * 2)
def double_returned(n):
return n * 2
result = double_printed(5) # displays 10, result is None
result = double_returned(5) # displays nothing, result is 10
print(result * 3) # 30 — only works with the second oneIf a function’s answer needs to be used in further calculations, it must return. A function with no return hands back “nothing” (None in Python, undefined in JavaScript), which is why None * 3 errors.
Default values#
def greet(name, greeting="Hello"):
return greeting + ", " + name + "!"
print(greet("Sam")) # Hello, Sam!
print(greet("Sam", "Welcome")) # Welcome, Sam!Variables inside a function stay inside it#
A variable created inside a function does not exist outside it. This is called scope, and it is a feature rather than an inconvenience — two functions can both use a variable called total without interfering with each other.
def calculate():
subtotal = 100
return subtotal
calculate()
print(subtotal) # NameError: name 'subtotal' is not definedIf you need the value outside, return it and store the result.
When should something become a function?#
- You copied and pasted code. The second copy is the moment to make a function.
- You want to name a step. If a block needs a comment explaining what it does, that comment is usually the function name.
- A block does more than one job. “Fetch the data and format it and save it” is three functions wearing a trench coat.
You do not need to make everything a function. A five-line script is fine as it is.
A worked example#
def apply_discount(price, percent):
return price - (price * percent / 100)
def format_money(amount):
return "Rs " + str(round(amount, 2))
original = 2500
final = apply_discount(original, 15)
print("Was:", format_money(original))
print("Now:", format_money(final))Two small functions, each doing one thing, combined at the end. That is the shape most well-organised programs take.
Questions people ask#
What is the difference between a function and a method?
A method is a function that belongs to an object. len(name) is a function; name.upper() is a method on the string. You call methods with a dot after the thing they work on.
Can a function call another function?
Yes, and it is normal. Small functions calling other small functions is how larger programs stay readable.
How many parameters is too many?
If you are passing five or six, the function is probably doing too much, or those values belong together in one object. Three or four is a reasonable ceiling for everyday code.
Can a function return more than one value?
Python can return several at once (return width, height) and you unpack them into two variables. JavaScript does the same by returning an object or an array.