2017-02-15 180 views
2

您好我想知道如何使用嵌套循环吸取输出嵌套while循环绘制图案

## 
# # 
# # 
# # 
# # 
#  # 
#  # 
#  # 

这种模式我发现了如何做一个循环,不嵌套的,但我我很好奇如何使用一个嵌套的while循环来绘制它。

while r < 7: 
    print("#{}#".format(r * " ")) 
    r = r + 1 
+1

你可以用嵌套'while'循环,但单一的'for'环就足以做到这一点。如果你试图围绕嵌套循环包装你的头,你最好能找到一个自然的解决方案 –

+0

为什么用一个嵌套的while循环增加复杂性,如果你可以更简单地使用单一循环'while'? – Peter

+0

该任务让我使用嵌套循环,不知道为什么。我可以只使用一个循环:S –

回答

1

这里是一个回答您的实际问题:使用两个嵌套while循环。

num_spaces_wanted = 0 
while num_spaces_wanted < 7: 
    print('#', end='') 
    num_spaces_printed = 0 
    while num_spaces_printed < num_spaces_wanted: 
     print(' ', end='') 
     num_spaces_printed += 1 
    print('#') 
    num_spaces_wanted += 1 

正如打印语句所示,这是针对Python 3.x的。将它们调整为2.x或添加行from __future__ import print_function以获得3.x样式打印。

1

如果您打算做这在Python 你不需要嵌套循环。

编辑有两个回路

#!/bin/python 
import sys 

n = int(raw_input().strip()) 
for i in xrange(n): 
    sys.stdout.write('#') 
    for j in xrange(i): 
     sys.stdout.write(' ') 
    sys.stdout.write('#') 
    print 
+1

为什么不只是'xrange(n)'? –

+0

@PatrickHaugh更新:) –

+0

但OP特别要求嵌套while循环。 –

-1

的嵌套循环的最有效的解决方案:

#!/bin/python 

n = int(raw_input().strip()) 
for i in xrange(n): 
    string = "#" + i * " " + "#" 
    print string 
    for -1 in xrange(n) 
    # Do nothing 
0

还有很多其他的答案已经正确地回答了这个问题,但我认为下面这样做在概念上更简单一些,它应该更容易学习。

spaces = 0 

while spaces < 8: 
    to_print = "#" 

    count = 0 
    while count < spaces: 
     to_print += " " 
     count += 1 

    to_print += "#" 

    print to_print 
    spaces += 1