简体   繁体   English

如何在具有range()的循环中使用变量? (蟒蛇)

[英]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. 我想知道在使用range()函数时是否可以使用变量。 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. Python告诉我在使用range函数时不能使用变量。 Can anybody help me? 有谁能够帮助我?

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. 由于用户输入是字符串,并且需要数值来定义范围,因此可以使用int方法将输入类型转换为整数值。

>> 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)

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. 但是问题是输入的数字将以字符串而不是int的形式显示。 So you have to convert string 2 int 所以你必须将字符串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 . 如果使用Python 2.X,则还可以优化代码-可以使用xrange来代替range。 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 在Python 3.X中,默认情况下实现了xrange

Try this code: 试试这个代码:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM