Dan Dan -3 years ago 201
Python Question

Clarification on what the author meant (Learning Python 5th Edition)

Link 1

Link 2

The author seems to be implying that the variant with (first, *rest) as the input arguments wouldn't work with files but after experimenting with it, I found that it does work.

# Code I tried:
def mysum(first, *rest):
return first if not rest else first + mysum(*rest)


mysum(*open("script1.py"))
works fine.

I think
mysum(open("script1.py"))
won't work because that what python would then see is
first = open("script1.py
and
rest = []
which means it's gonna give me the
<_io.TextIOWrapper name='script1.py' mode='r' encoding='cp1252'>
because not
[]
is true.

Answer Source

The author wants a function that takes an iterable (e.g. a list, tuple, etc) as input and returns the sum, e.g. like this:

mysum(open("script1.py"))

When you write

mysum(*open("script1.py"))

This is roughly equivalent to

f = open("script1.py").readlines()
mysum(f[0], f[1], ..., f[n])

Note that here your code does not take an interable as input, instead it takes several separate arguments which is not what the author wanted.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download