Reputation: 47
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))
Upvotes: 3
Views: 75
Reputation: 2203
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
Upvotes: 0
Reputation: 1709
First go to the file directory and run the command from command line.
python -c "import modulename"
here modulename
is your file_name.py
Upvotes: 0
Reputation: 6768
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
Upvotes: 1
Reputation:
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.
Upvotes: 4