I\'ve approached this question that I\'m struggling to solve. It\'s asking me to convert the code from \"for-loops\" to \"while-loops\":.
def print_names2(pe
@Martijn's answer works for the test case given (a sequence of sequences of names), but it is not (and as far as I know, has never been) equivalent to the original for loop code, which works with iterables of iterables of names. An example of the latter, that works with the for loops but not the while loops, is
def it_it_names():
yield ['John', 'Smith']
yield ['Mary', 'Keyes']
yield ['Jane', 'Doe']
Here is while-loop code that is essentially equivalent to the for loops.
def pn_while(people):
it = iter(people)
try:
while True:
person = next(it)
to_print = ""
it2 = iter(person)
try:
while True:
name = next(it2)
to_print += name + " "
except StopIteration:
pass
print(to_print)
except StopIteration:
pass
pn_while(it_it_names())
# prints
John Smith
Mary Keyes
Jane Doe
Before 2.2, the while loop equivalent would use indexing by 0, 1, 2, ... instead of next() and catch IndexError instead of StopIteration. At least as of 1.4, len() was not used to stop the loop.
It is perhaps worth noting that the body of the outer loop could be replaced with print(' '.join(person))
. The only difference would be to not add a space at the end.