+ 1
How to make this code work correctly?
I have a code to check if a number is prime or not,but it doesn't work for non prime numbers.How to solve this? n=int(input()) if n>1: for i in range(2,n): if n%i==0: print("np") break else: print("p") break
5 Réponses
+ 1
The else-part is indented wrongly.
Just pull it back and align it with your 'for' and it works.
n=int(input())
if n>1:
for i in range(2,n):
if n%i==0:
print("np")
break
else:
print("p")
+ 1
Normally, yes.
But with for loops you can use 'else' too, even without any 'if' around. It works like this:
If the loop executes a break, then it just stops. But if it doesn't break, the else branch is executed.
In this case that makes sense:
Only if the whole loop runs and you don't find a divisor (and consequently don't break) you want to print 'p'.
+ 1
You should remember this as a separate tool. There's no relation to 'if' in this case.
You could write this more complicated, for example:
prime = True
for i in range(2, n):
if not n%i:
print('np')
prime = False
break
if prime:
print('p')
So you would have a so-called 'flag' variable that decides what happens after the loop ends.
Cases like these come up quite often, so Python has added an alternative way to use 'else', for your convenience:
The else-branch after a for loop is only executed if the loop runs till the end and is not broken.
0
But I should aligned it with "if"
0
Thanks,it's working,but shouldn't "else" be for "if",
like if ... ,then this else this ?if so,then it should be aligned with "if"