+ 18
What is wrong with my code? (Solved)
https://code.sololearn.com/cJ0JqmtjZfQ9/?ref=app For a few multiples of 3 the code gives the result as prime
13 Respuestas
+ 5
# Priyangshu your actual code still has a corner case (wich isn't corrected in most of other answers) for num == 0 (output both of "0 is not prime" and "0 is prime")...
# fixed code:
num = int(input())
if num == 0 or num == 1:
print(num,"is not prime")
else:
for i in range(2,num):
if num % i == 0:
print(num,"is not prime")
break
else:
print(num,"is prime")
+ 16
for i in range(2,num):
if num % i == 0:
print(num,"is not prime")
break
else:
print(num,"is prime")
+ 5
Remove break from else statement and print() too.
Using break in both if and else made the loop to run only one time.
For 39
39%2!= 0 and it is printing 39 as prime.
+ 5
Pariket What difference does the space make?
+ 5
Priyangshu algorithm behind the solution of Simba sir is
for i in range():
if :
.......
else:
.......
else:
This block will run when the for loop finishes normally (no break)
for 39 => 39%3 == 0 => prints "not prime" and breaks the loop and the loop isn't finished normally so else after for loop won't run .
for 5 => the loop finishes normally not reaching any break so last else gets executed and print "is prime" .
+ 4
Simba The code is working perfectly now.
But if I place the else statement just under the if statement then the code shows 2 results.
for i in range(2,num):
if num % i == 0:
print(num,"is not prime")
break
else:
print(num,"is prime")
The result it gives is:
21 is prime
21 is not prime
Why is it so? Doesn't the 'break' stop the execution of the else statement?
+ 3
https://code.sololearn.com/cKlc8Rfg8t4B/?ref=app
+ 2
Priyangshu Please have a look at this:
https://code.sololearn.com/ct3YOcp5VfHt/?ref=app
+ 1
for i in range(2,num):
if num % i == 0:
print(num,"is not prime")
break
else:
print(num, "is prime")
#fixed
0
solved pls
- 3
Hiii