2016-12-01 124 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

如果它解決了你的問題,總是樂於接受答案;) –