Functions and Methods

Download notebook

Functions

You’ve already been using functions: print(), type(), int(). A function is a named, reusable block of code. Python comes with many built-in functions, and you can write your own.

Two reasons to write functions:

  1. Reuse: Write the logic once, call it as many times as you need.
  2. Readability: Small functions with clear names are easier to follow than one long script.
Tip

If you find yourself copying and pasting code to multiple locations, that’s a sign you should turn it into a function.

Built-in Functions

The parentheses are the tell-tale sign of a function. You must include them to call it:

print('Hello, world!')
Hello, world!

print() takes an input (a string, a variable, a number) and displays it on screen. You’ve also used int() and str() for type casting. These are all built-in functions that come with Python.

Creating a Function

You can define your own functions. Here’s the anatomy:

  1. def keyword: Starts the definition.
  2. Function name: A descriptive name (e.g., multiply).
  3. Parentheses: Contain the parameters (inputs). Leave them empty if the function needs no input.
  4. Indented body: The code the function runs. These lines must be indented (typically four spaces), and the indentation must be consistent.
  5. return statement (optional): Sends a result back to whoever called the function.
def multiply(a, b):
    result = a * b
    return result

my_result = multiply(3, 4)
print('3 multiplied by 4 is:', my_result)
3 multiplied by 4 is: 12

When you call multiply(3, 4), Python assigns 3 to a and 4 to b, runs the body, and returns 12. That returned value gets stored in my_result.


Practise

Write a function called add that takes two parameters (a and b) and returns their sum.

def add(a, b):
    return a + b

print('4 + 3 =', add(4, 3))
print('1 + 2 =', add(1, 2))
4 + 3 = 7
1 + 2 = 3

Write a function called square that takes a single parameter (number) and returns the number squared. (Remember the ** exponent operator from the previous lesson.)

def square(number):
    return number ** 2

print('The square of 5 is:', square(5))
The square of 5 is: 25

More About Functions

Not every function needs to return something. Some just perform an action. Notice there is no return statement here:

def greet(name):
    print('Hello', name)

greet('Alice')
Hello Alice

You can also give parameters default values, which makes them optional when calling the function. Default parameters must come after non-default ones:

def introduce(name, age=30):
    print(f'My name is {name}, and I am {age} years old.')

introduce('Alice', age=40)
introduce('Bob')  # age defaults to 30
My name is Alice, and I am 40 years old.
My name is Bob, and I am 30 years old.

Methods

Methods are functions that belong to a specific type of object. You call them with dot notation: object.method().

The difference from a standalone function like print() is that a method is attached to the data itself. Every string in Python comes with a set of built-in methods. Here are some common ones:

  1. lower()
    Converts all characters in the string to lowercase.

    print("HELLO".lower())
    hello
  2. upper()
    Converts all characters in the string to uppercase.

    print("hello".upper())
    HELLO
  3. strip()
    Removes leading and trailing whitespace (or other specified characters).

    print("  Hello  ".strip())
    print("yyHelloyy".strip("y"))
    Hello
    Hello
  4. replace()
    Replaces occurrences of a substring with another substring.

    print("I love Python".replace("Python", "coding"))
    I love coding
  5. capitalize()
    Capitalises the first character of the string and makes the rest lowercase.

    print("python is fun".capitalize())
    Python is fun

Methods vs Functions

The difference is in how you call them:

  • Functions are standalone. You pass the data in as an argument: len("Hello") returns 5.
  • Methods belong to an object. You call them on the data with dot notation: "Hello".upper() returns "HELLO".

Both do things. Methods just know which object they’re working on.

More Practise

These exercises combine what you’ve learned about functions, default parameters, and methods. Exercises 2 through 5 build on each other, ending with a function that calls all the others.

1. Excited Greeting

Create a function called excited_greeting which takes a parameter called name and a default parameter called punctuation with a default value of !!!. The function should return a greeting with the name shouted in all caps, followed by the punctuation.

def excited_greeting(name, punctuation="!!!"):
    return f'HEY {name.upper()}{punctuation}'

print(excited_greeting('Lucy'))              # default punctuation
print(excited_greeting('Lucy', '!!!??!!'))   # custom punctuation
HEY LUCY!!!
HEY LUCY!!!??!!

2. Cost Per Square Metre

Create a function called cost_per_sqm that calculates the cost per square metre. It should take two parameters: the build cost (build_cost) and the total square metres (sqm). Test it with a flat that costs £150,000 to build and is 40 square metres.

def cost_per_sqm(build_cost, sqm):
    return build_cost / sqm

result = cost_per_sqm(150000, 40)
print(f'Cost per square metre: £{result}')
Cost per square metre: £3750.0

3. Add Markup

Create a function called add_markup that applies a percentage markup to a base cost. It should take two parameters: the base cost (base_cost) and the markup percentage (markup_pct). It should return the cost after markup. Test it with a base cost of £3,750 and a 10% markup.

def add_markup(base_cost, markup_pct):
    return base_cost * (1 + markup_pct / 100)

cost_with_markup = add_markup(3750, 10)
print(f'Cost with markup: £{cost_with_markup}')
Cost with markup: £4125.0

4. Monthly Rental Price

Create a function called monthly_rental that calculates a monthly rental price to recoup build costs over 20 years. It should take two parameters: the square metres (sqm) and the cost per square metre after markup (sqm_cost). Multiply them to get the total cost, divide by 20 for the yearly amount, then divide by 12 for the monthly amount. Test it with 40 sqm at £4,125 per sqm.

def monthly_rental(sqm, sqm_cost):
    yearly = (sqm * sqm_cost) / 20
    monthly = yearly / 12
    return monthly

price = monthly_rental(40, 4125)
print(f'Monthly rental: £{price:.2f}')
Monthly rental: £687.50

5. Combine All Functions

Functions can call other functions. Create a function called auto_responder that takes name, sqm, build_cost, and markup as parameters. It should use the functions you wrote above to calculate the monthly rental and return a formatted response.

Test it with Harry’s enquiry: a 35 sqm flat, £150,000 build cost, 7.5% markup.

def auto_responder(name, sqm, build_cost, markup):
    sqm_cost = cost_per_sqm(build_cost, sqm)
    with_markup = add_markup(sqm_cost, markup)
    rent = monthly_rental(sqm, with_markup)

    greeting = excited_greeting(name)
    return f"{greeting} The monthly rent for the {sqm}m² flat is £{rent:.2f}."

response = auto_responder('Harry', 35, 150000, 7.5)
print(response)
HEY HARRY!!! The monthly rent for the 35m² flat is £671.88.