0

Let's say we want to look at range(2,10).

I have written the following code:

for n in range(2,10):
    for x in range(2,n):
        if n%x == 0:
            print(n,'equals',x,'*',n//x)  
            break
    else:
        print(n, "is a prime number") 

The above way can do checking correctly but it also returns one factor.

But if I replace break to continue:

for n in range(2,10):
    for x in range(2,n):
        if n%x == 0:
            print(n,'equals',x,'*',n//x)  
            continue
    else:
        print(n, "is a prime number") 

It couldn't do the checking correctly anymore. So is there any better way to get both checking and all factors correctly? Your answer will be of great help to me!!

ChrisGPT was on strike
  • 127,765
  • 105
  • 273
  • 257

1 Answers1

1

Do not use either break or continue, but make and use a bool variable prime as follows.

for n in range(2,10):
    prime = True
    for x in range(2, n):
        if n%x == 0:
            print(n,'equals',x,'*',n//x)  
            prime = False
    if prime:
        print(n, "is a prime number")
Gilseung Ahn
  • 2,598
  • 1
  • 4
  • 11