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+PyQT实现系统桌面时钟

用Python + PyQT写的一个系统桌面时钟,刚学习Python,写的比较简陋,但是基本的功能还可以。 功能: ①窗体在应用程序最上层,不用但是打开其他应用后看不到时间 ②左键双击全...

python简单实现矩阵的乘,加,转置和逆运算示例

本文实例讲述了python简单实现矩阵的乘,加,转置和逆运算。分享给大家供大家参考,具体如下: 使用python完成矩阵的乘,加,转置和逆: # -*- coding:utf-8 -...

在Django的URLconf中进行函数导入的方法

看下这个 URLconf: from django.conf.urls.defaults import * from mysite.views import hello, curre...

python实现全盘扫描搜索功能的方法

由用户指定需要扫描的盘符或目录,输入需要查找的文件或者文件夹名称(不包含中文名称) 代码: # encoding=utf-8 import os.path import stat #...

Python3 Post登录并且保存cookie登录其他页面的方法

如下所示: import urllib.request import sys import http.cookiejar import urllib.parse from bs4 i...