How to get only a single output of the result in python program?

Question:

I was writing a code in python to identify prime number. Here is the code

n=int(input("Enter any integer"))
for i in range(2,n,1):
   if n%i==0:
       print(n, " is not a prime number")
       break
   else:
       print("Prime number")

But the problem is that I am getting "Prime number" as an output for each time the else condition is activated. I am attaching the output results too.

enter image description here

I want to have a single "Prime number" written as an output if the number is prime. How can I get there?

I tried to use continue inside the else .

n=int(input("Enter any integer"))
for i in range(2,n,1):
   if n%i==0:
       print(n, " is not a prime number")
       break
   else:
       continue

If the number is prime there is no output. But I want "Prime number" written as my output if the number is prime.

Then I tried to apply for else condition.

It did work though but I want to know how to stop the multiple "prime number" printing of my previous code.

Answers:

Every time n%i is not equal to 0, the else statement runs.
To fix this, you can remove the else statement entirely and just stop the code after the if statement runs. For example, you can do this like this:
for i in range(2,n,1): if n%i==0: print(n, " is not a prime number") exit() print(f"{n} is a prime number")

Answered By: Tauman

There are a bunch of ways to do this (like terminating the program early, or saving to a variable to check on later, etc), but i think the one you are looking for is the for else clause.

n=int(input("Enter any integer"))
for i in range(2,n,1):
    if n%i==0:
       print(n, " is not a prime number")
       break
else:
   print("Prime number")

and yes, this is exactly like your code but with the else unindented. That Else statment that comes after the for loop basically means "Run this if the loop didn’t break, and skip it otherwise".

Answered By: PedroTurik

You can fix it like this:

n=int(input("Enter any integer"))

is_prime = True
for i in range(2,n):
    if n%i==0:
        is_prime = False
        break

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

This sets the variable is_prime to False if any divisor is found, exiting the loop immediately. If the loop runs to completion, then no divisor was found.

Note that this could be sped up in a couple ways:

  1. After checking if 2 is a divisor, you could skip the remaining even numbers and only check for odd divisors.
  2. The loop doesn’t need to run all the way up to n-1. Once i exceeds the square root of n, if no divisor has been found, then n is prime and the loop can exit.

But it should function correctly with this fix.

Answered By: Tom Karzes
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.