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

yipeiwu_com6年前Python基础

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

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

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

如果想要星星倒过来呢

#1.定义一个行计数器
row = 1
while row <= 5:
 #定义一个列计数器
 col = 5
 #开始循环
 while col >= 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

另外一种排列方式

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

ok~

以上这篇python实现while循环打印星星的四种形状就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python中xrange和range的区别

range 函数说明:range([start,] stop[, step]),根据start与stop指定的范围以及step设定的步长,生成一个序列。range示例:复制代码 代码如下...

Python 读取图片文件为矩阵和保存矩阵为图片的方法

读取图片为矩阵 import matplotlib im = matplotlib.image.imread('0_0.jpg') 保存矩阵为图片 import numpy a...

python实现列表的排序方法分享

python实现列表的排序方法分享

这次代码主要是实现列表的排序,使用sort函数实现,sort函数是对列表中的元素按照特定顺序进行排序,默认reverse,为false,从小到大排序, 如果指定reverse=...

Pandas之Dropna滤除缺失数据的实现方法

约定: import pandas as pd import numpy as np from numpy import nan as NaN 滤除缺失数据 pandas的设计目...

Python 读取 YUV(NV12) 视频文件实例

Python 读取 YUV(NV12) 视频文件实例

一、YUV 简介 YUV:是一种颜色编码方法,常使用在各个视频处理组件中 Y'UV, YCbCr, YPbPr等专有名词都可以称为 YUV,彼此有重叠 Y表示明亮度(单取此通道即可...