Print a triangular pattern of asterisks

后端 未结 15 1025
慢半拍i
慢半拍i 2020-11-30 11:01

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

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

15条回答
  •  粉色の甜心
    2020-11-30 11:32

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

提交回复
热议问题