Skip to content
Programs · Program 6-14

Q.Program 6-14: Program to check if the input number is prime or not.

Punjab PsebTextbookSubjective· 3mImportance★★★★★est
46% · 18/39 Questions
🔒 Locked · start free trial →

You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.

Start your 14-day free trial to unlock the full solution →

A prime has no divisor other than 1 and itself, so the program tries every candidate divisor from 2 to num−1; the first exact division proves the number composite (and breaks), while surviving the whole loop proves it prime.

The idea. This combines three constructs from the chapter: a for loop to generate candidate divisors, the modulus test num % i == 0 to detect a divisor, and break to stop as soon as the verdict is known. A Boolean flag (is_prime) carries the verdict out of the loop.

# Program 6-14: check whether the input number is prime
num = int(input("Enter a number: "))
is_prime = True
if num <= 1:
    is_prime = False          # 0, 1 and negatives are not prime by definition
for i in range(2, num):
    if num % i == 0:          # found a divisor other than 1 and num
        is_prime = False
        break                 # no need to test further
if is_prime:
    print(num, "is a prime number")
else:
    print(num, "is not a prime number")

Sample runs

Enter a number: 7
7 is a prime number
Enter a number: 10
10 is not a prime number

Dry run for num = 10: i = 2 → 10 % 2 is 0 → flag set False, break. Verdict: not prime (only one division needed). …

Unlock everything free for 14 days

  • Full step-by-step solutions
  • Concept-first explanations
  • Methods, shortcuts & mistakes
  • PYQ mapping + timed mock tests

Full access for 14 days. No credit card required.