循环中无法识别for循环内的变量

时间:2017-05-16 07:28:19

标签: python python-2.7 function variables for-loop

在变量zx执行时,无法识别应增加y值的变量x。 变量'z'设置为3时,我希望每次循环运行时x的值增加3,而是每次增加1。

def lists(x, y, z):
    numbers = []
    for x in range(x, y):
        print "At the top x is %d" % x
        numbers.append(x)

        x += z
        print "Numbers now: ", numbers
        print "At the bottom x is %d" % x

    print "The numbers: "

    for num in numbers:
        print num

lists(int(raw_input("Starting Value: ")), int(raw_input("Ending Value: ")),
int(raw_input("Increment Amount: ")))

1 个答案:

答案 0 :(得分:0)

for循环是for-each construct;它需要range()生成的序列,并依次将x设置为该序列中的每个值。

无论你使用循环体中的x 做什么都没有区别,因为for并不关心你对x做什么之后。

如果您想将z用作步长,请直接将其传递给range()

for value in range(x, y, z):
    numbers.append(value)

或者完全放弃for循环,因为在Python 2中range()创建了一个列表对象:

numbers = range(x, y, z)

如果您想模拟类似C的for循环(可以更改循环体中的循环变量),请使用 while循环而不是:

while x < y:
    x += z
    print x
相关问题