Lesson 4.1: Defining Functions and Function Arguments
Introduction:
Functions in Python are reusable blocks of code that perform a specific task. Using functions helps make programs organized, modular, and easier to maintain. This lesson covers how to define functions, pass arguments, and return values.
1. Defining a Function:
-
Use the
defkeyword to define a function. -
Syntax:
Example – Simple Function:
Output:
2. Function Arguments:
-
Arguments allow passing data into functions for processing.
Example – Function with Arguments:
Output:
3. Returning Values from Functions:
-
Use
returnto send a value back to the caller.
Example – Function Returning Value:
Output:
4. Types of Function Arguments:
-
Positional Arguments: Values passed in order.
-
Keyword Arguments: Values passed by specifying parameter names.
-
Default Arguments: Parameters with default values.
-
Variable-length Arguments: Using
*argsfor multiple values and**kwargsfor key-value pairs.
Example – Default Argument:
Practical Tips:
-
Keep functions short and focused on a single task
-
Use descriptive function and parameter names
-
Avoid unnecessary global variables; prefer passing data through arguments
Learning Outcome of This Lesson:
-
Understand how to define and call functions in Python
-
Use arguments to pass data into functions
-
Return values from functions to use results
-
Apply different types of arguments effectively
-
Write modular and reusable code using functions
