python-while循环练习四种星星形状

完成下面四种形状的星星

1.
*
**
***
****
*****
2.
    *
   **
  ***
 ****
*****

3. 
*****
****
***
**
*

4.
*****
 ****
  ***
   **
    *

题目分析:行数为一个最外层循环,里面嵌套控制*和空格的两个小循环。

1.
*
**
***
****
*****

row = 1
while row <= 5 :
    col = 1			# 每一行要打印的星星就是和当前行数是一致的
    while col <= row:
        print('*',end='')	# 不换行输出
        col += 1
    print()			 # 手动换行
    row +=1

在这里插入图片描述

2.
    *
   **
  ***
 ****
*****

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

在这里插入图片描述

3. 
*****
****
***
**
*

row = 1
while row <= 5:			#行数,循环五次
    a = 1
    cel = 1
    while a<=6-row:		#a控制*=6-行数
        print('*',end='')
        a +=1
    while cel >row and cel < 5:		#cel空格=行数-1 并且最大为4个空格
        print(' ',end='')
        cel += 1
    print()
    row += 1

在这里插入图片描述

4.
*****
 ****
  ***
   **
    *
row = 1
while row <= 5:					#行数,循环五次
    a = 1
    cel = 1
    while (cel < row) and (cel < 5):	#cel空格数=行数-1,最大为4
        print(' ',end='')
        cel += 1
    while a <= 6-row:				#a控制*,a=6-行数,例如:第一行*的数量5=6-1 
        print('*',end='')
        a += 1
    print()
    row += 1

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43067754/article/details/84311497