I want to input a command-line variable and then multiply it, but when I print the variable it repeats by the number I want to multiply it by.
eg:
#!/usr/bin/env python3
import sys
st_run_time_1 = sys.argv[1]*60
print ("Station 1 : %s" % st_run_time_1)
When I run the script I get the following: python3 test.py 2
Station 1 : 222222222222222222222222222222222222222222222222222222222222
sys.argv[x] is string. Multiplying string by number casue that string repeated.
>>> '2' * 5 # str * int
'22222'
>>> int('2') * 5 # int * int
10
To get multiplied number, first convert sys.argv[1] to numeric object using int or float, ....
import sys
st_run_time_1 = int(sys.argv[1]) * 60 # <---
print ("Station 1 : %s" % st_run_time_1)
You are multiplying a string with an integer, and that always means repetition. Python won't ever auto-coerce a string to an integer, and sys.argv is always a list of strings.
If you wanted integer arithmetic, convert the sys.argv[1] string to an integer first:
st_run_time_1 = int(sys.argv[1]) * 60
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With