Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Want to multiply, not repeat variable

Tags:

python

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
like image 271
Gregg Avatar asked Jan 26 '26 05:01

Gregg


2 Answers

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)
like image 77
falsetru Avatar answered Jan 27 '26 17:01

falsetru


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
like image 21
Martijn Pieters Avatar answered Jan 27 '26 18:01

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!