PRO511-Chapter 5 Lecture Notes
PRO511-Chapter 5 Lecture Notes
• Functions in Python are defined using the def keyword followed by the function name
and parentheses that may contain input parameters.
• Divide and Conquer is a problem-solving paradigm that breaks down a large task into
smaller, manageable subproblems.
• Functions help in solving these subproblems individually and then combining their
solutions to solve the original problem.
• 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.
o Contain no spaces
• def function_name():
• # function body
• To call the function, simply use the function name followed by parentheses ().
• Example:
• def greet():
• print("Hello, world!")
• Example:
• def greet(name):
• print(f"Hello, {name}")
• greet("Alice")
• The input() function can pause the program until the user presses Enter.
• 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:
• Local variables are variables defined inside a function. They can only be accessed
within the function.
• Example:
• def my_function():
• local_variable = 10
• print(local_variable)
• Parameters are variables in the function definition that accept these arguments.
• Example:
• def show_double(number):
• print(number * 2)
• value = 5
• The scope of a parameter is the function in which it is defined. It can only be accessed
within that function.
• 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.
• print(f"{message}, {name}")
•
• Keyword Arguments: Arguments passed by explicitly naming the parameter and its
value.
• Example:
• print(f"Interest: {interest}")
• Global variables are defined outside functions and can be accessed anywhere in the
program.
• Global constants are variables whose values should not change. These are typically
written in all uppercase letters with underscores separating words.
• Example:
• Global variables make the program less modular and harder to maintain.
• 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