Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
每次迭代的Python“for循环”中的更改范围开始_Python_Python 2.7_For Loop - Fatal编程技术网

每次迭代的Python“for循环”中的更改范围开始

每次迭代的Python“for循环”中的更改范围开始,python,python-2.7,for-loop,Python,Python 2.7,For Loop,我是一名新手,正在使用2.7学习python。我正在尝试一些简单的脚本来测试python如何处理不同类型的循环 我的问题是:如果开始点被分配给一个变量,python能否在每次迭代中更改range函数的开始点?下面是我的代码示例: def build(n, period): n2 = n for digit in range(int(n2), 20): print "At the top i is %d" % n digit += period

我是一名新手,正在使用2.7学习python。我正在尝试一些简单的脚本来测试python如何处理不同类型的循环

我的问题是:如果开始点被分配给一个变量,python能否在每次迭代中更改range函数的开始点?下面是我的代码示例:

def build(n, period):
    n2 = n
    for digit in range(int(n2), 20):
        print "At the top i is %d" % n
        digit += period
        numbers.append(digit)

        print "Numbers now:", numbers
        print "At the bottom i is %d" % digit

        print "The Numbers:"
        n2 += period

        for num in numbers:
            print num


key = raw_input("Press 1 to call function \"build\", press any other key to quit.")
if key == "1":
    i = raw_input("What integer is our start value?")
    amt = raw_input("What is the common difference?")
    numbers = [int(i)]
    build(int(i),int(amt))

else:
    quit()

我尝试在函数中使用第二个局部变量'n2',这样我可以保持'n'的初始值不变,然后重新定义每次迭代的范围。附加列表中的第一个数字按公共差移动,但之后总是按+1整数步进。我可以通过“while”循环轻松实现这一点,但我很好奇“for”循环是否可以用来实现这一点?

它不会以您期望的方式工作。表达式rangeintn2,20在for循环开始时仅计算一次。您不能以这种方式更改for循环的范围

您可以修改的是函数中的一个步骤参数,但它不会更改您的起点-它只定义迭代过程中的下一个元素。

在for循环开始时调用该函数时,会创建一个固定列表。您可以将for循环的顶部视为将n2分配给该列表的下一个元素,而不管您在循环中做什么。如果要更改范围的周期,请使用第三个参数:

range(n, 20, period)

将以大小周期的步长而不是大小为1的步长在范围内移动。

如何使索引超出范围?如果要查找其他循环,可以使用while循环-而n2<20:n2+=period。您还必须将数字数组传递给函数。否则,您可以将其称为全局变量。