names = ['Alan','Ivan','Jodi','Macy','Peng']
# This will print whatever is assigned to `names` for the number of times `names` is iterated
for a in names:
print(names)
# You're using same variable name for printing
for names in names:
print(names)
Extra Note: As @buran stated: This is valid, but not desirable to use,
because at the end value of names will be the last element in the
list, not the original list names
输出:
Alan
Ivan
Jodi
Macy
Peng
最后:
# This is what you need i.e. for each name in names, print the name
for name in names
print(name)
输出:
现在:
输出:
最后:
输出:
这是因为您使用相同的变量
name
进行打印。你知道吗尝试:
在for循环中,您将每个迭代值存储在变量中,而在print语句中,您将引用保存所有值的names变量。这就是它在同一行打印所有值的原因:
更改代码
与
相关问题 更多 >
编程相关推荐