What is wrong with my code? (Solved) | Sololearn: Learn to code for FREE!
Nouvelle formation ! Tous les codeurs devraient apprendre l'IA générative !
Essayez une leçon gratuite
+ 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

13th Jun 2021, 2:14 PM
Priyangshu
Priyangshu - avatar
13 Réponses
+ 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")
13th Jun 2021, 5:59 PM
visph
visph - avatar
+ 16
for i in range(2,num): if num % i == 0: print(num,"is not prime") break else: print(num,"is prime")
13th Jun 2021, 2:29 PM
Simba
Simba - avatar
+ 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.
13th Jun 2021, 2:21 PM
TOLUENE
TOLUENE - avatar
+ 5
Pariket What difference does the space make?
13th Jun 2021, 3:05 PM
Priyangshu
Priyangshu - avatar
+ 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" .
13th Jun 2021, 3:10 PM
TOLUENE
TOLUENE - avatar
+ 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?
13th Jun 2021, 2:50 PM
Priyangshu
Priyangshu - avatar
+ 3
https://code.sololearn.com/cKlc8Rfg8t4B/?ref=app
14th Jun 2021, 7:03 PM
Daniel Kagombe
Daniel Kagombe - avatar
13th Jun 2021, 2:30 PM
TOLUENE
TOLUENE - avatar
14th Jun 2021, 7:55 AM
Calvin Thomas
Calvin Thomas - avatar
+ 1
for i in range(2,num): if num % i == 0: print(num,"is not prime") break else: print(num, "is prime") #fixed
14th Jun 2021, 4:51 AM
PAUL OGENEKEWEN EMUROTU
PAUL OGENEKEWEN EMUROTU - avatar
0
solved pls
14th Jun 2021, 4:47 PM
md emon
md emon - avatar
- 3
Hiii
14th Jun 2021, 8:27 AM
Vamshi 20.AA.023