Core Python / Functions#
What is the purpose of a function in Python? Provide an example of when you might use a function. A function is a block of code that performs a specific task. Functions help in modularizing code, improving code readability, and promoting code reusability. Functions take inputs (arguments), perform some operations on them, and then return outputs.
What are the different parts of a function in Python?
function name, parameter list, and code block
How do you call or invoke a function in Python? Provide an example.
Use the function’s name followed by parentheses (). If the function accepts arguments, provide them inside the parentheses.
def greet(name): """This function greets the person with the given name.""" print("Hello, " + name + "!") # Call the function greet("John")
What is the difference between a function parameter and a function argument? Give an example of each.
In programming, the terms “parameter” and “argument” are often used interchangeably, but they do have distinct meanings:
Parameter: A parameter is a variable declared in the function definition and represents the data that a function receives when called. Parameters are placeholders for the actual values (arguments) that will be passed into the function during its invocation. Parameters are defined within the parentheses in the function header.
Argument: An argument is the actual value that is passed to the function when it is called - what’s supplied to a function’s parameters.
# Example of a function with multiple parameters def add(a, b): # 'a' and 'b' are the parameters """This function adds two numbers.""" return a + b # Example of calling the function with arguments result = add(3, 5) # 3 and 5 are the arguments passed to the 'a' and 'b' parameters print("Result:", result) # Output: Result: 8
How does a function send result(s) back to the caller? What statement is used? When should it be used and what occurs? When is that statement optional?
A function sends the result back to the caller by using the
return
statement followed by a value. Mutiple values may be returned by separating those values with a comma. (Implicitly, a tuple is created and returned containing the values). It should be used when the result is ready and no further processing/computation is needed.The statement is optional when no value is required to be returned.
If a function exits in Python without a return, what value does the caller receive (if any)?
Implicitly, the special value
None
will returned to the caller if there is no explicit return or if the return statement does not contain a value.The
None
keyword defines a null value (or no value at all).None
is not the same as 0,False
, or an empty string.None
has a type of “NoneType”.Explain the concept of variable scope in Python functions. What is the difference between local and global variables?
Variable scope refers to the region of a program where a particular variable is accessible. In Python functions, variables can have different scopes, mainly local and global.
Local Variables:
Local variables are defined within a function and can only be accessed within that function.
They are created when the function is called and are destroyed when the function completes execution.
Local variables cannot be accessed from outside the function.
Attempting to access a local variable outside its scope will result in a NameError.
def my_function(): x = 10 # This is a local variable print("Inside function:", x) my_function() # Trying to access the local variable outside the function will result in an error print("Outside function:", x) # This line will cause a NameError
Global Variables:
Global variables are defined outside of any function and can be accessed throughout the program, including inside functions.
They are accessible from any part of the program, both inside and outside functions.
If a variable is assigned a value within a function without being declared as
global
, Python will create a new local variable with the same name, which shadows the global variable within the function’s scope.To modify a global variable within a function, you need to use the
global
keyword to declare it as global.
x = 10 # This is a global variable def my_function(): global x # Declare 'x' as global to modify it within the function x = 20 # Modifying the global variable print("Inside function:", x) my_function() print("Outside function:", x) # Accessing the modified global variable
What are default parameter values in Python functions? Provide an example of how to define and use them.
Default parameter values allow you to specify a default value for a parameter in a function. If the caller of the function doesn’t provide a value for that parameter, the default value will be used. As Python does not provide function overloading, these default parameters provide some of the missing capability.
def greet(name="Guest"): """This function greets the person with the given name.""" print("Hello, " + name + "!") # Calling the function without providing any arguments greet() # Output: Hello, Guest! # Calling the function with an argument greet("Alice") # Output: Hello, Alice!
What is the purpose of a docstring in a Python function? How do you write a docstring, and what are the conventions?
A docstring (documentation string) describes what a function does, including information about its parameters, return values, and any side effects it may have. Docstrings help developers understand how to use the function correctly and are particularly useful for code readability and maintainability.
To write a docstring in Python, you simply add a string literal as the first statement in the function body. Conventionally, docstrings are enclosed in triple quotes (“”” “””) to allow for multiline descriptions.
Several conventions are available. For the FinTech program, we have adopted Google’s: google/styleguide
What is the difference between printing a value and returning a value?
Printing a value and returning a value are two different ways of communicating information from a function in Python.
Printing a value involves displaying it on the console or standard output using the print() function.
Printing is primarily used for debugging purposes or for providing information to the user.
Printed values are not directly accessible to other parts of the program; they are simply displayed on the console.
whereas
Returning a value involves specifying a value to be sent back to the caller of the function using the return statement.
Returned values are accessible to the caller, and they can be stored in variables or used in other expressions.
Returning values allows functions to compute results that can be further processed or manipulated by other parts of the program.