用python打印菱形的实操方法和代码

yipeiwu_com6年前Python基础

python怎么打印菱形?下面给大家带来三种方法:

第一种

rows = int(input('请输入菱形边长:\n'))

row = 1

while row <= rows:

  col = 1   # 保证每次内循环col都从1开始,打印前面空格的个数

  while col <= (rows-row): # 这个内层while就是单纯打印空格

    print(' ', end='') # 空格的打印不换行

    col += 1

  print(row * '* ') # 每一行打印完空格后,接着在同一行打印星星,星星个数与行数相等,且打印完星星后print默认换行

  row += 1

 

bottom = rows-1

while bottom > 0:

  col = 1   # 保证每次内循环col都从1开始,打印前面空格的个数

  while bottom+col <= rows:

    print(' ', end='') # 空格的打印不换行

    col += 1

  print(bottom * '* ') # 每一行打印完空格后,接着在同一行打印星星,星星个数与行数相等,且打印完星星后print默认换行

  bottom -= 1

输出结果:

请输入菱形边长:

5

  * 

  * * 

 * * * 

 * * * * 

* * * * * 

 * * * * 

 * * * 

  * * 

  *

第二种

s = '*'

for i in range(1, 8, 2):

  print((s * i).center(7))

for i in reversed(range(1, 6, 2)):

  print((s * i).center(7))

输出结果:

  *  

 *** 

 ***** 

*******

 ***** 

 *** 

  *

第三种

def stars(n):

  RANGE1 = [2*i+1 for i in range(n)]

  RANGE2 = [2*i+1 for i in range(n)[::-1]][1:]

  RANGE = RANGE1 + RANGE2

  RANGE_1 = [i for i in range(n)[::-1]]

  RANGE_2 = [i for i in range(n)[1:]]

  RANGE_12 = RANGE_1 + RANGE_2

  for i in range(len(RANGE)):

    print (' '*RANGE_12[i] + '*'*RANGE[i])

if __name__ == "__main__":

  stars(5)

输出结果:

  *

  ***

 *****

 *******

*********

 *******

 *****

  ***

  *

以上就是关于用python来画出菱形的方法总结,感谢大家的阅读和对【听图阁-专注于Python设计】的支持。

相关文章

利用Python暴力破解zip文件口令的方法详解

利用Python暴力破解zip文件口令的方法详解

前言 通过Python内置的zipfile模块实现对zip文件的解压,加点料完成口令破解 zipfile模块用来做zip格式编码的压缩和解压缩的,zipfile里有两个非常重要的cla...

python中字典(Dictionary)用法实例详解

本文实例讲述了python中字典(Dictionary)用法。分享给大家供大家参考。具体分析如下: 字典(Dictionary)是一种映射结构的数据类型,由无序的“键-值对”组成。字典的...

Tensorflow卷积神经网络实例进阶

Tensorflow卷积神经网络实例进阶

在Tensorflow卷积神经网络实例这篇博客中,我们实现了一个简单的卷积神经网络,没有复杂的Trick。接下来,我们将使用CIFAR-10数据集进行训练。 CIFAR-10是一个经...

python命令行参数解析OptionParser类用法实例

python命令行参数解析OptionParser类用法实例

本文实例讲述了python命令行参数解析OptionParser类的用法,分享给大家供大家参考。 具体代码如下: from optparse import OptionParser...

Python标准库与第三方库详解

本文详细罗列并说明了Python的标准库与第三方库如下,供对此有需要的朋友进行参考: Tkinter———— Python默认的图形界面接口。 Tkinter是一个和Tk接口的模块,Tk...