If you need the same calculation in many places, give it a name once and use it whenever you want. That is defining a function with def. This one splits an amount between 3 people:
def split3(total):
result = total / 3
return result
print(split3(6000))
print(split3(900))2000.0 300.0
| Step | Code |
|---|---|
| (1) Name and parameter | def split3(total): |
| (2) The work, indented | result = total / 3 |
| (3) Return the result | return result |
| (4) Call it | print(split3(6000)) |
def line ends with : and every line of the function is indented. A function never runs until you call it. Its name cannot contain a dot ..Parameter, argument and return value
The name inside the def brackets (here num) waits for a value. The value you pass when calling (like 10) is put into it. Whatever follows return goes back to where the function was called, so you can print it, store it, or keep calculating with it:
def calc7(num):
result = num * 7
return result
answer = calc7(10)
print(answer)
print(calc7(3) + 1)70 22
A function can contain an if and take more than one argument, separated by commas. This one works like min for two numbers:
def min2(num1, num2):
if num1 < num2:
result = num1
else:
result = num2
return result
print(min2(5, 10))
print(min2(8, 3))5 3
Variable scope
Scope is where a variable can be used. A variable created inside a function lives only inside it, so using it outside gives an error:
def split5(total):
result = total / 5
return result
print(result)NameError: name 'result' is not defined
print(split5(7500)). If you forget return, the function gives back None.Practice
Create a function split4 with parameter total that returns total ÷ 4, then print split4(1200).
Press Run to see the result. The program prints None. Add the missing line inside the function so it prints 70.
Hint
The function gives nothing back. Which word returns the result?def calc(num):
result = num * 7
print(calc(10))Press Run to see the result. Call calc with the argument 3 and print the result.
def calc(num):
result = num * 5
return result
print(___)Press Run to see the result. Create a function split7 with parameter total that divides the amount by 7, then print the result of calling it with 14000.
Press Run to see the result. Create a function to_minutes with parameter hours that returns the number of minutes (hours × 60). Print to_minutes(3), then to_minutes(1.5).
Press Run to see the result. A bookshop gives 10% off any bill of 500 or more. Create a function final_price with parameter price that returns price * 0.9 if price ≥ 500, otherwise price unchanged. Print final_price(800), then final_price(300).
Press Run to see the result. Key points
def name(param):, then the indented work, thenreturn; call it withname(value).- The returned value can be printed or stored in a variable.
- A variable created inside a function cannot be used outside it.