2016-12-01 168 views
1

我试着MAC终端,他们都返回语法错误上运行多个Python函数,对这一计划的我的Mac终端无法运行python功能

def spam(): 
    print "R" 

spam() 

它返回的错误:

./test.py: line 1: syntax error near unexpected token `(' 
./test.py: line 1: `def spam():' 

这真的是我能找到的最简单的功能。

只是为了清楚终端运行程序的其余部分,但它不能处理函数。

#!/usr/bin/python 
import math 

number = int(raw_input("What's your surd?")) 

print type(number) 

#Just to let us know what the input is 

if type(number) == int: 
    print "Number is an integer" 
else: 
    print "Please enter a number" 

value = math.sqrt(number) 

#Takes the number and square roots it 

new_value = int(value) 

#Turns square root of number into an integer 

if type(new_value) == int: 
    print "Surd can be simplified" 
    print new_value 
else: 
    print "Surd cannot be simplified" 
    print value 

这个程序运行良好,即使它现在有点bug,但是下面的程序返回与上一个函数相同的错误。

# define a function 
def print_factors(x): 
    print("The factors of",x,"are:") 
    for i in range(1, x + 1): 
     if x % i == 0: 
      print(i) 


num = int(input("What's your number? ")) 

print_factors(num) 

为什么终端在返回语法错误的地方没有?

+0

你是如何运行你的Python程序?试试'python。/ test.py'。 –

+1

您收到的错误消息表明'bash'外壳试图解释该文件。如果您在shell中键入'def spam():',您将得到一个相同的消息。这意味着该文件不包含正确的shebang行(就像您在更长的摘录中显示的'#!/ usr/bin/python')。 – kindall

回答

1

这里的问题(至少对于第一个例子)是你没有使用python解释器。终端使用bash解释器来处理你的python代码,并且变得非常困惑。使用像这样的命令来执行您的代码python spam.py。或者先运行python进入python命令解释器,然后在命令行解释器中输入您的代码。

开始时可能更容易得到一个像PyCharm(https://www.jetbrains.com/pycharm/)这样的IDE,并运行一些教程来获得它的感觉。

1

你的问题是你的shell不知道你正在运行一个Python脚本。你需要明确说明你应该使用Python解释器。您可以这样做:

1)在您的终端呼叫python test.py

2)在你的Python脚本的顶部添加#!/usr/bin/python(你可能需要更改你的系统上的路径,Python的可执行文件)。使脚本可执行,并在您的终端上拨打./test.py

2)的好处是你知道你将使用哪种版本的Python来运行你的脚本(Python 2.x在你的情况下?)。

方法1)将使用任何Python版本是第一次遇到在你的路径,这可能是Python的3或Python 2,这取决于你是否在某些时候安装了Python 3。您编写的代码将与Python 2.7一起使用,但不适用于Python 3.x.当然,您可以始终明确地致电python2.7 ./test.py

+0

太棒了,修复了它,谢谢你堆积 –

+0

如果它解决了你的问题,总是乐于接受答案;) –