user4038146
user4038146

Reputation:

Why is my code working fine with python 2.7 but outputting nothing with python 3.4?

Basically, the problem is to print all numbers from 1 to 1000 wherein the square of the number consists only of even numbers(Eg : 932**2 = 868624, all digits are even digits) I am sure I got the algorithm, got it working fine with python 2.7, but is failing with python 3.4. Seems pretty strange. Anyways, here is the code:

for x in range(1,1000): #x varies from 1 to 1000
    sq = x*x
    flag = True
    while sq != 0:
        if sq %2 != 0:    #everytime sq is divided by 10, result is even
            flag = False
            break
        sq /= 10
    if flag:
        print(x)
    x += 1

Upvotes: 0

Views: 75

Answers (3)

lord63. j
lord63. j

Reputation: 4670

As other answers said: use //. But I want to add a note:

from __future__ import division

Add this line at the start of your file, it will make division the same behaviour in python 2.x and 3.x . It should be useful when you want to write 2.x and 3.x compatible programs.


Before:

python 2.x

>>> 3 / 2
1
>>> 3 // 2
1

python 3.x

>>> 3 / 2
1.5
>>> 3 // 2
1

After:

python 2.x && python 3.x

>>> 3 / 2
1.5
>>> 3 // 2
1

Upvotes: 1

pguetschow
pguetschow

Reputation: 5337

http://www.pythontutor.com/visualize.html#mode=display

Shows that the problem is in line 8. Python 3 uses / only for float division, use // instead.

Source; http://www.informit.com/articles/article.aspx?p=1439189

for x in range(1,1000):
    sq = x*x
    flag = True
    while sq != 0:
        if sq %2 != 0:
            flag = False
            break
        sq //= 10 # <-- here
    if flag:
        print(x)
    x += 1

Now, the Output should look like this :

    2   
    8
    20
    22...

Upvotes: 0

Anand S Kumar
Anand S Kumar

Reputation: 90889

In Python 3.x , The result of / is float , Example -

>>> 868624/10
86862.4

Whereas in Python 2.x , when both operands to / were integer , it did integer division.

You need to do -

sq //= 10

Also, as suggested in the comments, you do not need x+=1 line at the end of the for loop , though that would not cause any skipping of numbers, its useless, you can remove that line.

This is because changing the x variable inside the for loop would not affect the range, and the for loop would take the next number from range and assign it to x for the next iteration.

Upvotes: 1

Related Questions