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遍历文件夹 处理json文件的方法

有两种做法:os.walk()、pathlib库,个人感觉pathlib库的path.glob用来匹配文件比较简单。 下面是第二种做法的实例(第一种做法百度有很多文章): from...

关于pymysql模块的使用以及代码详解

pymysql模块的使用 查询一条数据fetchone() from pymysql import * conn = connect( host='127.0.0.1',...

Python实现图像的垂直投影示例

Python实现图像的垂直投影示例

Python + OpenCV 直接上代码 import cv2 import numpy as np from matplotlib import pyplot as plt...

python发送邮件接收邮件示例分享

接收邮件 复制代码 代码如下:import poplib,pdb,email,re,timefrom email import header POP_ADDR = r'pop.126.c...

详解Python中的循环语句的用法

一、简介       Python的条件和循环语句,决定了程序的控制流程,体现结构的多样性。须重要理解,if、while、for以及与它...