如何在带有 range() 的循环中使用变量?(Python)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20779102/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 21:13:10  来源:igfitidea点击:

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

pythonvariables

提问by jakerm2002

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:

我一直在寻找很长一段时间,我似乎无法找到这个问题的答案。我想知道在使用range()函数时是否可以使用变量。例如,我无法让它工作:

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?

Python 告诉我在使用 range 函数时不能使用变量。有谁能够帮助我?

采纳答案by ranendra

Since the user inputs is a stringand you need integervalues to define the range, you can typecast the input to be a integer value using intmethod.

由于用户输入是一个字符串并且您需要数值来定义范围,因此您可以使用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)

回答by Stanislav Teroff

You ask user to input a number

你要求用户输入一个数字

l = raw_input('Enter Length: ')

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

但问题是输入的数字将显示为字符串而不是 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. It works much faster.

如果您使用 Python 2.X,您还可以优化您的代码 - 您可以使用xrange代替 range 。它的工作速度要快得多。

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 是默认实现的

回答by Luis Manuel Sánchez Ubiera

Try this code:

试试这个代码:

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