Converting for loops to while loops in python

后端 未结 3 1512
既然无缘
既然无缘 2020-12-11 08:55

I am struggling to find an efficient way to convert these for loops to a working set of while loops. Any Suggestions? I am using 2.7

def pr         


        
3条回答
  •  心在旅途
    2020-12-11 09:41

    It's like this:

    def printTTriangle(height):
        row = 1
        while row < height+1:
            col = 1
            while col < row+1:
                print 'T', 
                col += 1
            print
            row += 1
    

    Here's how I did it. For example, let's convert this line:

    for row in range(1, height+1):
    

    First step: create an iteration variable and initialize it in the starting value of the range:

    row = 1
    

    Second step: transform the ending value of the range into the loop condition, and careful with the indexes:

    while row < height+1:
    

    Finally, don't forget to advance the loop incrementing the iteration variable:

    row += 1
    

    Putting it all together:

    row = 1
    while row < height+1:
        row += 1
    

提交回复
热议问题