About Lesson
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
def
keyword is used to define a function.greet
is the function name, andname
is 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
return
statement. If no return statement is used, the function returnsNone
. pythondef square(x): return x * x result = square(4) print(result) # Output: 16