2016-03-30 15 views
-2
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']) 
+1

なぜそれをしたいですか?これは問題ありません。 – Evert

+1

さて、 'while names:print names.pop(0)'と言うと、リストが使い捨てであると仮定していますが、なぜこれをしたいのでしょうか?リストを反復することは、 'for'ループを使用する自然な場所です。 –

答えて

-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']) 
+0

'print_names'は無限ループです。それは決して戻ってこない。 –

+0

が無限に指摘されていますが、あなたがまだforループを持っていることを修正したとしても、OPの意味ではないと思います。 – schwobaseggl

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' 
+0

トップに 'name = names [i]'と言っていいかもしれないので、残りのループボディをリファクタリングする必要はありません –

+0

@JohnLaRooy私はあなたのポイントを見て調整しました。 – schwobaseggl

+0

誰かがループ本体で 'continue'を使うことを考えてみましょう。 'i'はインクリメントされません。ループの最初の行の後に 'i'を使用しなくなったので、ループの2行目にインクリメントを移動することができます –

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']) 
関連する問題