Quest 1 • Lesson 6
📞 Functions
A function is a reusable block of code that performs a specific task. You define it once and call it many times. Functions help you avoid repetition and organise your code better.
"Functions are like recipes – you write the steps once, then you can follow them whenever you need the result."
function_basic.py
def greet():
print("Hello, world!")
# Call the function
greet()
print("Hello, world!")
# Call the function
greet()
🧠 Function Basics
def– keyword to define a function.greet– function name (use descriptive names).()– parentheses for parameters (can be empty).- Indented block – the code that runs when the function is called.
function_parameters.py
def greet_person(name):
print(f"Hello, {name}!")
greet_person("Alice") # Output: Hello, Alice!
print(f"Hello, {name}!")
greet_person("Alice") # Output: Hello, Alice!
function_return.py
def add(a, b):
return a + b
result = add(5, 3)
print(result) # Output: 8
return a + b
result = add(5, 3)
print(result) # Output: 8
📤 Return Values
return– sends a value back to the caller.- If no
returnis used, the function returnsNone. - You can store the returned value in a variable.
✨ Challenge: Create a Multiplication Function
Write a function multiply(a, b) that returns the product of two numbers. Then call it with 4 and 7, and print the result.
def multiply(a, b):
return a * b
result = multiply(4, 7)
print(result) # 28
✨ Bonus Challenge: Celsius to Fahrenheit
Define a function celsius_to_fahrenheit(celsius) that returns the temperature in Fahrenheit. Formula: F = C × 9/5 + 32. Test it with 0 and 100.
def celsius_to_fahrenheit(celsius):
return celsius * 9/5 + 32
print(celsius_to_fahrenheit(0)) # 32.0
print(celsius_to_fahrenheit(100)) # 212.0
return celsius * 9/5 + 32
print(celsius_to_fahrenheit(0)) # 32.0
print(celsius_to_fahrenheit(100)) # 212.0
❤️ Support Free Education
This course is 100% free. If it helps you, consider buying me a coffee.
☕ Buy Me a Coffee➡️ Ready for more?
Next lesson: String Methods & Formatting.
Continue to Lesson 1.7 →(Coming soon – check back or buy Pro Pack for instant access)