Reputation: 3492
Newbie to python here, I am trying to use an integer as an argument for a for loop. The code I use
from sys import argv
script, numberofposts = argv
postsint = int(numberofposts)
for x in range(0,"%d" % postsint):
print 'on time'
print "number %d" % postsint
Gives me this error -
Traceback (most recent call last):
File "forarg.py", line 6, in <module>
for x in range(0,"%d" % postsint):
TypeError: range() integer end argument expected, got str.
What am I doing wrong here? I assumed that it was a syntax issue but the error seems to indicate that the for loop is expecting an integer which I attempted to force as you can see.
Upvotes: 2
Views: 8591
Reputation: 251001
it's because "%d"
is used for string formatting and it returns string only:
In [18]: type( "%d" % 3)
Out[18]: <type 'str'>
use just ,range(0,4)
or xrange(0,4)
if you're on python 2.x:
In [19]: range(0,4) #0 is the default value of the first argument, so range(0,4)==range(4)
Out[19]: [0, 1, 2, 3]
Upvotes: 3
Reputation: 3985
You are doing a formatted string as the second param to range.
In the case that you are using you are saying start at 1 and go up to a string with the number postint
in it.
This is wrong. You want to do range( 1, postint )
Upvotes: 1
Reputation: 55962
for x in range(postsint): # start at beginning as mgilson suggested
should work fine. You already casted it an integer, You shouldn't be creating a string from it
Upvotes: 3