python find prime numbers within 100

method one:

a = []
for i in range(2,100):
    isPrime = True
    for j in range(2,i):
        if i % j == 0:
            isPrime = False
            break
    if isPrime == True:
        a.append(i)
print(a)

Method Two:

This method uses python's for else

The characteristic of the for else syntax is that the else will be executed only after the for loop (same indentation) following the else is executed normally. If it is interrupted in the middle (such as encountering a break to exit the loop), the else statement will not be executed

a = []
for i in range(2,100):
    for j in range(2,i):
        if i % j == 0:
            break
    else:
        a.append(i)
print(a)

Method three:

Use list expressions

a = [i for i in range(2,100) if 0 not in [i % j for j in range(2,i)]]
print(a)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324831665&siteId=291194637