break, continue, pass#
В Python есть несколько операторов, которые позволяют менять поведение циклов по умолчанию.
Оператор break#
Оператор break позволяет досрочно прервать цикл:
- break прерывает текущий цикл и продолжает выполнение следующих выражений
- если используется несколько вложенных циклов, break прерывает внутренний цикл и продолжает выполнять выражения, следующие за блоком * break может использоваться в циклах for и while
In [1]: for num in range(10): . : if num 7: . : print(num) . : else: . : break . : 0 1 2 3 4 5 6
In [2]: i = 0 In [3]: while i 10: . : if i == 5: . : break . : else: . : print(i) . : i += 1 . : 0 1 2 3 4
Использование break в примере с запросом пароля (файл check_password_with_while_break.py):
username = input('Введите имя пользователя: ') password = input('Введите пароль: ') while True: if len(password) 8: print('Пароль слишком короткий\n') elif username in password: print('Пароль содержит имя пользователя\n') else: print('Пароль для пользователя <> установлен'.format(username)) # завершает цикл while break password = input('Введите пароль еще раз: ')
Теперь можно не повторять строку password = input(‘Введите пароль еще раз: ‘) в каждом ответвлении, достаточно перенести ее в конец цикла.
И, как только будет введен правильный пароль, break выведет программу из цикла while.
Оператор continue#
Оператор continue возвращает управление в начало цикла. То есть, continue позволяет «перепрыгнуть» оставшиеся выражения в цикле и перейти к следующей итерации.
In [4]: for num in range(5): . : if num == 3: . : continue . : else: . : print(num) . : 0 1 2 4
In [5]: i = 0 In [6]: while i 6: . : i += 1 . : if i == 3: . : print("Пропускаем 3") . : continue . : print("Это никто не увидит") . : else: . : print("Текущее значение: ", i) . : Текущее значение: 1 Текущее значение: 2 Пропускаем 3 Текущее значение: 4 Текущее значение: 5 Текущее значение: 6
Использование continue в примере с запросом пароля (файл check_password_with_while_continue.py):
username = input('Введите имя пользователя: ') password = input('Введите пароль: ') password_correct = False while not password_correct: if len(password) 8: print('Пароль слишком короткий\n') elif username in password: print('Пароль содержит имя пользователя\n') else: print('Пароль для пользователя <> установлен'.format(username)) password_correct = True continue password = input('Введите пароль еще раз: ')
Тут выход из цикла выполнятся с помощью проверки флага password_correct. Когда был введен правильный пароль, флаг выставляется равным True, и с помощью continue выполняется переход в начало цикла, перескочив последнюю строку с запросом пароля.
Результат выполнения будет таким:
$ python check_password_with_while_continue.py Введите имя пользователя: nata Введите пароль: nata12 Пароль слишком короткий Введите пароль еще раз: natalksdjflsdjf Пароль содержит имя пользователя Введите пароль еще раз: asdfsujljhdflaskjdfh Пароль для пользователя nata установлен
Оператор pass#
Оператор pass ничего не делает. Фактически, это такая заглушка для объектов.
Например, pass может помочь в ситуации, когда нужно прописать структуру скрипта. Его можно ставить в циклах, функциях, классах. И это не будет влиять на исполнение кода.
Пример использования pass:
In [6]: for num in range(5): . : if num 3: . : pass . : else: . : print(num) . : 3 4
python: restarting a loop
You may want to consider using a different type of loop where that logic is applicable, because it is the most obvious answer.
Just a reminder: with a while loop, make sure you have a termination condition that can always be satisfied.
But there’s nothing preventing i from continuing to reset to 2 indefinitely, depending on the «if something» test.
So it depends more on the if-test than the loop invariant? Is there another solution that avoids this while staying simple(because simplicity is key)? Won’t there always be the same risk in any loop with the potential to restart?
Changing the index variable i from within the loop is unlikely to do what you expect. You may need to use a while loop instead, and control the incrementing of the loop variable yourself. Each time around the for loop, i is reassigned with the next value from range() . So something like:
In my example, the continue statement jumps back up to the top of the loop, skipping the i += 1 statement for that iteration. Otherwise, i is incremented as you would expect (same as the for loop).
Here is an example using a generator’s send() method:
def restartable(seq): while True: for item in seq: restart = yield item if restart: break else: raise StopIteration
x = [1, 2, 3, 4, 5] total = 0 r = restartable(x) for item in r: if item == 5 and total < 100: total += r.send(True) else: total += item
Just wanted to post an alternative which might be more genearally usable. Most of the existing solutions use a loop index to avoid this. But you don't have to use an index - the key here is that unlike a for loop, where the loop variable is hidden, the loop variable is exposed.
You can do very similar things with iterators/generators:
x = [1,2,3,4,5,6] xi = iter(x) ival = xi.next() while not exit_condition(ival): # Do some ival stuff if ival == 4: xi = iter(x) ival = xi.next()
It's not as clean, but still retains the ability to write to the loop iterator itself.
Usually, when you think you want to do this, your algorithm is wrong, and you should rewrite it more cleanly. Probably what you really want to do is use a generator/coroutine instead. But it is at least possible.
Как выйти из цикла и сразу начать его заново python?
когда создаешь запрос от пользователя
если продолжить то 1 иной вариант завершает цикл.
number = random.randint(1, 100) while True: print(number) userNumber = int(input("Введите число: ")) if number == userNumber: print("Победа") user = int(input("Еще разок ? если да то 1 если нет то 2: ")) if user == 1: number = random.randint(1, 100) continue else: break elif number < userNumber: print("введите число меньше") elif number >userNumber: print("введите число больше")
Таким способом спрашиваем запустить цикл занного или нет.
Очень частный случай, в моем случае это не помогает, мне же надо чтобы цикл начался заново а не продолжился пропустив это значение, как этого добиться?
def function (args) : # - вызываем функцию с циклом
while True: # - начало цикла
# то что вы хотели делать
if (ваше условие):
break # - остановка цикла
function (args) # - снова вызываем функцию и снова попадаем в цикл
from my_func import my_func
while True: #цикл бесконечный
____if my_condition==True:#условие:
________my_func()#выходим из цикла, там хотим вернёмся, хотим нет, хотим заново запустим цикл
________#либо а=my_func() ; что-то принесём в цикл
________#либо my_func(a) ;что-то возъмём с собой
________#либо b=my_func(a);и то, и другое
____#что-то делаем
____continue