Define and use procedures and functions, with or without parameters
📚 Programming: Procedures & Functions
What is a Procedure?
A procedure (also called a subroutine) is a block of code that performs a specific task but does not return a value. Think of it as a recipe that tells the computer how to bake a cake, but it doesn’t give you the cake itself.
What is a Function?
A function is similar to a procedure, but it returns a value after execution. It’s like a vending machine: you give it coins (arguments) and it gives you a snack (return value).
Parameters & Arguments
Parameters are placeholders in a procedure/function definition. Arguments are the actual values you pass when you call it.
- Procedure example:
def greet(name): - Function example:
def add(a, b):
Return Values
Only functions can return values. Use the return statement to send data back to the caller.
Example: return a + b sends the sum of a and b back.
Comparison Table
| Feature | Procedure | Function |
|---|---|---|
| Returns a value? | No | Yes |
| Can be called anywhere? | Yes | Yes |
| Typical use? | Perform actions (e.g., print) | Calculate and return data |
Example: Calculating the Area of a Circle
We’ll write a function that takes the radius as a parameter and returns the area.
def circle_area(radius):
"""Return the area of a circle with the given radius."""
pi = 3.14159
return pi * radius * radius
Usage:
r = 5
area = circle_area(r)
print(f"The area of a circle with radius {r} is {area:.2f}")
Mathematically: $A = \pi r^2$
Practice Problems
- Write a procedure
print_hellothat prints “Hello, world!”. - Write a function
multiply(a, b)that returns the product of two numbers. - Write a function
fahrenheit_to_celsius(f)that converts a temperature from Fahrenheit to Celsius. - Write a procedure
display_menu()that prints a simple menu of options. - Write a function
is_even(n)that returnsTrueifnis even, otherwiseFalse.
Summary
Procedures are like recipes that perform actions; functions are like vending machines that return a value. Both use parameters to accept input, but only functions use return to send data back. By mastering these concepts, you’ll be able to write cleaner, reusable code and solve problems more efficiently. 🚀
Revision
Log in to practice.