2017-02-15 179 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