在python中将循环转换为while循环

在python中将循环转换为while循环

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

问题描述

我很努力地找到一种有效的方法来将这些 循环转换为循环的工作集。有什么建议么?我使用2.7

  def printTTriangle(height):
用于范围内的行(1,height + 1):
print行T's
(1,row + 1):
print'T',
print

谢谢大家的帮助!

解决方案

像这样:

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

我是这么做的。例如,让我们转换这一行:

 用于范围内的行(1,height + 1):

第一步:创建一个迭代变量,并将其初始化为范围的起始值:

  row = 1 

第二步:将范围的结尾值转换为循环条件,并小心处理索引:

  while row<高度+ 1:

最后,不要忘记增加循环递增迭代变量: p>

  row + = 1 

放在一起:

  row = 1 
while row<身高+ 1:
行+ = 1


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

Thank you all for your help!

解决方案

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

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

08-26 06:58