我的mac终端无法运行python函数

时间:2016-12-01 00:28:56

标签: python macos function terminal

我试过在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

此程序运行正常,即使此时有点错误,但以下程序返回与上一个函数相同的错误。

# 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)

为什么终端在没有语法错误的情况下返回语法错误?

2 个答案:

答案 0 :(得分:1)

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

入门时可能更容易的是获得像PyCharm(https://www.jetbrains.com/pycharm/)这样的IDE并运行他们的几个教程来感受它。

答案 1 :(得分:1)

您的问题是您的shell不知道您正在运行Python脚本。您需要明确表示您应该使用Python解释器。您可以通过以下方式执行此操作:

1)在您的终端拨打python test.py

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

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

方法1)将使用PATH中首先遇到的Python版本,可能是Python 3或Python 2,具体取决于您是否在某些时候安装了Python 3。您编写的代码将与Python 2.7一起使用,但不适用于Python 3.x.当然,您始终可以明确地呼叫python2.7 ./test.py

相关问题