Моя первоначальная логика сводилась к следующему:
Код: Выделить всё
max_iterations = 5 # Either an integer or None (the number actually comes from user input)
stop_flag = False
i = 0
while not stop_flag:
do_some_operation(i)
i += 1
stop_flag = (i == max_iterations) or test_some_stop_condition()
Код: Выделить всё
i = 0
while not ((i == max_iterations) or test_some_stop_condition()):
do_some_operation(i)
i += 1
Итак, я использовал itertools.count для выполнения итерации:
Код: Выделить всё
import itertools
max_iterations = 5 # Either an integer or None (the number actually comes from user input)
for i in itertools.count():
do_some_operation(i)
if (i == max_iterations) or test_some_stop_condition():
break
Есть ли лучшее решение?
Некоторые примечания:
- i Переменная обязательна, так как do_some_operation использует ее.
- по-прежнему может возвращать значение True независимо от того, равно ли i None или int. Это нормально.
Код: Выделить всё
test_some_stop_condition()
Подробнее здесь: https://stackoverflow.com/questions/790 ... xed-number