Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
497 views
in Technique[技术] by (71.8m points)

for loop - Print a triangular pattern of asterisks

I am required to use nested for loops and print('*', end=' ') to create the pattern shown here: enter image description here

And here is my code. I have figured out the first two.

n = 0

print ("Pattern A")
for x in range (0,11):
    n = n + 1
    for a in range (0, n-1):
        print ('*', end = '')
    print()
print ('')
print ("Pattern B")
for b in range (0,11):
    n = n - 1
    for d in range (0, n+1):
        print ('*', end = '')
    print()
print ('')

When i start pattern C and D, i try the following:

print ("Pattern C")
for e in range (11,0,-1):
    n = n + 1
    for f in range (0, n+1):
        print ('*', end = '')
    print()
print ('')
print ("Pattern D")
for g in range (11,0,-1):
    n = n - 1
    for h in range (0, n-1):
        print ('*', end = '')
    print()

But the result is the same as A and B. Help is appreciated!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Both patterns C and D require leading spaces and you are not printing any spaces, just stars.

Here is alternative code that prints the required leading spaces:

print ("Pattern C")
for e in range (11,0,-1):
    print((11-e) * ' ' + e * '*')

print ('')
print ("Pattern D")
for g in range (11,0,-1):
    print(g * ' ' + (11-g) * '*')

Here is the output:

Pattern C
***********
 **********
  *********
   ********
    *******
     ******
      *****
       ****
        ***
         **
          *

Pattern D

          *
         **
        ***
       ****
      *****
     ******
    *******
   ********
  *********
 **********

In more detail, consider this line:

print((11-e) * ' ' + e * '*')

It prints (11-e) spaces followed by e stars. This provides the leading spaces needed to make the patterns.

If your teacher wants nested loops, then you may need to convert print((11-e) * ' ' + e * '*') into loops printing each space, one at a time, followed by each star, one at a time.

Pattern C via nested loops

If you followed the hints I gave about nested loops, you would have arrived at a solution for Pattern C like the following:

print ("Pattern C")
for e in range (11,0,-1):
    #print((11-e) * ' ' + e * '*')
    for d in range (11-e):
        print (' ', end = '')
    for d in range (e):
        print ('*', end = '')
    print()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...