开发者

Disregarding python variables [duplicate]

This question already has answers here: Closed 11 years ago.

Possible 开发者_运维百科Duplicate:

how can i get around declaring an unused variable in a for loop

In Python, particularly with a for-loop, is there a way to not create a variable if you don't care about it, ie the i in this example which isn't needed:

for i in range(10):
    print('Hello')


No, but often you will find that _ is used instead:

for _ in range(10):
    print('Hello')

You only have to be careful when you use gettext.


A for-loop always creates a name. If you don't want to use it, just make this clear by its name, for example call it dummy. Some people also use the name _ for an unused variable, but I wouldn't recommend this name because it tends to confuse people, making them think this is some special kind of syntax. Furthermore, it clashes with the name _ in the interactive interpreter and with the common gettext alias of the same name.


I've seen people use _ as a throw-away variable. I tend to just use i and not use it.


Just use a variable name you don't care about. This could be dummy or the often-seen _.


Yes:

from __future__ import print_function
print(*['Hello']*10, sep='\n')

But you should prefer the for loop for readability


Try this little arabesqsue.

print "Hello\n"*10
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜