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从单元素字典中获取key和value的实例

之前写代码很多时候会遇到这么一种情况:在python的字典中只有一个key/value键值对,想要获取其中的这一个元素还要写个for循环获取。 网上搜了一下,发现还有很多简单的方法: 方...

python实现三维拟合的方法

如下所示: from matplotlib import pyplot as plt import numpy as np from mpl_toolkits.mplot3d imp...

Python+Turtle动态绘制一棵树实例分享

Python+Turtle动态绘制一棵树实例分享

本文实例主要是对turtle的使用,实现Python+turtle动态绘制一棵树的实例,具体代码: # drawtree.py from turtle import Turtle...

Django 批量插入数据的实现方法

项目需求:浏览器中访问django后端某一条url(如:127.0.0.1:8080/get_book/),实时朝数据库中生成一千条数据并将生成的数据查询出来,并展示到前端页面 view...

浅谈Python2.6和Python3.0中八进制数字表示的区别

在Python2.x中表示八进制的方式有两种:以'0'开头和以'0o'(字母o)开头:   Python2.7中: >>> 0100 64 >>&g...