本文介绍了打印星号的三角形图案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用嵌套的循环和print('*', end=' ')来创建显示的模式这里:

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

当我启动模式C和D时,我尝试以下操作:

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

但是结果与A和B相同.我们非常感谢您的帮助!

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

推荐答案

模式C和D都需要前导空格,并且您不打印任何空格,而只打印星号.

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) * '*')

以下是输出:

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

Pattern D

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

更详细地考虑以下这一行:

In more detail, consider this line:

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

它将打印(11-e)个空格,后跟e个星号.这提供了制作图案所需的前导空间.

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

如果您的老师想要嵌套循环,那么您可能需要将print((11-e) * ' ' + e * '*')转换成循环打印每个空间,一次打印一个空间,然后打印每个星星,一次打印一个空间.

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.

如果按照我给出的有关嵌套循环的提示进行操作,您将可以找到模式C的解决方案,如下所示:

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

这篇关于打印星号的三角形图案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-11 11:21