Does python officially support reusing a loop-variable after the loop?

前端 未结 5 1177
渐次进展
渐次进展 2020-12-10 11:45

Is the following code bad practice?

for i in some_values:
    do_whatever(i)
do_more_things(i)

Somehow, it feels to me like the variable

5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-10 12:36

    Just like @petr said, it sound unnatural. Not because it's allowed that it's natural or you have to use it.

    I rather have something like this, although it may not apply to the logic with a break use-case:

    for i in some_values:
        do_whatever(i)
    else:
        do_more_things(i)

    But this still raise NameError if some_values evaluate to empty, but sounds clearer. It does not give the clear readability of an inner scope but the indentation may suggests it.

    But as other said, to answer to the specific OP's question, yes, it's legal.

提交回复
热议问题