A function is a reusable block of code with a name. You write it once, then call it whenever you need it โ no copy-pasting. You've already used functions: print() and len() are built-in ones!
โ๏ธ Defining your own
Use the def keyword. Don't forget the colon and indentation:
def greet():
print("Hello there!")
print("Welcome to Python!")
greet() # call it โ runs the two prints
greet() # call it again!
๐ Define, then call
Writing def greet(): only creates the function. Nothing happens until you call it with greet().
๐ Parameters โ giving input
A parameter lets you pass information into a function so it can behave differently each time:
Write a function is_even(n) that returnsTrue if n is even, False if odd. Print is_even(8) then is_even(3). Output:
True
False
def is_even(n):
return n % 2 == 0
print(is_even(8))
print(is_even(3))
๐ฒ
Task 5: Free Play โ Your Own Function
Creative
Invent a useful function! Ideas: double(n) that returns nร2, shout(word) that returns it in CAPS, or a function that builds a fun greeting. Call it a few times.
๐๏ธ Extra Practice โ Drill Time!
Functions are how programmers stop repeating themselves. Write lots of small ones โ that is the whole trick.
๐
Task 6: Two Parameters
Easy
Write rectangle_area(width, height) that returns width ร height. Print the area of a 4 ร 6 rectangle and a 2 ร 9 rectangle.
Write min_and_max(numbers) that returns both the smallest and the largest value. Call it with [4, 9, 1, 7], unpack the answer into low, high, and print low 1 high 9.
Write safe_divide(a, b) that returns the text "Cannot divide by zero" straight away if b is 0, otherwise returns a / b. Print safe_divide(10, 2) and safe_divide(7, 0).
5.0
Cannot divide by zero
def safe_divide(a, b):
if b == 0:
return "Cannot divide by zero"
return a / b
print(safe_divide(10, 2))
print(safe_divide(7, 0))
๐
Task 12: A List Goes In
Tricky
Write average(numbers) that returns the mean of a list, rounded to 1 decimal place. Print the average of [8, 9, 10] and of [3, 4].
Write celsius_to_fahrenheit(c) with a docstring (a """triple-quoted""" sentence on the first line inside the function) explaining what it does. Print the result for 0 and 100, then print celsius_to_fahrenheit.__doc__ โ exactly the sentence Convert Celsius to Fahrenheit.
32.0
212.0
Convert Celsius to Fahrenheit.
def celsius_to_fahrenheit(c):
"""Convert Celsius to Fahrenheit."""
return c * 9 / 5 + 32
print(celsius_to_fahrenheit(0))
print(celsius_to_fahrenheit(100))
print(celsius_to_fahrenheit.__doc__)
๐งฐ
Task 14: Boss Level: Password Toolbox
Boss
Write three small functions: is_long_enough(p) (8+ characters), has_digit(p) (contains any of 0-9) and strength(p) which returns "strong" when both are true, "medium" when only one is, and "weak" when neither. Print the strength of "dragon123", "dragon" and "a1".
strong
weak
medium
def is_long_enough(p):
return len(p) >= 8
def has_digit(p):
for ch in p:
if ch.isdigit():
return True
return False
def strength(p):
score = 0
if is_long_enough(p):
score += 1
if has_digit(p):
score += 1
if score == 2:
return "strong"
if score == 1:
return "medium"
return "weak"
print(strength("dragon123"))
print(strength("dragon"))
print(strength("a1"))
๐ ๏ธ
Task 15: Free Play โ Build Your Toolbox
Creative
Write four functions you would actually use: convert money, work out a tip, turn a name into initials, pick a random complimentโฆ then call them all and print the results. Give every one a clear name and a docstring. ๐งฐ