Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python displays all of the prime numbers from 1 through 100

Tags:

python

I'm trying to print the all of the prime numbers from 1 through 100 by using Boolean function.

Below is my code that is working.

for n in range(1,101):
status = True
if n < 2:
    status = False
else:
    for i in range(2,n):
        if n % i == 0:
            status = False

    if status:
        print(n, '', sep=',', end='')

But when I put the code in the function and run module, there's nothing print on the shell. What did I do wrong?

is_prime():
    for n in range(1,101):
        status = True
        if n < 2:
            status = False
        else:
            for i in range(2,n):
                if n % i == 0:
                    status = False
        return status

if is_prime():    
    print(n, '', sep=',', end='')

Below is the output of the program. How do I prevent the last comma from printing?
2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,

like image 298
user2210599 Avatar asked Apr 12 '13 05:04

user2210599


People also ask

How do you show prime numbers in Python?

We check if num is exactly divisible by any number from 2 to num - 1 . If we find a factor in that range, the number is not prime, so we set flag to True and break out of the loop. Outside the loop, we check if flag is True or False . If it is True , num is not a prime number.


1 Answers

try this

def is_prime(n):
    status = True
    if n < 2:
        status = False
    else:
        for i in range(2,n):
            if n % i == 0:
                status = False
    return status

for n in range(1,101):
    if is_prime(n):
        if n==97:
            print n
        else:
            print n,",",

output is
2 , 3 , 5 , 7 , 11 , 13 , 17 , 19 , 23 , 29 , 31 , 37 , 41 , 43 , 47 , 53 , 59 , 61 , 67 , 71 , 73 , 79 , 83 , 89 , 97

like image 50
Mahdi-bagvand Avatar answered Nov 13 '22 19:11

Mahdi-bagvand