Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
142 views
in Technique[技术] by (71.8m points)

Python Exception Processing

N=int(input("Find Prime Number:"))
ans = [2]
count=0
for i in range(3,N+1):
    for j in ans:
        if i % j ==0:
            break
    else:
        ans.append(i)
print(ans)

This is a code for finding the prime number.

I wonder how "else" works when there is no "if" in the repetition.

question from:https://stackoverflow.com/questions/66058432/python-exception-processing

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The Python language supports the use of the else keyword as part of the syntax of a for statement. Most folks steer clear of it because it is an oddity, but it will execute if and only if the for loop is exited "naturally" - that is without executing break. For that reason it is sometimes referred to as the "no-break" conditional. In the sample code given in the question, i is appended to ans only if the break statement in the for loop above it is never reached.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...