6

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?

3
  • Please post the full traceback... Commented Dec 26, 2013 at 4:27
  • 7
    If your variable came from raw_input, it is a string. Cast it to an int. Commented Dec 26, 2013 at 4:30
  • @roippi, I agree, but I think that the code we both have in mind is int(raw_input('Enter Length.')), so the exact term is not "Cast", but "Convert it to an integer", or "Construct an integer out of it". Commented Dec 26, 2013 at 6:48

3 Answers 3

7

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)
Sign up to request clarification or add additional context in comments.

1 Comment

for i in range (l) is shorter and does the same thing
0

You ask user to input a number

l = raw_input('Enter Length: ')

But the problem is that entered number will be presented as a string instead of int. So you have to convert string 2 int

l = int(raw_input('Enter Length: '))

If you use Python 2.X you also can optimize your code - instead of range you might use xrange. It works much faster.

for i in xrange (l):
    #Do something (like append to a list)

In Python 3.X xrange was implemented by default

Comments

-2

Try this code:

x = int(input("the number you want"))
for i in range(x):

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.