0

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
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Symonds
  • 184
  • 1
  • 2
  • 15

1 Answers1

2

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

Wander Nauta
  • 18,832
  • 1
  • 45
  • 62
  • thanks and how can i pass string as parameter ? – Symonds Sep 02 '21 at 08:31
  • 1
    It works the same way. `python test.py 3 spam 'eggs foo'` will mean `sys.argv` is `['test.py', '3', 'spam', 'eggs foo']`. Feel free to experiment. – Wander Nauta Sep 02 '21 at 08:36
  • sorry one more question..for example if i have to pass multiple parameter then how to do that ? For example i have complex code and now i want to pass 3 parameter in different place in my code then does it work in Python ? – Symonds Sep 02 '21 at 08:47