2017-10-11 14 views
0
friends = ['Masum','Pavel','Sohag'] 
print(friends[1]) # this one gives me the result 'Pavel' 

for friends in friends: 
    print('Happy new yers,', friends) 

print(friends[1]) # Why this one give me the result o 
+6

ループ変数 'friends' - ' 'でリスト 'friends'をシャドーイングしたので、あなたは'' Sohag '[0] 'を取得しています。友人のために 'のための'を試してください:... '代わりに。 – jonrsharpe

答えて

0

リストの名前の友人と文字列の名前を使用したので、変数の友人があなたのforの最後に['Masum'、 'Pavel'、 'Sohag']から 'Sohag'に変更されました。これはただのためにあなたを変更する修正するには

:友人の中に友人のため

0

friend in friendsを試してみてください。あなたはちょうどfriendsをイテレータの同じ名前で上書きします。

0

反復のためのリストと同じ変数名を使用しないでください:

friends = ['Masum','Pavel','Sohag'] 

for friend in friends: 
    print('Happy new yers,', friend) 

# At this point friend will be the last one while friends will still be the list you assigned 
1

あなたが書くとき:

for friends in friends: 

あなたは再割り当てラベルfriendsこの内の項目にアレイ。 ループの完了後、配列には名前がなく、したがって失われます。ただし、ラベルfriendsはその配列の最後の値を格納します。例: (->手段 'にポイント')値 'Sohag' で1つの変数のみ今があること

Before iteration: friends -> array 
Ist iteration: friends -> 'Masum' 
2nd iteration: friends -> 'Pavel' 
3rd iteration and after loop completion: friends -> 'Sohag' 

注意。他のすべての変数/配列は失われます。

関連する問題