No output in python 3 code

So, i made this code in python 3, it should test if the sum of the digits of the number “a” is a prime number. When I try to run it, i don’t see the output. What is wrong with it?


a = 4875
prime = 1
s = 0
d = 2
while (a != 0) :
    c = a % 10
    s = s + c
    a = a % 10
if (s % d == 0) :
    prime == 0
    
if (prime == 1) : 
    print ("Suma nr. este prima")
else : 
    print ("Suma nr. nu este prima")

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make easier to read.

See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

Note: Backticks are not single quotes.

markdown_Forums

You have an infinite loop. Your while never exits, so none of the if statements execute.

I changed the code, but now is wrong…

<p> a = 4875
prime = 1
s = 0
d = 2
while (a != 0) :
    c = a % 10
    s = s + c
    a = a % 10
    
    if (s % d == 0) :
        prime == 0

    break
if (prime == 1) : 
    print ("Suma nr. este prima")
else : 
    print ("Suma nr. nu este prima")
</p>

Prime should have the value zero, but is 1.

You have a break statement in your loop, so it’ll only go through 1 iteration and stop. And on that first iteration s will be 5, so the expression if (s % d == 0) will evaluate to false. That’s why you get prime = 1.

What should i do to fix it? If i remove the break it will go into an infinite loop.

Well, think about it. if you just had pen and paper, how would you find if 4875 was prime or not? You could start by checking if it has a factor of 2 (divides cleanly by 2). If not, try bigger and bigger numbers until your divisor (d) is sufficiently large to conclude that your number (a) is prime.

So, rethink your loop condition (a != 0) and its contents. The loop condition, whatever it is, should become false at some point so the loop ends.