TOPIC 4: Functions & Code Documentation
Completion requirements
2. Function Parameters and Return Values
Functions can accept parameters and return values.
- Parameters: These are values passed into the function when called. Parameters allow the function to operate on different data each time it is called.
- Return Values: Functions can send a value back to the caller using the return keyword. The return statement allows you to output a result from the function.
Example 1: Function with Multiple Parameters
def multiply(x, y):
return x * y
result = multiply(4, 5)
print(result) # Output: 20
Explanation:
- The function multiply(x, y) takes two parameters, x and y, multiplies them, and returns the result.
- The function is called with the arguments 4 and 5, and the result is stored in result.
Example 2: Function with Default Parameters
Functions can have default values for parameters, which are used if no value is passed when calling the function.
def greet(name="Guest"):
print(f"Hello, {name}!")
greet("Alice") # Output: Hello, Alice!
greet() # Output: Hello, Guest!
Explanation:
- The function greet(name="Guest") has a default value for the name parameter.
- If no argument is passed to greet(), it defaults to "Guest". If an argument is passed (e.g., "Alice"), it uses that value.