pythonfunctionterminal

Adding functions to Python Shell


Let's say I define the following function:

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)

I want to be able to call roots(a,b,c) inside the python shell. How can I accomplish this?

I expect the result to be something like.

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

Solution

  • Assuming your functions are defined in a python script functions.py, you have two options:

    1. Run your script with -i flag to start an interactive session using python3 -i functions.py. This opens an interactive session with the functions in functions.py available in scope.

    2. Alternatively, in the same directory containing functions.py, just start an interpreter and run from functions import roots.