Functions are the building blocks of any programming language, and mastering them is crucial for writing clean and maintainable code. Once defined, a function can be called repeatedly without rewriting the same code over and over again.
By organizing your code into functions, you make it more readable and maintainable. Imagine writing the same calculation code multiple times—functions allow you to write it once and use it wherever needed.
def greet(name):
print(f"Hello, {name}!")
The following function takes a name as an argument and prints a greeting message
def function_name(parameter):
# code block
return value
def greet(name):
print(f"Hello, {name}!")
This is a simple function definition with:
- def keyword to define a function
- Function name: greet()
- Parameter: name (enclosed in parentheses)
- Code block: indented under the function definition
- return statement: executes the code and sends the result back
| Parameter | Argument | A parameter is a variable declared in the function definition that receives values | An argument is an actual value given when calling the function |
|---|
def calculate_sum(num1, num2):
return num1 + num2
The following function takes two numbers as arguments and returns their sum
calculate_sum(5, 3)
When you call this function with arguments 5 and 3, it will return 8
def greet(first_name, last_name=None):
if last_name is None:
print(f"Hello, {first_name}!")
else:
print(f"Hello, {first_name} {last_name}!")
This function accepts two parameters: first_name and last_name (with a default value of None)
return statement
The function will return a value based on the logic implemented within it
In this reading, you've learned:
Functions are one of the most powerful tools in Python programming. Practice defining, calling, and using functions with different arguments to become comfortable with this concept.