Python打印“菱形”星号代码方法

yipeiwu_com5年前Python基础

本人是一名python初学者,刚刚看到一道有趣的python问题,“用python如何在编译器中打印出菱形图案?”
因此决定尝试一下,代码不多,仅供参考。

代码

def printStar(intNum):
  s = "*"
  spaceLength = intNum
  blockCount = int(intNum/2+1)

  for i in range(spaceLength):
    result = s.rjust(blockCount)
    if i >= int(spaceLength/2):
      print(result)
      s = s[2:]
      blockCount -= 1
    else:
      print(result)
      s = s+(2*"*")
      blockCount += 1

def oddOReven(intNum):

  if intNum%2 == 0:
    print("please input a odd num data")
  else: 
    printStar(intNum)

if __name__ == '__main__':
  
  while True:
    try:
      intNum = eval(input("please input a odd num data\n"))
      oddOReven(intNum)
    except BaseException as e:
      print("Please input as 1/2/3... Errorcode:%s" % e) 
      

运行结果:

相关文章

Python脚本判断 Linux 是否运行在虚拟机上

在 WebHostingTalk 论坛上有些国外奸商会把虚拟机当作独立服务器卖,去年7月份的时候就有一位中国同胞上当受骗,并在 WHT 上发帖声讨,证据确凿,甚至连服务商自己也承认,回帖...

python中文件变化监控示例(watchdog)

在python中文件监控主要有两个库,一个是pyinotify ( https://github.com/seb-m/pyinotify/wiki ),一个是watchdog(http:...

Python实现对excel文件列表值进行统计的方法

本文实例讲述了Python实现对excel文件列表值进行统计的方法。分享给大家供大家参考。具体如下: #!/usr/bin/env python #coding=gbk #此PY用来...

Python OpenCV实现图片上输出中文

Python OpenCV实现图片上输出中文

OpenCV中在图片上输出中文一般需要借助FreeType库实现。FreeType库是一个完全免费(开源)的、高质量的且可移植的字体引擎,它提供统一的接口来访问多种字体格式文件。但使用F...

详解Python读取yaml文件多层菜单

需要用到的Python知识点 Python的对象属性方法; 用到字典{key:value}值的提取; 列表的增加; if循环结合break的使用; yaml文件读取...