Python course Β· Module 1: Python Basics
Functions - Exploration Tools
In this lesson7
Welcome! After every stage of the route you calculate the average marching speed. The third time you copy the same formula, you make a typo. A good explorer doesn't perform every task from scratch. They have ready-made tools: one swing of the machete, one gesture to pitch the tent. In programming, such a reusable tool is called a function. A function is a named block of code that we can run whenever we want.
Defining a Function - the def Keyword
We create a function with the keyword def (from "define"). We give the function a name, parentheses and a colon, and below - an indented block of code. The indentation, usually four spaces, tells Python which lines belong to the function:
def greet_explorer():
print("Welcome to the Safari!")
print("Darwin wishes you a great expedition.")
# Calling the function - we run it by its name
greet_explorer()Merely defining a function does not run it - it's like writing the instruction manual for a tool. To use the tool, we must call it by writing its name with parentheses: greet_explorer(). We can call it many times! The bare name without parentheses does nothing - it is just a tool hanging on a hook.
Parameters - Passing Data into a Function
A tool becomes more powerful when we can pass something to it. Parameters are data that a function accepts in parentheses. In the definition name is a slot for a value, and in the call we pass a concrete argument:
def greet_explorer(name):
print(f"Welcome, {name}, to the Safari!")
greet_explorer("Darwin") # Welcome, Darwin, to the Safari!
greet_explorer("Anna") # Welcome, Anna, to the Safari!The same function printed two different greetings, because name gets a new value with every call. A parameter lives only inside the function - outside it, the name name does not exist.
A function can accept multiple parameters. We separate them with commas, and the arguments land in their slots in order:
def describe_animal(species, weight):
print(f"{species} weighs {weight} kg.")
describe_animal("Elephant", 5000) # Elephant weighs 5000 kg.
describe_animal("Lion", 190) # Lion weighs 190 kg.Order matters: describe_animal(5000, "Elephant") prints "5000 weighs Elephant kg." - Python won't guess what you meant.
Returning a Value - the return Keyword
So far our functions only displayed text. But often we want a function to compute something and give us the result. That's what the return keyword is for:
def calculate_speed(distance, time):
speed = distance / time
return speed
# We can save the result to a variable
result = calculate_speed(30, 4)
print(f"Speed: {result} km/h") # Speed: 7.5 km/h
# Or use it right away
print(f"Speed: {calculate_speed(60, 3)} km/h") # Speed: 20.0 km/hThe difference is important: print() only shows text on the screen, while return gives back a value that we can use further in calculations. After return runs, the function ends immediately.
What Happens Without return?
The most common mistake of novice trackers: the function prints the result instead of returning it. The screen looks fine, but nothing reaches the variable:
def show_speed(distance, time):
print(distance / time)
result = show_speed(30, 4) # prints 7.5
print(result) # NoneA function without return returns None, the "no value" from the lesson on types. The number 7.5 appeared on screen, but result does not hold it. So my advice: let calculating functions return the result, and leave displaying to the code that calls them.
Functions with Conditions - Combining Knowledge
Functions can contain everything you've learned - conditions, loops, operators. This function decides whether an animal is too heavy to approach closely:
def is_dangerous(weight):
if weight > 1000:
return True
else:
return False
print(is_dangerous(5000)) # True (elephant)
print(is_dangerous(190)) # False (lion)It works, but it is wordy. The comparison weight > 1000 is already a True or False value by itself, so you can return it directly:
def is_dangerous(weight):
return weight > 1000
print(is_dangerous(5000)) # TrueThe result is identical, and the function is three lines shorter. I recommend this form - the fewer branches, the harder it is to get lost.
Practice
Write a function that calculates how many days it takes to cover a given distance. Run the function in the editor and call it with other values:
Code for this lesson: main.py
# Functions - expedition day calculator
# TODO: define a function that calculates the number of days
# distance - distance in km, daily_pace - km per day
def calculate_days(distance, daily_pace):
days = distance / daily_pace
return days
# TODO: call the function and display the result
result = calculate_days(120, 30)
print(f"The expedition will take {result} days")
# Try other values:
print(f"100 km at a pace of 25 km/day: {calculate_days(100, 25)} days")Summary
In this lesson you created your own explorer's tools:
def- defines a function (a named block of code)- Calling a function with
name() - Parameters - data passed into a function in parentheses
return- returns a result that can be used further- The difference between
print()(displays) andreturn(gives back a value)
Congratulations! You now know the fundamentals of Python: variables, types, operators, conditions, loops, and functions. Time to combine this knowledge in a great expedition project!
Remember: a function is a tool from your backpack - you define it once with def, then reach for it with a call as often as you like.
Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. Which keyword do we use to define a function?
2. What is return used for in a function?
3. How does print() differ from return?
Hands-on tasks in the game
- Click in order
Click the elements to call the function greet():
- Code editor
Define a function calculate_days(distance, daily_pace) that returns distance / daily_pace. Call it for 150 km at 30 km a day and print the result: