我是python的新手,目前正在学习正确使用def函数.
我在Sublime Text中的def代码如下:
def quadratic(a,b,c):
if not isinstance(a,(int,float)):
raise TypeError('bad operand type')
if not isinstance(b,(int,float)):
raise TypeError('bad operand type')
if not isinstance(c,(int,float)):
raise TypeError('bad operand type')
d = b ** 2 - 4 * a * c
if d < 0:
print('no result!')
if d = 0:
x1 = -b / (2 * a)
x2 = x1
return x1,x2
else:
x1 = (-b + math.sqrt(d)) / (2 * a)
x2 = (-b - math.sqrt(d)) / (2 * a)
return x1,x2
Run Code Online (Sandbox Code Playgroud)
但是当我使用终端(在Mac中)运行此代码时,遇到此错误:
Frank-s-Macbook-Pro:Coding frank$ quadratic(1,2,1)
-bash: syntax error near unexpected token `1,2,1'
Run Code Online (Sandbox Code Playgroud)
对于我必须犯的错误,我将不胜感激.
您无法直接从终端运行python定义的函数.在这种情况下,您可能希望通过在终端中键入python来在与脚本相同的文件夹中运行解释器.
然后python启动(如果它已安装并且别名正确).然后,您可以通过导入文件名导入该函数.假设您的函数保存在myfunction.py文件下.然后:
import myfunction (without the .py)
Run Code Online (Sandbox Code Playgroud)
然后输入:
>> myfunction.quadratic(a, b, c)
Run Code Online (Sandbox Code Playgroud)
你应该把答案归还给你.
如果你想直接从终端运行脚本,你应该查看输入函数或sys.argv函数,并在重写后执行你的脚本
$ python myfunction.py
Run Code Online (Sandbox Code Playgroud)
编辑:你的代码中也有一些错误,请参阅其他答案:)