简体   繁体   English

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

[英]Unexpected output in Python while executing simple loop

I have this rather simple loop我有这个相当简单的循环

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 * '#')

I expect it to break.我希望它打破。 However, what I did not expect is this output.然而,我没想到的是这个输出。

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
....

Where is the none coming from? none来自哪里? I do not print this, nor do I execute something where I'd expect this to be printed...我不print这个,也不执行我期望打印的东西......

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

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

因为你有 2 个打印命令

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

in the above line you are printing print functions output.在上面的行中,您正在打印打印功能输出。

If you look at function Def it doesn't have a return type so you are getting None from the inner print() statement.如果您查看函数 Def,它没有返回类型,因此您将从内部print()语句中获得None

Also a remark - fix the index check for index > len(countries)另请注意- 修复index > len(countries)index检查

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM