执行简单循环时Python中出现意外输出



我有一个相当简单的循环

cities = ['Merano', 'Madrid', 'New York', 'Bangkok']
countries = ['Italy', 'Spain', 'USA']
for index, city in enumerate(cities):
print('This is index:', index)
print('This is city:', city)
print('The length of the list 'cities' is: ', len(cities))
print(print('The length of the list 'countries' is: ', len(countries)))
print(countries[index])
print(5 * '#')

我希望它能坏掉。然而,我没有想到的是这个输出。

This is index: 0
This is city: Merano
The length of the list 'cities' is:  4
The length of the list 'countries' is:  3
None
Italy
#####
This is index: 1
This is city: Madrid
The length of the list 'cities' is:  4
The length of the list 'countries' is:  3
None
Spain
....

none从哪里来?我不print这个,也不执行我希望打印的东西。。。

您在print(print('The length of the list 'countries' is: ', len(countries)))中使用了print(print(使用

print('The length of the list 'countries' is: ', len(countries))`

因为您有两个打印命令

print(print('The length of the list 'countries' is: ', len(countries)))
print(print('The length of the list 'countries' is: ', len(countries)))

在上面的行中,您正在打印打印功能输出。

如果您查看函数Def,它没有返回类型,因此您从内部print()语句中获得None

还有备注-修复index > len(countries)index检查

最新更新