简体   繁体   English

Python 3:使用变量执行for循环x次

[英]Python 3: Executing a For loop x number of times by using a variable

Edit: Fixed the screwed up brackets, sorry.编辑:抱歉,修复了搞砸的括号。 Should have caught this.应该抓住这个。 Let's see if this clarifies what I'm trying to do.让我们看看这是否阐明了我正在尝试做的事情。

I want to do a basic program that takes the variable "run" and runs the following code that number of times by using a For loop.我想做一个基本程序,它接受变量“运行”并使用 For 循环运行以下代码的次数。

run = 3
def program(run):
    for i in range(5):
        print("The number is",i)

program(run)

What I want is to get is:我想要的是:

the number is 0
the number is 1
the number is 2
the number is 3
the number is 4
the number is 0
the number is 1
the number is 2
the number is 3
the number is 4
the number is 0
the number is 1
the number is 2
the number is 3
the number is 4

ie the "program" loops however many times I set "run" to equal.即“程序”循环,但我将“运行”设置为相等很多次。

Let's break the code and the error message down a bit:让我们稍微分解一下代码和错误消息:

    for i in range[5]:
TypeError: 'type' object is not subscriptable

"Subscripting" is the way you access a particular element in a container, like a list or a dict. “下标”是您访问容器中特定元素的方式,例如列表或字典。 For example, to get the first (0th) element of a list called foo , you'd say foo[0] , and to get the value associated with the key "bar" in a dictionary called foo , you'd say foo["bar"] .例如,要获取名为foo的列表的第一个(第 0 个)元素,您可以说foo[0] ,而要获取与名为foo的字典中的键"bar"相关联的值,您可以说foo["bar"]

Note that when you just use the [] symbols by themselves (instead of putting them after some other identifier), they serve a different purpose: they construct a list .请注意,当您单独使用[]符号(而不是将它们放在其他标识符之后)时,它们具有不同的用途:它们构造一个list The expression [5] is a list that contains a single element (the number 5 ).表达式[5]是一个包含单个元素(数字5 )的列表。 To represent more elements, you comma-separate them, eg [0, 1, 2, 3, 4] .要表示更多元素,请用逗号分隔它们,例如[0, 1, 2, 3, 4]

So what the error is telling you is that a type object can't be subscripted.所以错误告诉你的是type对象不能被下标。 Does that mean that range is a type ?这是否意味着range是一种type Yes!是的! In Python, a range is a type of iterable object that represents a range of numbers.在 Python 中, range是一种可迭代对象,表示一个数字范围。 On its own, the word range in a Python program refers to the entire class of range objects (that is, a type of object), not a particular range object.就其本身而言,字range在Python程序指的是整个类的range对象(即,一个type的对象),而不是一个特定的范围对象。

You construct a range the same way you construct most objects, by calling the type as a constructor function, with parameters in parentheses.您可以像构造大多数对象一样构造一个range ,方法是将类型作为构造函数调用,参数在括号中。 For example, to construct a range with 5 numbers in it (0 to 4, similar to the list [0, 1, 2, 3, 4] ) you can simply say range(5) .例如,要构造一个包含 5 个数字的range (0 到 4,类似于列表[0, 1, 2, 3, 4] ),您可以简单地说range(5)

So to print all the numbers from 0 to 4 you can do:因此,要打印从 0 到 4 的所有数字,您可以执行以下操作:

    for i in range(5):
        print("The number is", i)

In your code, the run variable serves no purpose and can be removed completely.在您的代码中, run变量没有任何作用,可以完全删除。 Functions can take any number of parameters, or none at all, and since in this case your function doesn't do anything with the parameter you pass in, it can be simply:函数可以接受任意数量的参数,或者根本不接受,因为在这种情况下,您的函数不会对您传入的参数执行任何操作,因此它可以很简单:

def program():
    for i in range(5):
        print("The number is", i)

program()

If you wanted to make the length of the range variable, that would make sense as a parameter -- you just need to pass the parameter along to your range construction:如果你想让范围变量的长度,作为参数是有意义的——你只需要将参数传递给你的range构造:

def program(num):
    for i in range(num):
        print("The number is", i)

runs = 3
for _ in range(runs):
    program(5)

You'd use range, but you would use parenthesis to call the function instead of braces.您将使用范围,但您将使用括号而不是大括号来调用函数。 Ie range(5) instead of range[5] .range(5)而不是range[5] Or you could use your run variable like range(run)或者你可以使用你的run变量,比如range(run)

In short you are seeing the error because you are using square brackets and not parentheses range() is a function.简而言之,您看到错误是因为您使用的是方括号而不是括号range()是一个函数。 Change it to将其更改为

def program(run):
    for i in range(5):
        print("The number is",i)

program(run)
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4

and it works fine.它工作正常。

If you want to the program to loop the same number of times as specified in run then you can do this:如果您希望程序按照 run 中指定的次数循环,则可以执行以下操作:

run = 5
def program(run):
    for i in range(run):
        print("the number is",i)

program(run)
def program(n):
    for i in range(0,n+1):
        print("The number is",i)

program(5)

ouput输出

The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5

Whelp, I finally figured it out - the reason I couldn't seem to find a solution anywhere to "could this be done and how would I go about it" is that in Python at least, a For statement cannot do this kind of loop, only a While can.哎呀,我终于弄明白了 - 我似乎无法在任何地方找到“这是否可以完成以及我将如何进行”的解决方案的原因是至少在 Python 中,For 语句不能执行这种循环,只有一个 While 可以。

So my experiment of trying to do this via a For is a moot point, it's not something that can be coded without using While.所以我尝试通过 For 来做到这一点的实验是有争议的,它不是不使用 While 就可以编码的东西。

Thanks for the help.谢谢您的帮助。

Give this a try.试试这个。 Hopefully understood the assignment:希望理解任务:

run = 3


def program(run):
    nums = [f'The number is: {n}' for r in range(run) for n in range(5)]
    print('\n'.join(nums))

program(run)

This uses list comprehension to loop twice which translates to:这使用列表理解来循环两次,这转化为:

run = 3


def program(run):
    for r in range(run):
        for n in range(5):
            print(f'The number is: {n}')

program(run)

Or:或者:

run = 3


def program():
    for n in range(5):
        print(f'The number is: {n}')

for r in range(run):
    program()

Output: Output:

The number is: 0
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 0
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 0
The number is: 1
The number is: 2
The number is: 3
The number is: 4

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

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