简体   繁体   中英

Python Integer for loop 200 to 205

I need to input a list of http-response codes into my application config and want to provide a python shorthand so they won't list off each single code.

something like the following:

class settings: 
  success_codes= 200..299        # successful request
  retry_codes= 400..404,500-503  # retry later
  fail_codes = 504,505,506       # don't retry again 

doesn't python support some kind of clean syntax like this to define ranges? I need multiple ranges.

Use ranges , in Python 2.x:

success_codes = range(200, 300)
retry_code    = range(400, 405) + range(500, 504)
fail_codes    = range(504, 507)

And for reference, in Python 3.x (also works in Python 2.x):

success_codes = list(range(200, 300))
retry_code    = list(range(400, 405)) + list(range(500, 504))
fail_codes    = list(range(504, 507))

只需使用range函数:

vals = range(start, stop + 1)

This works across all versions of python

class settings: 
  success_codes = list(range(200, 299 + 1)) # successful request
  retry_codes = list(range(400, 404 + 1)) + list(range(500, 503 + 1)) # retry later
  fail_codes = list(range(504, 506 + 1)) # don't retry again

In earlier versions of python, list(range()) can be replaced by range() . Also, obviously, you can add the 1 to the upper value directly.

Using range(n, m+1), like a lot of people are suggesting, works. However, do you need to create all the possible values in memory?

In most cases you can use:

if return_code < 200 or return_code >= 299:
    do_something()

Or:

if return_code in range(200, 299+1):
    do_something()

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