Sub topic 1
Defining and Calling Your First Function
Prerequisites
You should know variables, strings, numbers, lists, dictionaries, if statements, and calls to built-in functions such as print() and len().
Defining and Calling a Function
A function is a named block of reusable code. Define one with def, followed by its name, parentheses, and a colon. The indented body runs when you call the function.
def greet(name):
return f"Hello, {name}!"
message = greet("Ada")
print(message) # Hello, Ada!name is a parameter. It is the local name that receives input. "Ada" is an argument, the actual value supplied by the caller. The function call returns a string, which is stored in message.
Parameters and Arguments
Parameters define what a function expects. Arguments provide values for those parameters. A function can have several parameters:
def rectangle_area(width, height):
return width * height
area = rectangle_area(5, 3)
print(area) # 15Here, width and height are parameters. 5 and 3 are positional arguments because Python assigns them from left to right.
Sending Results Back with `return`
return ends the function and sends a value back to the caller. The caller can store, print, or use that value in another expression.
def is_adult(age):
return age >= 18
allowed = is_adult(20)
print(allowed) # TrueA function without return sends back None, Python’s value meaning “no result.” Printing inside a function is different from returning a value: printing displays text, while returning makes data available to the caller.
Passing Arguments by Position and by Keyword
You can pass an argument by position or by keyword. Keyword arguments name the parameter explicitly, which can make calls clearer.
def power(base, exponent=2):
return base ** exponent
print(power(5)) # 25
print(power(2, 10)) # 1024
print(power(base=2, exponent=3)) # 8exponent=2 is a default value. Python uses it when the caller omits that argument. Positional arguments must come before keyword arguments.
Exercise
What value does power(base=3) return, and why?
Show answer
It returns 9 because the omitted exponent uses its default value of 2.