简体   繁体   中英

how to make my for loop print only once instead of for each value of i

I am trying to create a function that checks if a given number as a parameter is prime or not. I decided to do this with a for loop but it keeps printing that the number is not prime for certain dividers and that it is prime for other numbers. Here is my code:

def prime(n):
    for i in range(2, n):
        if n%i == 0:
            print (n," is not prime because it is divisible by ", i)

        else:
            print (n, " is a prime number")


prime (15)

this is the output:

15  is a prime number
15  is not prime because it is divisible by  3
15  is a prime number
15  is not prime because it is divisible by  5
15  is a prime number
15  is a prime number
15  is a prime number
15  is a prime number
15  is a prime number
15  is a prime number
15  is a prime number
15  is a prime number
15  is a prime number

So instead of giving this as an output, I would like to immediately recognise that the number is not prime if it has a divider other than 1 and itself. If the number doesn't. Kind of like this:

#if number if prime
15 is a prime number

#if number is not prime
15 is not a prime number because it is divisible by 3

By return ing, the function stops once it recognizes that a number is not prime.

def prime(n):
    for i in range(2, n):
        if n%i == 0:
            print (n," is not prime because it is divisible by ", i)
            return 
    print (n, " is a prime number")
    return

The benefit of this is once the expression n%i == 0 evaluates to true, it prints, and it returns, stopping further unnecessary evaluations.

Try this

def prime(n):
    for i in range(2, n):
        if n%i == 0:
            print (n," is not prime because it is divisible by ", i)

prime (15)

I would try something like:

def prime(n): 
    isprime = True
    for i in range(2, n): 
         if n%i == 0:
              print (n," is not prime because it is divisible by ", i)
              isprime = False
              break
    if isprime:
         print (n, " is a prime number")
prime (15)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM