print('Hello, world!')Hello, world!
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:
If you find yourself copying and pasting code to multiple locations, that’s a sign you should turn it into a function.
The parentheses are the tell-tale sign of a function. You must include them to call it:
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.
You can define your own functions. Here’s the anatomy:
def keyword: Starts the definition.multiply).return statement (optional): Sends a result back to whoever called the function.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.
Write a function called add that takes two parameters (a and b) and returns their sum.
Write a function called square that takes a single parameter (number) and returns the number squared. (Remember the ** exponent operator from the previous lesson.)
Not every function needs to return something. Some just perform an action. Notice there is no return statement here:
You can also give parameters default values, which makes them optional when calling the function. Default parameters must come after non-default ones:
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:
lower()
Converts all characters in the string to lowercase.
upper()
Converts all characters in the string to uppercase.
strip()
Removes leading and trailing whitespace (or other specified characters).
replace()
Replaces occurrences of a substring with another substring.
capitalize()
Capitalises the first character of the string and makes the rest lowercase.
The difference is in how you call them:
len("Hello") returns 5."Hello".upper() returns "HELLO".Both do things. Methods just know which object they’re working on.
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.
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.
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.
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.
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.
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.