Fancy Tricks with Functions
Consider the print
function. It is a highly
flexible and powerful too for formatting text. Let's take a look
at its header.
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
Much appears to be mysterious, but we will whittle that right down.
Python functions have three types of arguments. All of the functions we have written so far use positional arguments. These are so-named because they are passed to the function's parameters in order. Consider this example.
def foo(x,y):
return x + 3*y
print(plus(2,3))
The memory address where 2 is stored is passed to x
and the memory address where 3 is stored is passed to y
. The
order of the arguments is critical. Hence the name "positional."
Starguments The first argument to print
is
*objects
; this is a stargument. You can pass a
comma-separated list of arguments to a stargument and it will neatly package
them into a list. The print
function uses a loop to print out the
objects.
>>> print(1,"cat", True, [1,2,3])
1 cat True [1, 2, 3]
This facility is avaiable to you. There is one catch: You are allowed one stargument and it must come after any positional arguments.
Here is a very simple example.
def product(*x):
out = 1
for in x:
out *= k
return out
print(product(2,3,4,5)) # x -> [2,3,4,5]
print(product()) # x -> []
The comma-separated sequence 2,3,4,5 is packaged into a list
and the variable x
is a local variable in the function
product
that points at this list.
Here is a nifty trick if you want to require at least one argument. Just put a positional argument at the beginning. You can requre several arguments by placing several positional arguments at the beginning of the function's parameter list.
def product(a, *x):
out = a
for in x:
out *= k
return out
print(product(2,3,4,5)) # x -> [3,4,5] a ->2
print(product()) # x -> [] This fails, becase there is no a.
If you think about it for a moment, you can see why starguments only come after positional arguments and why you can only have one.
Keyword Arguments You have used these with
print
. If you look at this header, you will see that
print
has several keyword arguments. Each is given
a default value.
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
sep
This goes in between the items printed out.end
This goes at the end after print has done its job.file
This is the file object you want print to place its output in. By default, it'ssys.stdout
, or the screen.flush
This causes the OS to finalize writing to a file.
You can have keyword arguments in your functions. If you don't pass a keyword argument, the default is used.
def print_case(*x, caps=False):
if caps:
for k in x:
print(str(k.upper()))
else:
for k in x:
print(str(k))
print_case("a", "bcd", "efg", caps=True)
print_case("a", "bcd", "efg")