Python Functions
A function is a named, reusable block of code that runs only when you call it, letting you organize logic and avoid repetition.
What is a function?
A function groups a set of statements under a single name so you can run them whenever you need to. Instead of copying the same lines in several places, you define the behavior once and call it as many times as you like. This keeps programs shorter, easier to read, and simpler to fix, because a change made inside the function takes effect everywhere the function is used.
Defining and calling a function
You create a function with the def keyword, followed by a name, a pair of parentheses, and a colon. The indented lines below the colon form the function body. Defining a function does not run it; the body executes only when you call the function by writing its name followed by parentheses.
Define once, call many times
def greet():
print("Welcome to the course!")
greet()
greet()
# Output:
# Welcome to the course!
# Welcome to the course!Returning a value
Many functions calculate a result and hand it back to the caller with the return statement. The returned value can be stored in a variable or used directly in an expression. When a function has no return statement, or reaches the end without one, it automatically returns the special value None.
Using return to send a value back
def square(number):
return number * number
result = square(5)
print(result) # 25
print(square(9) + 1) # 82Passing information in
The names listed inside the parentheses of a definition are called parameters. The actual values you supply when calling the function are called arguments. This lets one function work on different data each time it is called, which is what makes functions so flexible.
Exercise: Python Functions
Which keyword is used to define a function in Python?