Defining and Calling Functions
- Definition: A function is a block of reusable code that performs a specific task. Functions help in organizing code and avoiding repetition.
- Syntax: python
def function_name(parameters): # code block return value - Example: python
def greet(name): return f"Hello, {name}!" print(greet("Alice"))- Explanation: The
defkeyword is used to define a function.greetis the function name, andnameis the parameter. The function returns a greeting message.
- Explanation: The
Function Arguments and Return Values
- Arguments: Values passed to a function when it is called. They can be positional or keyword arguments.
- Positional Arguments: Passed in the order they are defined.
- Keyword Arguments: Passed with the parameter name, allowing out-of-order passing.
python
def add(a, b): return a + b print(add(2, 3)) # Positional print(add(b=3, a=2)) # Keyword - Return Values: The value that a function returns using the
returnstatement. If no return statement is used, the function returnsNone. pythondef square(x): return x * x result = square(4) print(result) # Output: 16