3

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

1
  • Do you have the functions stored in a file? Or on command line? Commented Aug 9, 2017 at 1:17

4 Answers 4

4

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

First go to the file directory and run the command from command line.

python -c "import modulename"

here modulename is your file_name.py

Comments

0

If you are open to using a 3rd party package, check out Google's Fire.

pip install fire

Modify your code as follows:

#!/usr/bin/env python
from fire import Fire

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

if __name__ == '__main__':
  Fire(perfect)

Make sure your file is executable if on Mac or Linux (sorry, have no idea if you have to do that on Windows). Assuming your code is in a file named perfect:

chmod +x perfect

If the file is in your path, you should now be able to call it like this:

$ perfect 44
[1, 2, 4, 11, 22]
False

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.