0

I'm trying to loop through list of arguments passed by the prompt in calling the function in python I want to get the sys.argv[1] as integer not string

this is the code i wrote in the function

x=[1,2,3,4,5]
for n in x:
    print sys.argv[1] * n

if i called the previous function with 5 i receive

    5
    55
    555
    5555
    55555

how can i receive

5
25
125
625

any ideas what can be the solution

glglgl
  • 89,107
  • 13
  • 149
  • 217
  • possible duplicate of [Parse String to Float or Int](http://stackoverflow.com/questions/379906/parse-string-to-float-or-int) – Paolo Moretti Aug 28 '14 at 08:41

2 Answers2

2
import sys
x=[1,2,3,45]
try:
    for n in x:
        print int(sys.argv[1]) * n
except IndexError:
    print "No argument were passed to the program"

Output:

enter image description here

1

simply by doing this

x=[1,2,3,45]
for n in x:
    print int(sys.argv[1]) * n

but be careful this solution will blow up if you pass anything that can't be casted into a string or if you are not passing anything. So you probably want to catch any exceptions with a try and except block.

greole
  • 4,523
  • 5
  • 29
  • 49