5.9. Parameters and arguments¶
Some of the built-in functions we have seen require arguments. For
example, when you call math.sin
, you pass a number as an
argument. Some functions take more than one argument:
math.pow
takes two, the base and the exponent.
Inside the function, the arguments are assigned to variables called parameters. Here is an example of a user-defined function that takes an argument:
def print_twice(bruce):
print(bruce)
print(bruce)
This function assigns the argument to a parameter named
bruce
. When the function is called, it prints the value of
the parameter (whatever it is) twice.
This function works with any value that can be printed.
Activity: CodeLens 5.9.2 (functParam_codelens1)
The same rules of composition that apply to built-in functions also
apply to user-defined functions, so we can use any kind of expression as
an argument for print_twice
:
Activity: CodeLens 5.9.3 (functParam_codelens2)
The argument is evaluated before the function is called, so in the
examples the expressions 'Spam '*4
and math.cos(math.pi)
are only evaluated once.
You can also use a variable as an argument:
Activity: CodeLens 5.9.4 (functParam_codelens3)
The name of the variable we pass as an argument (michael
)
has nothing to do with the name of the parameter (bruce
).
It doesn’t matter what the value was called back home (in the caller);
here in print_twice
, we call everybody bruce
.
- 67 (on the same line)
- Incorrect! In Python, each print statement automatically adds a new line after printing whatever is inside the print statement. Try again.
- 67 (on two separate lines)
- Correct! Even though the variable "hi" was changed in the functions, its value outside the functions remains the same, and print statements automatically add a new line.
- 69 (on two separate lines)
- Incorrect! Even though the variable "hi" was changed in the functions, its value outside the functions remains the same unless specified. Try again.
- 69 (on the same line)
- Incorrect! In Python, each print statement automatically adds a new line after printing whatever is inside the print statement. Try again.
Q-5: Consider the code block below. What prints?
def add_two(num):
num = num + 2
print(num)
def add_three(nums):
nums = nums + 3
print(nums)
hi = 4
add_two(hi)
add_three(hi)
Construct a block of code with four functions, defined in this order: printName, printGPA, printAttendance, printStudentInfo. printStudentInfo should call the other three functions which will print all of the student’s information. Be mindful of indentation!