python快速输入下划线_尝试使用下划线和输入了解Python循环

One more tip - if anyone is learning Python on HackerRank, knowing this is critical for starting out.

I'm trying to understand this code:

stamps = set()

for _ in range(int(input())):

print('underscore is', _)

stamps.add(raw_input().strip())

print(stamps)

Output:

>>>2

underscore is 0

>>>first

set(['first'])

underscore is 1

>>>second

set(['second', 'first'])

I put 2 as the first raw input. How does the function know that I'm only looping twice? This is throwing me off because it isn't the typical...for i in xrange(0,2) structure.

At first my thinking was the underscore repeats the last command in shell. So I added print statements in the code to see the value of underscore...but the values just show the 0 and 1, like the typical loop structure.

I read through this post already and I still can't understand which of those 3 usages of underscore is being used.

I'm just starting to learn Python so easy explanations would be much appreciated!

解决方案

ncoghlan's answer lists 3 conventional uses for _ in Python:

To hold the result of the last executed statement in an interactive

interpreter session. This precedent was set by the standard CPython

interpreter, and other interpreters have followed suit

For translation lookup in i18n (imported from the corresponding C

conventions, I believe), as in code like:

raise forms.ValidationError(_("Please enter a correct username"))`

As a general purpose "throwaway" variable name to indicate that part

of a function result is being deliberately ignored, as in code like:

label, has_label, _ = text.partition(':')

Your question is which one of these is being used in the example in your code. The answer would be that is a throwaway variable (case 3), but its contents are printed here for debugging purposes.

It is however not a general Python convention to use _ as a loop variable if its value is used in any way. Thus you regularly might see:

for _ in range(10):

print("Hello world")

where _ immediately signals the reader that the value is not important and it the loop is just repeated 10 times.

However in a code such as

for i in range(10):

do_something(i)

where the value of the loop variable is used, it is the convention to use a variable name such as i, j instead of _.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值