我可以使用for循环而不是while循环吗?

时间:2013-01-15 21:23:09

标签: python

我有一个关于循环的基本问题。我正在尝试进入编程,目前我正在阅读“学习Python艰难之路”这本书,并且在前33中被困在第5号学习练习中: http://learnpythonthehardway.org/book/ex33.html

这就是我的代码:

i = 0
numbers = []

def main(i, numbers):
    userloop = int(raw_input("Type in max value for the loop > "))
    while i < userloop:

        print "At the top i is %d" % i
        numbers.append(i)
        userincrease = int(raw_input("Increase > "))
        i += userincrease

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


    print "The numbers: "
    print numbers
    for num in numbers:
    print num       


main(i, numbers)

问题是我想使用for循环而不是while循环。这是否可能然后,我该怎么做?我试过简单地交换

while i < userloop:

for i in range(userloop)

但是,每当它到达循环的“顶部”时,i值就会重置。

由于我对此非常陌生,如果我错过了一些明显的东西,请不要太吝啬。

顺便问一下,有没有人知道这本书开头是好还是我在浪费时间?

5 个答案:

答案 0 :(得分:4)

python中的for循环遍历in之后的表达式提供的一系列值。在Python中,我们使用术语iterable来表示可以生成这样一个系列的任何内容。这可以是range(),但它可以是任何可以迭代(循环)的东西。循环变量i在每次迭代时接收下一个值,无论之前的值是什么。

因此,以下是合法的:

for i in ('foo', 'bar', 'baz'):
    print i
    i = 'spam'

i = 'spam'基本上什么也没做。

你必须以不同的方式接近它; 跳过这些值:

print_at = 0
for i in range(userloop):
    if i >= print_at:
        print "At the top i is %d" % i
        numbers.append(i)
        userincrease = int(raw_input("Increase > "))
        print_at = i + userincrease

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

每当您要求用户增加时,我们会将值print_at更新为i的当前值加上该增加的总和,然后继续忽略大部分循环体直到i赶上print_at

答案 1 :(得分:2)

for循环和while循环之间存在关键区别。

for循环:执行循环体固定次数,计算迭代次数。

while循环:只要循环条件为真,就会重复执行循环体。

通常,从零开始并停在特定数字(例如userloop)时,意味着for循环是最合适的。但是,这个程序并没有说“我会从0计算到用户循环,每次都做这个东西”;它说“我从零开始,我会做这些事情,根据用户输入改变一个值,直到该值满足条件(&gt; userloop)”。

用户可以多次输入0,或输入负数,您可能永远不会退出循环。

答案 2 :(得分:1)

所以我查看了你链接到的Python the Hard Way网站上的问题......我认为他实际上只是要求你使用for循环和范围重写他的原始脚本,在这种情况下你可以做像这样的东西:

numbers = []

for i in range(6):
    print "at the top i is", i
    numbers.append(i)
    print "numbers now", numbers

print "finally numbers is:"
for num in numbers:
    print num

如果你运行它,你会得到这样的输出:

$ python loops.py 
at the top i is 0
numbers now [0]
at the top i is 1
numbers now [0, 1]
at the top i is 2
numbers now [0, 1, 2]
at the top i is 3
numbers now [0, 1, 2, 3]
at the top i is 4
numbers now [0, 1, 2, 3, 4]
at the top i is 5
numbers now [0, 1, 2, 3, 4, 5]
finally numbers is:
0
1
2
3
4
5

要回答有关增量声明的问题,如果有必要,请尝试:

for i in range(6):
    print "at the top i is", i
    numbers.append(i)

    i += 2
    print "numbers now", numbers
    print "at the bottom i is", i

print "finally numbers is:"
for num in numbers:
    print num

你会得到这样的输出:

$ python loops.py
at the top i is 0
numbers now [0]
at the bottom i is 2
at the top i is 1
numbers now [0, 1]
at the bottom i is 3
at the top i is 2
numbers now [0, 1, 2]
at the bottom i is 4
at the top i is 3
numbers now [0, 1, 2, 3]
at the bottom i is 5
at the top i is 4
numbers now [0, 1, 2, 3, 4]
at the bottom i is 6
at the top i is 5
numbers now [0, 1, 2, 3, 4, 5]
at the bottom i is 7
finally numbers is:
0
1
2
3
4
5

你看到这里发生了什么吗?请记住,范围函数会生成如下列表:
range(6) - &gt; [0,1,2,3,4,5]。
这是Python的for语句知道如何迭代(他们将这些类型的东西称为迭代)。无论如何,变量i在每次迭代中被绑定到范围(6)中的一个项(即列表[0,1,2,3,4,5])。即使你在for循环中对i做了一些事情,它也会被反弹到iterable中的下一个项目。因此,增量声明绝对不是必需的。在这种情况下,它只是增加了2,无论我是什么,但无论如何,它都像正常情况一样反弹。

好的,这就是我在改变你的特定代码时的错误,每次从使用while循环到使用带范围的for循环时都可以选择更改迭代器。

我认为你只是通过浏览你链接到的在线书籍的前几章来介绍函数,但是如果你之前没有看过递归,那可能会有点混乱。再次调用函数之前的if语句是保持当前值不超过范围中的值,这将导致超出最大递归深度的错误(python这样做是为了防止堆栈溢出错误我很确定)。

最后一点你可以用范围做这样的事情:
范围(0,10,2) - &gt;我在下面使用的[0,2,4,6,8]:

def my_loop(max, current=0, increment=1, numbers=[]):
    for x in range(current, max, increment):
        print "at the top, current is %d" % current
        numbers.append(current)

        increment = int(raw_input("Increase > "))
        current += increment

        print "numbers is now: ", numbers
        print "at the bottom current is %d" % current
        break

    if current < max:
        my_loop(max, current, increment, numbers)
    else:
        print "no more iterating!"


max = int(raw_input("Type in max value for the loop > "))    

my_loop(max)

我认为我不会这样做是真实的,但这至少是一个有趣的事情。

答案 3 :(得分:1)

我使用此代码完成了它,其中p是您在函数调用numba(p)中设置的参数

i = 0
elements = [ ]

def numba(p):
    for i in range(0, p):
        print "At the top i is %r" % i
        elements.append(i)
        print "Numbers now: ", elements
        print "At the bottom i is %r" % (i + 1)

numba(3)

答案 4 :(得分:0)

好吧,我猜你可以尝试向generators方向挖掘动态控制的for循环

相关问题