2015-04-27 41 views
-1

我正在使用Python 3.4在Windows 8.1中运行此脚本。 这是我的脚本的一部分,我相信这是造成问题:Python 3脚本无法在Python 3.4中正常运行,但Python 2脚本能正常工作

if __name__ == '__main__': 
    import sys 
    print("Enter a sentence: ",end="") 
    sen = sys.stdin.readline() 
    print("\nThe Longest word in the sentence is {}".format(longestWord(sen))) 
    sys.stdin.readline() 

我已经使用调用sys.stdin.readline(),因为输入()会给我一个EOF错误。这解决了EOF错误,但现在我得到另一个错误指向打印结束参数说它的语法错误。只有当我将它作为顶层脚本运行时才会出现此问题,但在IDLE中正常运行。如果我使用input()而不是sys.stdin.readline(),那么将它作为顶级脚本运行时,会为我在打印状态的'end'参数处提供一个SyntaxError。

我再改剧本2.x版

if __name__ == '__main__': 
    sen = raw_input("Enter a sentence: ") 
    print "\nThe Longest word in the sentence is {}".format(longestWord(sen)) 
    raw_input() 

该脚本正常工作在Python 2.7,而且在3.4的工作。我期待的raw_input函数和打印语句的错误,但我没有得到它们。 但是这两个脚本都在IDLE 3.4中正常工作。 有人可以解释发生了什么?

+0

脚本失败的地方?这在你的文本中不太清楚。 –

回答

0

简单的解释是你很困惑,脚本最初是用python 2而不是3来运行的。这就是为什么end=发生的语法错误。

的Python 2:

In [1]: print("Enter a sentence: ",end="") 
    File "<ipython-input-1-fa5e4168bd19>", line 1 
    print("Enter a sentence: ",end="") 
           ^
SyntaxError: invalid syntax 

的Python 3:

In [1]: print("Enter a sentence: ",end="") 
Enter a sentence: 

混乱的继续,这是因为第二脚本不能下蟒3工作:

In [1]: print "\nThe Longest word in the sentence is {}".format(longestWord(sen)) 
    File "<ipython-input-1-ae375034dd27>", line 1 
    print "\nThe Longest word in the sentence is {}".format(longestWord(sen)) 
               ^
SyntaxError: invalid syntax 

在Python 3 print是一个函数和这条线就行不通了。

+0

其实我很确定这两个脚本都是用Python 3.4运行的。这是我系统的默认设置,窗口的标题栏显示为Python34。 – RudolphA

+0

标题栏可以说真的。尝试打印出'sys.version'来查看它。 – viraptor

+0

这个脚本**不能**在Pyhon 3.x下运行。 – Matthias