Passing a Single Parameter
Let’s use the example from Figure 5-3 to create our first function that accepts a parameter:
# passing a single parameter into a function def printName(full_name): print( "Your name is: { }".format(full_name) ) printName("John Smith") printName("Amanda")
Go ahead and run the cell. We’ll get two different outputs here that use the same function. Parameters allow us to pass different information for each call.
Multiple Parameters
The preceding example passes a string data type into a function, so let’s check out how to pass numbers and create a nicely formatted print statement:
CHapTeR 5 FUnCTIonS
# passing multiple parameters into a function def addNums(num1, num2): result = num1 + num2 print( "{ } + { } = { }".format(num1, num2, result) ) addNums(5, 8) # will output 13 addNums(3.5, 5.5) # will output 9.0
Go ahead and run that cell. Our function definition is expecting two numbers to be passed into the parameters num1 and num2. Within the function block, we reference these values passed in by their argument names.
Passing a List
Passing around a large amount of data is usually easiest when it is stored in a list. For that reason, functions are great at performing repetitive tasks on lists. Let’s see an example:
# using a function to square all information numbers1 = [ 2, 4, 5, 10 ] numbers2 = [ 1, 3, 6 ] def squares(nums): for num in nums:
print(num**2) squares(numbers1) squares(numbers2)
Go ahead and run the cell. You can see that it will output all the numbers squared. This is much more efficient than writing the for loop twice for each list. This is the beauty of functions and passing in parameters.
Note Remember that nums is an arbitrary name and is the variable that we reference within the function block.
Default Parameters
In many situations, a parameter can be associated with a default value. Take the value of pi for instance; it will always be 3.14, so we can set a parameter called pi to that exact value. This allows us to call the function with an already defined value for pi. If you wanted to have a more concise value for pi you could, but generally 3.14 is good enough:
# setting default parameter values def calcArea(r, pi=3.14): area = pi * (r**2) print( "Area: { }".format(area) ) calcArea(2) # assuming radius is the value of 2
Go ahead and run the cell. Now we can run the function without needing to pass a value for pi. Default parameters MUST always go after non-default parameters. In this example the radius must be declared first, then pi.
Do'stlaringiz bilan baham: |