Functions Jump to this section
Functions let you put a chunk of code in one place and run it multiple times.
Why use functions? Jump to this section
- Avoid repeating code
- Break problems into smaller, testable pieces.
- Give a name to a task so your code reads like instructions.
Defining and Calling a Function Jump to this section
Use def to define a function, give it a name, parentheses, and a colon. Put the actual code of the function below (make sure to indent it).
def greet(): # define the function
print("Hello!")
greet() # call the function
Defining a function does not run it. The code inside runs only when you call it.
Parameters and Return Values Jump to this section
Functions can take parameters (inputs) and return values (outputs).
def greet(name):
print("Hello", name)
greet("Ada") # Hello Ada
Functions can take multiple parameters:
def add(a, b):
return a + b
result = add(3, 2)
print(result) # 5
If a function doesn't use return, it returns None by default.
Default Values Jump to this section
You can give parameters default values and call by name.
def power(x, exp=2): # without a default this would be "def power(x, exp)""
return x ** exp # remember, ** is used to raise to a power
print(power(3)) # 9 (uses default exp=2)
print(power(2, exp=3)) # 8 (override default)
Scope (local vs global) Jump to this section
Variables created inside a function are local to that function (they only exist inside the function and cannot be used anywhere else).
def f():
x = 10 # local
# x is not available here
Variables defined inside a function are local by default.
You can use the global keyword to make a variable accessible anywhere (global name = Ada), but this shouldn't be used often.
Small examples Jump to this section
Example: a function that formats a name:
def format_name(first, last):
return last + ", " + first
print(format_name("Ada", "Lovelace"))
# Output: Lovelace, Ada
Example: function used inside a loop:
def greet_person(name):
print("Hello", name)
names = ["Ada", "Grace"]
for n in names:
greet_person(n)
Challenge Jump to this section
Write a function is_even(n) that returns True when n is even and False otherwise. Then use it to print whether numbers 1..10 are even.
Hint
Use the modulus operator % with 2: n % 2 is 0 when n is even.
Show example solution
def is_even(n):
return n % 2 == 0
for i in range(1, 11):
print(i, "even?", is_even(i))
Key Takeaways Jump to this section
- If you copy-paste code more than once, it probably should be a function.
- Use
def name(parameters):to define a function andname()to call it. - Parameters are the values that a function receives (input);
returnsends a result back (output). - Prefer small functions that do one job; they are easier to test and reuse.
- Understand local variables: variables defined inside a function are not visible outside it.
