Lesson 10 of 35Python
Python · Lesson 10 · 30 minutes
Your own functions
What you'll learn
- Write your own functions with
def - Pass values in with parameters and give them back with
return - Reuse functions inside other functions
Why your own functions?
You’ve been using functions all along: print(), len(), input(). Now you build your own! A function is a mini program with a name. You write it once and can then call it as often as you like.
def greet():
print("Hello!")
print("Great to have you here.")
greet()
greet()def means “define”. The code inside the function is indented and only runs when you call the function.
Parameters: passing values in
Inside the brackets you write parameters, placeholders for values you pass in when calling:
def greet(name, language="en"):
if language == "de":
print(f"Hallo {name}!")
else:
print(f"Hello {name}!")
greet("Mia")
greet("Tom", "de")language="en" is a default value: if you leave it out when calling, "en" is used.
return: giving results back
print() only shows something. With return the function gives back a result that you can keep calculating with:
def area(width, height):
result = width * height
return result
room = area(4, 3)
hall = area(5, 1)
print(f"Together: {room + hall} m²")Press Steps: when Python jumps into the function you see a separate memory area “Inside function area()”. Variables like result only exist there – after return they’re gone again.
Remember: After
returnthe function ends immediately. Code after it inside the function doesn’t run any more.
Combining functions
Functions get really powerful when they use each other. That keeps every function short and easy to understand:
def in_euros(cents):
return cents / 100
def price_text(cents):
return f"{in_euros(cents):.2f} €"
print(price_text(250))
print(price_text(1999)):.2f in the f-string means: show exactly 2 decimal places.
Quick check
Before you start the task: what does this program print? Type your guess – then Python works it out.
def double(number):
return number * 2
print(double(3) + double(1))Your task
Your turn
Write two functions. is_even(number) returns True if the number is even, otherwise False (tip: number % 2 is the remainder when dividing by 2). count_even(numbers) gets a list of numbers and returns how many of them are even. Use is_even for that.
def is_even(number):
# return True or False
pass
def count_even(numbers):
# count with the help of is_even
pass
print(is_even(4))
print(count_even([1, 2, 3, 4, 6]))- Something to think about
A number is even when number
%2==0. Give the result back withreturn. - Which command helps?
Start with count
=0, go through the list and increase count wheneveris_even(number)isTrue. At the end return count.Call
is_eveninsidecount_eveninstead of repeating the calculation. - Gap code – fill in the ___
def is_even(number): return ___ def count_even(numbers): count = ___ for number in ___: if ___: count = ___ return ___ print(is_even(4)) print(count_even([1, 2, 3, 4, 6]))
Solve it without hints to earn a ⭐ on your progress page.
Show solution🔒 Unlocks after all hints or 2 checks
Try it yourself first – mistakes teach you the most. Here is one possible solution:
def is_even(number):
return number % 2 == 0
def count_even(numbers):
count = 0
for number in numbers:
if is_even(number):
count = count + 1
return count
print(is_even(4))
print(count_even([1, 2, 3, 4, 6]))For fast learners
Pro task
Write is_palindrome(text). A palindrome reads the same forwards and backwards, like “Anna” or “racecar”. Upper and lower case and spaces don't count: “Never odd or even” is a palindrome too. The function returns True or False.
def is_palindrome(text):
return False
print(is_palindrome("Anna"))
print(is_palindrome("Python"))Show pro solution
def is_palindrome(text):
clean = text.lower().replace(" ", "")
return clean == clean[::-1]
print(is_palindrome("Anna"))
print(is_palindrome("Python"))