What is wrong with my code? (Solved) | Sololearn: Learn to code for FREE!

+17

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

6/13/2021 2:14:10 PM

Priyangshu

17 Answers

New Answer

+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

https://code.sololearn.com/cIV997b0JMqX/?ref=app Remove the last break statement

+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

https://code.sololearn.com/cn3IAqL5uiSw/?ref=app

+4

Priyangshu Don't give the space else: #not else: for i in range(2,num): if num % i == 0: print(num,"is not prime") break else: print(num,"is prime") Not for i in range(2,num): if num % i == 0: print(num,"is not prime") break else: print(num,"is prime") Mistake [space between them ] else: print(num,"is prime") else: print(num,"is prime")

+4

Pariket What difference does the space make?

+4

https://code.sololearn.com/c6Wbmle0X7O2/?ref=app https://code.sololearn.com/cyGIIyTHcw0G/?ref=app

+3

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?

+2

https://code.sololearn.com/cANRpO4Gw63e/?ref=app

+2

Priyangshu Please have a look at this: https://code.sololearn.com/ct3YOcp5VfHt/?ref=app

+2

https://code.sololearn.com/cKlc8Rfg8t4B/?ref=app

+2

happy to be on sololearn

+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