如何将for循环转换为while循环?

时间:2016-03-30 05:42:57

标签: python

def print_names(names):

    """Print the names in the list of names, one per line"""

    for name in names:

        print(name)

print_names(['John', 'Mary', 'Donald'])

3 个答案:

答案 0 :(得分:1)

这是最直接的(有更短的方法,但这似乎最相同):

def print_names(names):
    i = 0
    while i < len(names):
        name = names[i]
        print(name)
        i += 1  # make sure to increment before any 'continue'

答案 1 :(得分:1)

通常,可以将任何for循环转换为等效的while循环,如下所示:

for X in Y:
    S

变为:

it = iter(Y)
try:
    while True:
        X = next(Y)
        S
    except StopIteration:
        pass

所以,你的程序变成了:

def print_names(names):
    """Print the names in the list of names, one per line"""
    it = iter(names)
    try:
        while True:
            name = next(it)
            print(name)
    except StopIteration:
        pass

print_names(['John', 'Mary', 'Donald'])

答案 2 :(得分:-1)

你可以简单地将for循环放在while循环中。

def print_names(names):

    """Print the names in the list of names, one per line"""

    running = True:
    while running:

        for name in names:

            print(name)

print_names(['John', 'Mary', 'Donald'])