Arguments

1. Explain the difference between parameter and arguments.
  • Parameters are part of the definition of the function. The number of inputs to the functions.
  • Arguments are the values you set to the parameters.
2. Explain default arguments.

Default values can be assigned to parameters in a function. If a value is not provided for a parameter during the function call, the default value is used. Which makes them optional when the function is called.

def greet_name(name='Bob'):
    print(f"Hi {name}")

greet_name() # Hi Bob
3. Explain positional arguments.

The first value will be assigned to the first argument. The order of argument value inputs matters.

def greet_name(name):
    print(f"Hi {name}")

greet_name('Lisa') # Hi Lisa 
4. Explain keyword arguments.

When calling the function, we can explicitly specify which parameter each value corresponds to by using the parameter names.

def greet_name(name):
    print(f"Hi {name}")

greet_name(name='Lisa')# Hi Lisa 
5. Explain the arbitrary arguments *args and **kwargs.
  • *args: To take in variable amount of remaining positional arguments.
  • **kwargs: To take in variable amount of the remaining keywords arguments.
6. Use *args to create a function to print the arguments passed in.
# *args for variable number of arguments
def myFunc(*argv):
	for arg in argv:
		print (arg)
  
myFunc(1,2,3,4)
## Outputs
# 1
# 2
# 3
# 4 
7. Use **kwargs to create a function to print the key-value argument pairs passed in.
# *kwargs for variable number of keyword arguments
def myFunc(**kwargs):
	for key, value in kwargs.items():
		print (key, 'is', value)

myFunc(one=1, two=2, three=3)
## Output
# one is 1
# two is 2
# three is 3
8. Explain the term Pass By Object Reference when calling a function with an argument.
When you pass a variable to a function, you are passing the reference (memory address) to the object that variable points to, not the actual object.
9. What are the implications of passing by an object reference, when the object is mutable?
Any operations performed by the function on the variable/object will modify the internal state (data) of the object.
10. What are the implications of passing by an object reference, when the object is immutable?
Changes made inside the function create new objects, and the original object’s internal state (data) remains unchanged.
Last updated on 19 Nov 2023