pythonpython-3.xpython-idle

Code works in one Python environments but has a syntax error in another


I am working on the following code:

def numberToName(number):
    if (number==3):
        return "Three"
    elif (number==2):
        return "Two"
    elif (number==1):
        return "One"
    else:
        return "Invalid"

print numberToName(2)
print numberToName(3)
print numberToName(1)
print numberToName(1)

This code runs 100% fine in the following online Python environment - http://www.codeskulptor.org/#user11_Hh0KVUpNVP_0.py

But when I use IDLE it shows a syntax error Invalid Syntax in line print numberToName(2)

My Python version is 3.3.1

I have noticed some issues as well. For an example, in the given URL, I can run print "hello" and get the output, but the same generated error in IDLE unless I type print ("Hello").

What is the issue here? I am new to Python.

(Please note the main question is about the given code snippet).


Solution

  • That is because the IDE is using Python 3.X, and not Python 2.X like in the online environment.

    In Python 2.X you can use print("test") or print "Text".

    In Python 3.x you need to use print("test").

    This is because in Python 2.X print is a keyword, and not a function, while in Python 3 it is a function.

    If you change the print functions to this, it will run on both the web application and your IDE.

    print(numberToName(2))
    print(numberToName(3))
    print(numberToName(1))
    print(numberToName(1))