Skip to content Skip to sidebar Skip to footer

Program Fails In Python 2.7.8 But Runs In Python 3.4.1

I've ran this code using Python 3.4.1 and it works, but if I use Python 2.7.8 it fails, why? i=1 while i<10: for x in(1,2,3,4,5,6,7,8,9): print (i*x,'\t',end='')

Solution 1:

In fact, print is a function in Python 3 but not Python 2. In Python 2, you need to remove () and end. As an alternative, you can add from __future__ import print_function into your code in Python 2 to use print as in Python 3.


Solution 2:

Amongst the breaking changes between Python versions 2.x and 3.x is that print is a function - in 2.x it was a statement. You have two options, either use:

from __future__ import print_function

at the top of your script to use the new function in 2.x, or have a separate 2.x version with the old syntax:

print '{0}\t'.format(i * x), # note trailing comma to suppress newline

The former is much easier, in my opinion.

Note that the default sep equivalent for the 2.x print statement is a single space, so the naïve version

print i * x, '\t',

would include an extra space before the tab. Also, note that your 3.x version can be slightly simpler:

print(i * x, end='\t')

Post a Comment for "Program Fails In Python 2.7.8 But Runs In Python 3.4.1"