[Tutor] How to run this block of code dozens of times

Steven D'Aprano steve at pearwood.info
Mon Sep 17 05:17:20 CEST 2012


On 17/09/12 10:56, Scurvy Scott wrote:

> Why would you use an underscore rather than a letter or name like I've
> always seen. I've never seen an underscore used before.

An underscore on its own is often used to mean "don't care". Like a
scratch variable to hold a result when you don't actually need the result.
So in a for-loop:

for _ in range(20):
     ...


the idea is to tell the reader we don't actually care about the indexes
0, 1, 2, ... but only care that the loop happens 20 times.

Other uses are:

* a single leading underscore usually means "private, don't touch"

E.g. if you see a function called _func then you shouldn't use it in
your own code, because the author is stating that the function is for
private use only and it might go away or change in the next version.

* double leading and trailing underscore names have special meaning
   to Python, e.g.:

   __name__
   __class__
   __len__
   __add__
   and many others



-- 
Steven


More information about the Tutor mailing list