简体   繁体   中英

How can I turn this 'while' loop into a 'for' loop?

I'm working through LPTHW, on exercise 33, and on the very last study drill, they ask to change the code I have to a 'for' loops, rather than the 'while' loop I've written. Here's the code I've come up with:

numbers = []

def loop(i, x, new_num):
    while i < x:
        print "At the top i is %d" % i
        numbers.append(i)

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


    print "The numbers: "

    for num in numbers:
        print num

loop(0, 10, 6)

Now the study drill instructs me to, "Now, write it to use for- loops and range instead. Do you need the incrementor in the middle anymore? What happens if you do not get rid of it?"

This is how far I've managed to get, but I've got no idea if I'm going in the right direction. Basically just shooting in the dark:

numbers = []
new_numbers = [0]
def loop2():
    for i in new_numbers: 
        print "At the top i is %d" % i
        numbers.append(i)

I don't know where to insert a 'range' function either. If I managed to turn this into a 'for' loop that did exactly what this 'while' loop code does, what would it look like?

In your working example with the while loop, you assign i = i + new_num during each loop, so you iterate i by new_num . This can be easily replicated with range .

range takes up to 3 arguments: (starting_point, upper_bound, num_to_iterate_by)

In your code, i is the starting point, x is the upper bound, and new_num is the number you iterate by each loop.

Note: The third argument in a for loop is optional. Python will use 1 as the default iterator if none is specified.

Changes from your code:

  1. Replaced while i < x: with for i in range(i, x, new_num): at line 4
  2. Removed i = i + new_num at line 8

-

numbers = []

def loop(i, x, new_num):
    for i in range(i, x, new_num):
        print "At the top i is %d" % i
        numbers.append(i)

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


    print "The numbers: "

    for num in numbers:
        print num

loop(0, 10, 6)

Output:

At the top i is 0
Numbers now:  [0]
At the bottom i is 0
At the top i is 6
Numbers now:  [0, 6]
At the bottom i is 6
The numbers: 
0
6

By using for in range => for i in range(x,y)

numbers = []

def loop(i, x, new_num):
    for i in range(i, x):
        print "At the top i is %d" % i
        numbers.append(i)

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


  print "The numbers: "

  for num in numbers:
    print num

loop(0, 10, 6)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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