0

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

2
  • 5
    In Python 3, print is a function, so k*k is an argument to print() and then the result of printing (None) is given the % operator. To fix, just put parentheses around the whole thing (excluding the actual print word, of course). Commented Nov 23, 2016 at 20:20
  • If you want to print the result of (k*k)% (1000000000+7) you have to wrap the whole thing in parenthesis: print((k*k) % (1000000000+7)). BTW: this produces the same result in both python and python3. (The output changes when you start using commas or keyword arguments...) Commented Nov 23, 2016 at 20:25

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.