Functions are blocks of reusable code that perform a specific task. They help you avoid repetition and make your code more organized and readable. In Python, you can define a function using the def
keyword.
Example: Greeting Function
def greet(name):
print(f"Hello, {name}!")
This function takes a name
as input and prints a greeting.
Defining and Calling Functions
To define a function, use the def
keyword followed by the function name and parentheses. You can also include parameters inside the parentheses. To call a function, simply use its name followed by parentheses.
Example: Adding Numbers
def add(a, b):
return a + b
result = add(5, 10)
print(f"The sum is {result}.") # Output: The sum is 15.
Parameters and Return Values
Functions can take parameters (inputs) and return values (outputs). Parameters allow you to pass data into the function, while return values allow the function to send data back to the caller.
Example: Area Calculator
def calculate_area(length, width):
return length * width
area = calculate_area(5, 10)
print(f"The area is {area} square units.") # Output: The area is 50 square units.
Conclusion
Functions are a fundamental concept in Python programming. By writing reusable functions, you can make your code more efficient and easier to maintain. Practice creating your own functions and experiment with different parameters and return values.