Symonds
Symonds

Reputation: 194

How to pass simple parameter in python

I want to try simple Python code test.py where I want to pass parameter.

import sys    
result = 3 * 3 * <parameter>
print(result)

When I run the Python code i want to pass value as 3 in input parameter so that i can get result 27 at the end. I can run the python code after passing the value in the parameter. For example i can run the python code like below. Is it possible to do in Python ?

 test.py 3

Upvotes: 1

Views: 727

Answers (1)

Wander Nauta
Wander Nauta

Reputation: 19615

You were pretty close with the import sys. The first command-line argument is in sys.argv[1], as a string.

import sys    
result = 3 * 3 * int(sys.argv[1])
print(result)

Example:

~ > python test.py 3
27

Assuming some UNIX-like system, you can run your script as a program (so ./test.py 3) by making it executable and adding a shebang; to run your script from everywhere (so test.py 3), add it to your $PATH. Both of these are optional.

Reference

Upvotes: 3

Related Questions