python中while循环打印星星的四种形状

在控制台连续输出五行*,每一行星号数量一次递增
*
**
***
****
*****

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




<p> <img alt="" class="has" height="167" src="https://img-blog.csdnimg.cn/20190117145604733.png" width="743" /></p>

<p>如果想要星星倒过来呢</p>

<pre class="has">
<code class="hljs language-python">#1.定义一个行计数器
row = 1
while row &lt;= 5:
    #定义一个列计数器
    col = 5
    #开始循环
    while col &gt;= row:
        print('*',end='')
        col -= 1
    print('')
    row += 1

那么如果想让空格先,然后*呢

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




<p><img alt="" class="has" height="149" src="https://img-blog.csdnimg.cn/20190117160511332.png" width="601" /></p>

<p>另外一种排列方式</p>

<pre class="has">
<code class="hljs language-python">row = 1
while row &lt;= 5:  # 行数,循环五次
    a = 1
    col = 1
    while a &lt;= row - 1:  # a控制每行的空格数=5-行数,例如:第一行为5-1=4个空格
        print(' ', end='')  # 不换行
        a += 1
    while  col &lt;= 6-row:  # col控制*的数量=行数
        print('*', end='')
        col += 1
    print()
    row += 1

ok~

来源:https://blog.csdn.net/weixin_40543283/article/details/86527521

猜你喜欢

转载自www.cnblogs.com/datiangou/p/10289689.html