Welcome, @name! 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.
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.
1def greet_explorer():
2 print("🌴 Welcome to the Safari!")
3 print("Darwin wishes you a great expedition.")
4
5# Calling the function - we run it by its name
6greet_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!
A tool becomes more powerful when we can pass something to it. Parameters are data that a function accepts in parentheses.
1def greet_explorer(name):
2 print(f"🌴 Welcome, {name}, to the Safari!")
3
4greet_explorer("Darwin") # 🌴 Welcome, Darwin, to the Safari!
5greet_explorer("Anna") # 🌴 Welcome, Anna, to the Safari!A function can accept multiple parameters:
1def describe_animal(species, weight):
2 print(f"{species} weighs {weight} kg.")
3
4describe_animal("Elephant", 5000)
5describe_animal("Lion", 190)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.
1def calculate_speed(distance, time):
2 speed = distance / time
3 return speed
4
5# We can save the result to a variable
6result = calculate_speed(30, 4)
7print(f"Speed: {result} km/h") # Speed: 7.5 km/h
8
9# Or use it right away
10print(f"Speed: {calculate_speed(60, 3)} km/h")The 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.
Functions can contain everything you've learned - conditions, loops, operators:
1def is_dangerous(weight):
2 if weight > 1000:
3 return True
4 else:
5 return False
6
7print(is_dangerous(5000)) # True (elephant)
8print(is_dangerous(190)) # False (lion)Write a function that calculates how many days it takes to cover a given distance. Complete the code in the editor:
In this lesson you created your own explorer's tools:
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! 🎉🌴