Home  >  Article  >  Backend Development  >  The while loop in python prints the four shapes of stars

The while loop in python prints the four shapes of stars

云罗郡主
云罗郡主Original
2019-01-22 15:24:256509browse

Continuously output five lines of * on the console, and the number of each asterisk increases once [Recommended reading: Python video tutorial]
*
**
***
****
*****

#1.定义一个行计数器row = 1while row <= 5:    #定义一个列计数器
    col = 1
    #开始循环
    while col <= row:
        print(&#39;*&#39;,end=&#39;&#39;)
        col += 1
    print(&#39;&#39;)
    row += 1

The while loop in python prints the four shapes of stars

#1.定义一个行计数器row = 1while row <= 5:    #定义一个列计数器
    col = 5
    #开始循环
    while col >= row:
        print(&#39;*&#39;,end=&#39;&#39;)
        col -= 1
    print(&#39;&#39;)
    row += 1

The while loop in python prints the four shapes of stars

##So what if you want spaces first, then *

row = 1while row <= 5:  # 行数,循环五次
    a = 1
    col = 1
    while a <= 5 - row:  # a控制每行的空格数=5-行数,例如:第一行为5-1=4个空格
        print(&#39; &#39;, end=&#39;&#39;)  # 不换行
        a += 1
    while col <= row:  # col控制*的数量=行数
        print(&#39;*&#39;, end=&#39;&#39;)
        col += 1
    print()
    row += 1

The while loop in python prints the four shapes of stars

Another arrangement

row = 1while row <= 5:  # 行数,循环五次
    a = 1
    col = 1
    while a <= row - 1:  # a控制每行的空格数=5-行数,例如:第一行为5-1=4个空格
        print(&#39; &#39;, end=&#39;&#39;)  # 不换行
        a += 1
    while  col <= 6-row:  # col控制*的数量=行数
        print(&#39;*&#39;, end=&#39;&#39;)
        col += 1
    print()
    row += 1

The while loop in python prints the four shapes of stars

The above is the detailed content of The while loop in python prints the four shapes of stars. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn