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
You are forgetting to index into people
again; you are printing just the index. You also want to loop over all entries in people
not just the names in the first sub-list:
def print_names2(people):
i = 0
while i < len(people):
print(people[i])
i += 1
This only loops over the outer list. If you want to loop over the inner sublists, add a second while
loop:
def print_names2(people):
i = 0
while i < len(people):
j = 0
while j < len(people[i])
print(people[i][j])
j += 1
i += 1
All this prints the names directly, and all names will end up on new lines rather than each sublist printed on one with a space in between. If you needed to replicate the string building, do so and not print until the inner while
loop has ended:
def print_names2(people):
i = 0
while i < len(people):
to_print = ""
j = 0
while j < len(people[i])
to_print += people[i][j] + " "
j += 1
print(to_print)
i += 1
This now is closest to the original version with the for
loops.
An alternative version could create copies of the lists and then remove items from those lists until they are empty:
def print_names2(people):
i = 0
while i < len(people):
person = list(people[i])
to_print = ""
while person:
name = person.pop(0)
to_print += name + " "
print(to_print)
i += 1
I left the outer loop using an index.
Maybe here's what you want:
def print_names(people):
while people:
p = people.pop()
n = ''
while p:
n += p.pop() + ' '
print n
@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.