Keyword arguments and print()
Normally, we will call the print()
function like this:
print('hello')
or
number = 5
print(number)
You can even give print()
multiple things to print:
name = 'Sarah'
course = 'CS110'
grade = 'A'
print(name, course, grade)
This will print the values of all arguments, separated by a space:
Sarah CS110 A
Positional arguments
The examples above all use positional arguments, meaning the position matters. For example, we might define a function:
def compute(a, b, c):
return (a + b) * c
The position of these arguments matters! If I call this function:
result = compute(3, 4, 5)
then result
will be (3 + 4) * 5 = 35
. However, if we instead call it like
this:
result = compute(5, 4, 3)
then result
will be (5 + 4) * 3 = 27
.
Keyword arguments
Some functions take keyword arguments, meaning their value is defined by a
keyword instead of their position. One function that works this way is print
:
name = 'Sarah'
course = 'CS110'
grade = 'A'
print(name, course, grade, sep=',')
Here, we give sep
as a keyword argument, where sep
stands for separator —
any characters you want printed between the positional arguments. The default,
when you don’t provide the sep
argument, is a single space.
However, if you use sep='a'
then print()
will use a
as a separator. This
is how you use a keyword argument — you specify its keyword, use an =
, and
then give its value.
In the code above, we tell print()
to use a comma as the separator, so this
code will print:
Sarah,CS110,A
Using a comma as a separator when printing data is nice — you can create CSV files that programs like Excel can read. Python also has a variety of libraries that can read CSV files and create plots.
The print()
function also takes end
as a set of characters you want to end
each line with. By default each line is ended with a newline (n
). But we could
change that:
name = 'Sarah'
course = 'CS110'
grade = 'A'
print(name, course, grade, end='**')
This will print:
Sarah CS110 A**
Multiple keyword arguments
You can use as many keyword arguments as the function supports. Since print()
allows both sep
and end
, we can list both of them, in any order we prefer,
as long as they come after any positional arguments.
name = 'Sarah'
course = 'CS110'
grade = 'A'
print(name, course, grade, sep=', ', end='**')
This will print:
Sarah, CS110, A**
You can use keyword arguments with functions you write
We will show you how to do this later. :-)