Sometimes you need to make functions that take optional arguments. The best example is always middle names; some people have them, and some don’t. If we wanted to write a function that would print out properly for both situations, we would need to make the middle name an optional parameter. We do this by assigning an empty string value as the default:
# setting default parameter values def printName(first, last, middle=""):
if middle:
print( "{ } { } { }".format(first, middle, last) ) else:
print( "{ } { }".format(first, last) ) printName("John", "Smith") printName("John", "Smith", "Paul") # will output with middle name
CHapTeR 5 FUnCTIonS
Go ahead and run the cell. Whether you pass in a middle name or not, the function will run efficiently either way. Keep in mind the order of our parameters! Parameters must line up from left to right according to the function definition. If “Paul” was placed as the second value after “John” in the second call, then our function would assign “Paul” into the parameter “last.”
During the function call, you can explicity assign values into parameter names. This is useful when you don’t want to mix up the order of values being passed in, as they work from left to right by default. You can use parameter names to assign values for every parameter if you choose, but it’s not necessary most of the time. Let’s check out an example:
# explicity assigning values to parameters by referencing the name def addNums(num1, num2):
print(num2) print(num1) addNums(5, num2 = 2.5)
Go ahead and run the cell. Here, we explicity assign the value of num2 in the call using a keyword argument.
* args
The use of *args allows you to pass a variable number of arguments into a function. This allows you to make functions more modular. The magic isn’t the “args” keyword here though; it’s really the unary operator (*) that allows us to perform this feature. You could theoretically replace the word args with anyone, like “*data”, and it would still work. However, args is the default and general standard throughout the industry. Let’s see how we can use args in a function call:
# using args parameter to take in a tuple of arbitrary values def outputData(name, *args): print( type(args) ) for arg in args: print(arg) outputData("John Smith", 5, True, "Jess")
Go ahead and run the cell. You’ll notice that the args parameter takes in all values not assigned in the call as a tuple, as output with our first print statement. We then output each argument within that tuple. When you access the args parameter in the block, you do not need to include the unary operator. Notice that “John Smith” was not printed out. That’s because we have two parameters in the function definition, name and *args. The first argument in the function call is mapped to the name parameter, and the rest are inserted into the args tuple. This is a useful mechanism when you’re not sure how many arguments to expect.
Do'stlaringiz bilan baham: |