Reputation: 97
Hi I'm wondering on how to use a nested loop to draw this pattern on the output
##
# #
# #
# #
# #
# #
# #
# #
I found out how to do it in a loop without nested, but I am curious as to how to draw this using a nested while loop.
while r < 7:
print("#{}#".format(r * " "))
r = r + 1
Upvotes: 2
Views: 2448
Reputation: 22544
Here is an answer to your actual question: using two nested while loops.
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
As the print statements show, this is for Python 3.x. Adjust them for 2.x or add the line from __future__ import print_function
to get the 3.x style printing.
Upvotes: 1
Reputation: 1644
There are a number of other answers which already correctly answer the question, but I think the following does so in a conceptually more simple way, and it should make it easier to learn from.
spaces = 0
while spaces < 8:
to_print = "#"
count = 0
while count < spaces:
to_print += " "
count += 1
to_print += "#"
print to_print
spaces += 1
Upvotes: 0
Reputation: 508
The most efficient solution for a nested loop:
#!/bin/python
n = int(raw_input().strip())
for i in xrange(n):
string = "#" + i * " " + "#"
print string
for -1 in xrange(n)
# Do nothing
Upvotes: -1
Reputation: 4643
If you intend to do this in python You don't need a nested loop.
Edit With two loops
#!/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
Upvotes: 1