有没有办法在 python 中的 "for" 循环中操作计数器

Is there a way to manipulate the counter in a "for" loop in python

“计数器”是指我所附代码中的“i”。我刚刚为大学选择了 Python,我想知道我是否可以像在 C++ 中那样操纵计数器

n=5
for i in range(n):
    print("Test")
    i=i-1

这段代码的结果是

测试 测试 测试 测试 测试

但我想知道你是否可以操纵“i”使其成为一个无限循环

如果我的意思不够清楚,欢迎提问

问题 是 python 使用迭代器,这并不意味着在迭代时被操纵。一个好的规则是,如果您需要操作 for 循环,则不应使用 for 循环。更好的方法是使用 while 循环。一个例子:

n = 10
while n > 5:
    print("Test " + n)
    n -= 2
    if n == 6:
        n += 1

或者无限循环:

while True:
    print("Test")

查看 this 了解更多信息。