user3068762
user3068762

Reputation: 297

run python code in vi editor and passing user input

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.

Upvotes: 1

Views: 1179

Answers (2)

user1251007
user1251007

Reputation: 16731

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

Upvotes: 1

hashbrown
hashbrown

Reputation: 3516

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

Upvotes: 1

Related Questions