简体   繁体   English

使用 for 循环打印三角形金字塔图案 python

[英]Print Triangle Pyramid pattern using for loop python

I am using the following for loop code to print star pattern and the code is working perfectly fine.我正在使用以下 for 循环代码来打印星形图案,并且代码运行良好。 Here is my code这是我的代码

for i in range(1,6):
    for j in range(i):
        print("*", end=" ")
    print()

Output of this code is displaying as此代码的 Output 显示为

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

Now my question is how to print output like现在我的问题是如何打印 output 之类的

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

Actually, that can be done in a single loop:实际上,这可以在一个循环中完成:

for i in range(1, 6):
  print (' ' * (5 - i), '* ' * i)

This can be achieved in one loop and center padding.这可以在一个循环和中心填充中实现。

n = int(input('Enter the row you want to print:- '))
sym = input('Enter the symbol you want to print:- ')
for i in range(n):
    print((sym * ((2 * i) + 1)).center((2 * n) - 1, ' '))
# right angle triangle
for i in range(1, 10):
    print("* " * i)

# equilateral triangle
# using reverse of range
for i , j in zip(range(1, 10), reversed(range(1, 10)):
    print(" " * j + "* " * i)

# using only range()
for i, j in zip(range(1, 10), range(10, -1, -1):
    print(" " * j + "* " * i)

You just need to add spaces loop ahead:您只需要在前面添加空格循环:

for i in range(1,6):
    for j in range(6-i):
        print(" ", end="")
    for j in range(i):
        print("*", end=" ")
    print()

Here is another way这是另一种方式

size = 7
m = (2 * size) - 2
for i in range(0, size):
    for j in range(0, m):
        print(end=" ")
    m = m - 1 # decrementing m after each loop
    for j in range(0, i + 1):
        # printing full Triangle pyramid using stars
        print("* ", end=' ')
    print(" ")

Try this :-尝试这个 :-

Description for printing star pattern:-星形图案印刷说明:-

1)First line is for Function to demonstrate printing pattern triangle 1)第一行是Function来演示印刷图案三角形

2)Second line is for number of spaces 2)第二行是空格数

3)Third line for outer loop to handle number of rows. 3)外循环的第三行处理行数。

4)in loop inner loop to handle number spaces and values changing according to requirements. 4) in loop 内循环处理根据需要改变的数字空间和值。

5)After loop each loop decrementing k value. 5)循环后每次循环递减k值。

6)After decrementing k value inner loop to handle number of columns and values changing according to outer loop. 6)内循环递减k值后,处理根据外循环变化的列数和值。

7)printing '*' after j loop. 7) 在 j 循环后打印 '*'。

8)Ending line after each row 8)每行后的结束行

def triangle(n): 
  k = 2*n - 2
  for i in range(0, n): 


    for j in range(0, k): 
        print(end=" ") 

    k = k - 1

    for j in range(0, i+1): 

        print("* ", end="") 


    print("\r") 


n = 5
triangle(n) 
def triangle(val: str, n: int, type: str):
    for i in range(n):
        if type == "regular":
            print((i + 1) * val)
        elif type == "reversed":
            print((n - i) * val)
        elif type == "inverted":
            print((n - (i + 1)) * " " + (i + 1) * val)
        elif type == "inverted reversed":
            print(i * " " + (val * (n - i)))
        elif type == "triangle":
            print((n - (i + 1)) * " " + ((2*i)+1) * val) 

Call the function like this像这样调用函数

triangle("*", 5, 'triangle')

Output输出

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

.very simple answer.. don't go for complex codes.. .非常简单的答案..不要去复杂的代码..

first try to draw a pyramid.首先尝试画一个金字塔。 by * ..then u easly understand the code..my solution is.. simplest..here example of 5 lines pyramid..通过* ..那么你很容易理解代码..我的解决方案是..最简单的..这里是5行金字塔的例子..

number_space  =  5
for   i   in   range (5)

     print('/r')

     print (number_space *"  ", end='')

     number_space=number_space-1

     for star in range (i+1):

                print("*",end="  ")

Use String Multiplication, To simply multiply a string, this is the most straightforward way to go about doing it:使用字符串乘法,要简单地将字符串相乘,这是最直接的方法:

num = 5 for e in range(num, 0, -1): print(" " (e-1)+(" " (num-e+1))+(" "*(num-e))) num = 5 for e in range(num, 0, -1): print(" " (e-1)+(" " (num-e+1))+(" "*(num-e)))

Late to answer.回答晚了。 But as other mentioned, this can be done in a single loop like below但正如其他人提到的,这可以在一个循环中完成,如下所示

j=1
for i in range(10,0,-1):
    print(" "*i,"*"*j)
    j+=2

Method #1: Comprehension version方法#1:理解版本

This could be easiest way to print any pattern in Python这可能是在Python打印任何模式的最简单方法

n = 5
print('\n'.join([('* '*i).center(2*n) for i in range(1,n+1)]))

Use center method of str , give it a width as parameter and it will centered the whole string accordingly.使用str center方法,给它一个宽度作为参数,它会相应地将整个字符串居中。

Method #2: Regular version方法#2:普通版

n = 5
for i in range(1,n+1):
  print(('* '*i).center(2*n))

Here's the easiest way to print this pattern:这是打印此图案的最简单方法:

n = int(input("Enter the number of rows: "))
for i in range(1,n+1):
    print(" "*(n-i) + "* "*i)

You have to print spaces (ni) times where n is the number of rows and i is for variable of loop and add it with stars i times.您必须打印空格 (ni) 次,其中 n 是行数,i 是循环变量,并添加星号 i 次。 This will give you the desired pattern.这将为您提供所需的模式。 See the above mentioned code for better understandability.请参阅上面提到的代码以获得更好的理解。

j=1 j=1

for i in range(5,0,-1):对于我在范围内(5,0,-1):

print(" "*i, end="")

while j<6:
    print("* "*j)
    j=j+1
    break
          #n=Number of rows
          def get_triangle(n):
              space,star=" ","* "
              for i in range(1,n+1):
                   print((n-i)*space + star*i)
           
                         


          get_triangle(5)
function printPyramid($n)
{
    //example 1
    for ($x = 1; $x <= $n; $x++) {
        for ($y = 1; $y <= $x; $y++) {
            echo 'x';
        }
        echo "\n";
    }

    // example 2
    for ($x = 1; $x <= $n; $x++) {
        for ($y = $n; $y >= $x; $y--) {
            echo 'x';
        }
        echo "\n";
    }

    // example 3

    for($x = 0; $x < $n; $x++) {
        for($y = 0; $y < $n - $x; $y++) {
            echo ' ';
        }
        for($z = 0; $z < $x * 2 +1; $z++) {
            echo 'x';
        }
        echo "\n";
    }


}

#CPP Program for Print the dynamic pyramid pattern by using one loop in one line. #CPP 程序用于在一行中使用一个循环来打印动态金字塔图案。

https://www.linkedin.com/posts/akashdarji8320_cpp-cplusplus-c-activity-6683972516999950336-ttlP https://www.linkedin.com/posts/akashdarji8320_cpp-cplusplus-c-activity-6683972516999950336-ttlP

#include

using namespace std;

int main() {
    int rows;

    cout<<"Enter number of rows :: ";
    cin>>rows;

    for( int i = 1, j = rows, k = rows; i <= rows*rows; i++ )
        if( i >= j && cout<<"*" && i % k == 0 && (j += rows-1) && cout<<endl || cout<<" " );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM