Most elegant way to do something N times

Tim Chase python.list at tim.thechases.com
Sun Dec 22 16:09:42 EST 2019


On 2019-12-22 23:34, Batuhan Taskaya wrote:
> I encounter with cases like doing a function 6 time with no
> argument, or same arguments over and over or doing some structral
> thing N times and I dont know how elegant I can express that to the
> code. I dont know why but I dont like this
>
> for _ in range(n): do()

The best way to improve it would be to clarify readibility.  Why 6
times instead of 5 or 7?  Are they retries?

  MAX_RETRIES = 6 # defined in RFC-3141592
  for _ in range(MAX_RETRIES):
    if successful(do_thing()):
      break
  else:
    error_condition()

or because someone likes the number 6?

  MY_FAVORITE_NUMBER = 6
  for _ in range(MY_FAVORITE_NUMBER):
    print(f"I love the number {MY_FAVORITE_NUMBER}!")

or days of the week that aren't Sunday?
  
  for day in calendar.c.iterweekdays():
    if day == calendar.SUNDAY: continue
    do_thing()

or is it because it's the number of whole columns that fit?

  screen_cols = 80 # get this from curses?
  chars_per_col = 13
  for _ in range(screen_cols // chars_per_col):
    do_thing()

or because that's how many people there are in a paticular grouping?

  family = "Dad Mom Sis Brother Me Baby".split()
  for _ in family:
    do_thing()

Note how each of those conveys what "6" means, not just some
arbitrary number.

-tkc




More information about the Python-list mailing list