1
def is_prime():
    for num in range (1, 101):
        if num > 1:
            for i in range (2, num):
                if num % i == 0:
                    break           
            else:
                print(num)
is_prime()
1

1 ответ 1

3

Это такой оригинальный питоновский синтаксис - for ... else. Да, этот else принадлежит к for. Если с цикла выйти по break - else не отработает. Если цикл завершится нормально, то else будет выполнятся.

Документация - https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops

Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the iterable (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement. This is exemplified by the following loop, which searches for prime numbers:

и тут же приведен Ваш пример:)

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.