在python中将for循环转换为while循环 [英] Converting for loops to while loops in python

查看:125
本文介绍了在python中将for循环转换为while循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力寻找一种有效的方法将这些 for 循环转换为一组有效的 while 循环.有什么建议?我正在使用 2.7

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 printTTriangle(height):
 for row in range(1,height+1):
    # print row T's
    for col in range(1,row+1):
        print 'T', 
    print

感谢大家的帮助!

推荐答案

是这样的:

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

综合起来:

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

这篇关于在python中将for循环转换为while循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆