Functions in Python
Lesson Introduction
Welcome to the lesson on recalling functions in Python. Functions are fundamental building blocks that allow for code modularity, reusability, and better organization. Understanding functions helps you write cleaner and more maintainable code.
The goal of this lesson is to refresh your memory on defining and calling functions effectively in Python.
Functions: Declaration and Definition
In Python, a function is defined directly using the def keyword. There is no need for a separate declaration step. This makes defining and using functions straightforward and efficient.
A function definition provides the function's actual body and specifies what the function does when it is called. Functions can receive any number of arguments separated by commas.
Consider these function definitions in our code snippet:
The add function returns the sum of the two input parameters, while the greet function prints a greeting message. The pass statement in the if __name__ == "__main__": block indicates an empty block of code that does nothing. It acts as a placeholder.
Using Functions
Once functions are defined, they can be called from the main body of the script or any other function.
Calling a function involves specifying the function name followed by arguments in parentheses. If a function does not have a return statement, it returns None by default.
In our code snippet, we call the add function from the main body:
Here, add(2, 3) returns 5, and add(2.5, 3.5) returns 6.0. The results are then printed using print(). The greet("Alice") function doesn't return anything useful, so we call it without assigning its result to a variable.
As a reminder, if __name__ == "__main__": is a special block in Python that ensures certain code runs only when the script is executed directly, not when it's imported as a module in another script. It is considered a good practice to include this in your Python scripts.
