简体   繁体   中英

what is the cleanest way to loop in a range of numbers in python?

So lets say

start = 10
end = 30

now I need a loop that goes from start to end

I was thinking of something like this:

for i in [start..end]
  print i

but that does not quite work. Is there a clean way to do this?

for i in range(start, end+1):
   print i

will give you the output from 10 to inclusive 30.

NOTE: The reason I added +1 to your end value is because the range() function specifies a half-closed interval . This means the first value is included , but the end value is not .

Ie,

  range(5, 10)

would give you a list of

  5, 6, 7, 8, 9

but not include 10.

You can also specify the step size for range() and a host of other things, see the documenation .

Finally, if you are using Python 2.x you can also use xrange() in place of range() , though in Python 3.x you will only have range() which is why I used it here.

If you are curious about the differences between range() and xrange() (though it is not really directly relevant to your question) the following two SO questions are a good place to start: What is the difference between range and xrange functions in Python 2.X? and Should you always favor xrange() over range()?

for i in xrange(start, end + 1):
    print i

Use range in xrange 's stead (as @Levon suggests) if you are using Python 3, as opposed to Python 2.x.

for i in xrange(10, 31):
   # something

Look at the fine manual, it'll explain it for you... Note that the ending point is "up to, but not including" - it's called a half closed range.

Also as others have mentioned in Python 3.x - range() is a generator and doesn't create a list as in Python 2.x. However, the 2to3 tool will automatically convert an xrange to a range statement.

In 2.x range generated a physical list which can be sliced etc... But in 3.x you have to write list(range(1000)) if you want it to materialise what it did in 2.x.

You're looking for range()

range(start,end) #end not inclusive
range(end) # starts with 0,end not inclusive
range(start, end, step) #increments of step, default = 1

For example,

for i in range(100,150):
   print i

Note: Py3k+ has only range(), prior versions have xrange() and range() , both are similar except xrange() is a generator, whereas range() creates a list of the numbers which you can iterate over.

You can iterate and print each element of the list. Try the following:

for i in range(start,end+1):
print i

您还可以通过打印从range返回的结果列表来打印全范围的数字:

print(range(start, end+1))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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