Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can i use a function directly in commandline in python?

Tags:

python

for example: my command line after execution of a program has to be like this:

perfect(44) #using the defined function in the output screen.(44) or any other number

and the output should be:

false

this the code i have tried but in this i cannot use the funcion in the command line.


def factors(n):
    factorlist = []
    for i in range(1,n):
        if n%i == 0:
            factorlist = factorlist + [i]
    print factorlist
    return factorlist

def perfect(n): factorlist = factors(n) if sum(factorlist) == n: return True else : return False

n = int(raw_input()) print(perfect(n))

like image 663
Benetha Thambi Avatar asked Feb 14 '26 17:02

Benetha Thambi


2 Answers

Go to the path where you have the .py file located. Start the python interpreter in interactive mode by the following command:

python -i filename.py

By doing this, you should be able to access all functions inside your filename.py file.

You can append the following lines to your python script to call a function when the script is loaded.

if __name__ == '__main__':
    print(perfect(int(sys.argv[1])))

You can then call it like:

python myscript.py 44
like image 38
alvits Avatar answered Feb 16 '26 07:02

alvits



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!