vri vri
vri vri

Reputation: 39

range difference in Python 2.7 and Python 3

I ran the following code on Python 2 and Python 3

i = int(input())
for j in range(i):
    k = int(input())
    print(k*k)%(1000000000+7)

the input was was fed from a file containing the following

2
2
1

The Python 2 version ran fine but Python 3 gave this error

4
Traceback (most recent call last):
  File "solution.py", line 4, in <module>
    print(k*k)%(1000000000+7)
TypeError: unsupported operand type(s) for %: 'NoneType' and 'int'

why is this error occurring in Python 3 and how do i correct it

Upvotes: 0

Views: 90

Answers (2)

linusg
linusg

Reputation: 6439

It has nothing to do with range. You're just trying to use modulo on None, that's what the print function returns. Just reorder the parantheses like this:

print((k*k)%(1000000000+7))

Hope this helps!

Upvotes: 0

wim
wim

Reputation: 363133

In Python 2 it's parsing like this:

n = (k*k)%(1000000000+7)
print n

In Python 3 it's parsing differently, like this:

n = print(k*k)
n%(1000000000+7)  # TypeError

It's due to the changing of print from a statement into a function. The return code of the print function is None, which you can't use with the remainder operator %.

Make yourself aware also of the differences between input on Python 2 and Python 3

Upvotes: 2

Related Questions