Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
503 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 Reply

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()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...