向Python Shell添加函数



假设我定义了以下函数:

def roots(a,b,c):
top = (b*b - 4*a*c)**0.5
p1 = (- b + ( top ) )/(2*a)
p2 = (- b - ( top ) )/(2*a)
print(p1)
print(p2)

我希望能够在python shell中调用roots(a,b,c)。我怎样才能做到这一点?

我预计结果会是这样的。

Python 3.8.6 (tags/v3.8.6:db45529, Sep 23 2020, 15:52:53) [MSC v.1927 64 bit (AMD64)] on win32                                                                                                                                     
Type "help", "copyright", "credits" or "license" for more information.                                                                                                                                                             
>>> roots(2,3,1)
-0.5
-1.0
>>>

假设您的函数是在python脚本functions.py中定义的,那么您有两个选项:

  1. 使用-i标志运行脚本,以使用python3 -i functions.py启动交互式会话。这将打开一个交互式会话,其中functions.py中的功能在作用域中可用。

  2. 或者,在包含functions.py的同一目录中,只需启动一个解释器并运行from functions import roots

最新更新