Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use variables in a loop with range()? (Python)

I've been searching for quite a while, and I can't seem to find the answer to this. I want to know if you can use variables when using the range() function. For example, I can't get this to work:

l=raw_input('Enter Length.')
#Let's say I enter 9.
l=9
for i in range (0,l):
    #Do something (like append to a list)

Python tells me I cannot use variables when using the range function. Can anybody help me?

like image 788
jakerm2002 Avatar asked Dec 26 '13 04:12

jakerm2002


1 Answers

Since the user inputs is a string and you need integer values to define the range, you can typecast the input to be a integer value using int method.

>> l=int(raw_input('Enter Length: '))  # python 3: int(input('Enter Length: '))
>> for i in range (0,l):
>>    #Do something (like append to a list)
like image 108
ranendra Avatar answered Oct 29 '22 23:10

ranendra