1

I want to run the following code in vi editor:

def factorial( n ):
   if n <1:   # base case
       return 1
   else:
       returnNumber = n * factorial( n - 1 )  # recursive call
       print(str(n) + '! = ' + str(returnNumber))
       return returnNumber

I want to give a runtime input for the value n while running the program in vi editor. I don't know how to give run time user input for a python program in vi editor. Also wants to know what changes need to be done in the code while running the code in vi editor. Can I have a resolution for this? I am able to run the code but unable to pass the value of n.

I am running this in Putty and I am using Python3.

2 Answers 2

1

To run a code from inside vi editor, use this:

:!python code.py arg1

Using :! from within vi you can run any valid shell command. Furthermore, you can also pass command-line argument (arg1) to your python code using this method.

Hope this helps

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

2 Comments

I am unable to do this with your suggestion. Can you please help me with more information. I am running this like following:[arindam@n1 lesson]$ :!python fact1.py factorial(4) :python fact1.py -v factorial(4) fact1.py factorial(4) -bash: syntax error near unexpected token `(' [arindam@n1 lesson]$
@user3068762: You can not directly call a function. Have look at my answer to see what needs to be changed in your code
1

You need to change your code:

import sys

def factorial(n):
    # your function here

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

When the script file is executed, it is started from if __name__ == '__main__' and your factorial() is called with the command line argument as a parameter.

Then you can run this script from within vi as described by hashbrown, for example:

:!python code.py 20

PS: You might want to add a line print(sys.argv) just before calling your factorial function, just to learn what sys.argv actually contains (why using index 1 and int()).

1 Comment

For e.g. :!python my.py M=10 N=41, see this answer

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.