Chapter Five: FUNCTIONS
5.1 Introduction to Functions
• A function in Python is a reusable block of code designed to perform a specific task.
• Functions in Python are defined using the def keyword followed by the function name
and parentheses that may contain input parameters.
• Functions can optionally return a value using the return statement.
• Functions help modularize code, making it easier to manage and debug.
5.1.1 Divide and Conquer
• Divide and Conquer is a problem-solving paradigm that breaks down a large task into
smaller, manageable subproblems.
• In Python, divide and conquer algorithms can be implemented using functions.
• Functions help in solving these subproblems individually and then combining their
solutions to solve the original problem.
5.1.2 Benefits of Using Functions
• Improved Readability & Maintainability: Functions help break down complex
programs into smaller chunks, making them easier to read and maintain.
• Reusability: Functions can be reused across different parts of a program, reducing
redundancy and making the code easier to test.
• Encapsulation: Functions allow hiding the internal details of the implementation and
expose only necessary interfaces to other parts of the program.
• Error Handling: Functions can return error codes or raise exceptions, making it easier to
handle errors.
• Improved Testing: Modular functions can be individually tested, improving the overall
testing process.
5.1.3 Defining and Calling a Function
• Function names must:
o Not use Python keywords
o Contain no spaces
o Start with a letter or an underscore
o Contain letters, numbers, or underscores
• A function is defined as follows:
• def function_name():
• # function body
• To call the function, simply use the function name followed by parentheses ().
• Example:
• def greet():
• print("Hello, world!")
• greet() # calling the function
5.1.4 Void Functions
• Void Function: A function that does not return a value.
• Typically used to perform actions such as printing results or modifying arguments.
• Example:
• def greet(name):
• print(f"Hello, {name}")
• greet("Alice")
5.1.5 Pausing Execution Until User Input
• The input() function can pause the program until the user presses Enter.
• input('Press Enter to continue...')
5.1.6 Using the pass Keyword
• The pass keyword acts as a placeholder for code that hasn’t been implemented yet or as
a syntactic placeholder where a statement is required but no action is needed.
• Example:
• def step1(): pass
• def step2(): pass
5.2 Local Variables
• Local variables are variables defined inside a function. They can only be accessed
within the function.
• They are not accessible outside the function.
• Example:
• def my_function():
• local_variable = 10
• print(local_variable)
• # Accessing outside the function results in an error
• print(local_variable) # Error: NameError
5.2 Passing Arguments to Functions
• Arguments are values passed to a function when it is called.
• Parameters are variables in the function definition that accept these arguments.
• Example:
• def show_double(number):
• print(number * 2)
• value = 5
• show_double(value) # Passing value as an argument
5.2.1 Parameter Variable Scope
• The scope of a parameter is the function in which it is defined. It can only be accessed
within that function.
5.2.2 Passing Multiple Arguments
• Positional Arguments: These are passed in the same order as the parameters are
defined in the function.
• Default Arguments: These arguments have default values if not provided by the caller.
• def greet(name, message="Hello"):
• print(f"{message}, {name}")
•
• greet("Alice") # Output: Hello, Alice
• greet("Alice", "Goodbye") # Output: Goodbye, Alice
5.2.3 Mixing Keyword Arguments with Positional Arguments
• Keyword Arguments: Arguments passed by explicitly naming the parameter and its
value.
• Example:
• def show_interest(principal, rate, periods):
• interest = principal * rate * periods
• print(f"Interest: {interest}")
• show_interest(1000.0, rate=0.01, periods=10)
5.3 Global Variables and Constants
5.3.1 Global Variables
• Global variables are defined outside functions and can be accessed anywhere in the
program.
• To modify a global variable inside a function, use the global keyword.
5.3.2 Global Constants
• Global constants are variables whose values should not change. These are typically
written in all uppercase letters with underscores separating words.
• Example:
• PI = 3.14159 # Global constant
5.3.3 Limitations of Global Variables
• Over-reliance on global variables can lead to difficult debugging and understanding of
the program.
• Global variables make the program less modular and harder to maintain.
5.4 Value-Returning Functions
• Value-returning functions return a value to the caller using the return keyword.
• Example:
• def sum_numbers(a, b):
• return a + b
• result = sum_numbers(3, 5)
• print(result) # Output: 8