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) 
      

运行结果:

相关文章

Pandas中Series和DataFrame的索引实现

正文 在对Series对象和DataFrame对象进行索引的时候要明确这么一个概念:是使用下标进行索引,还是使用关键字进行索引。比如list进行索引的时候使用的是下标,而dict索引的时...

Python常用模块os.path之文件及路径操作方法

以下是 os.path 模块的几种常用方法: 方法 说明 os.path.abspath(path...

基于python log取对数详解

log()方法返回x的自然对数,对于x>0。 语法 以下是log()方法的语法: import math math.log( x ) 注意:此函数是无法直接访问的,所以我...

使用python实现哈希表、字典、集合操作

使用python实现哈希表、字典、集合操作

哈希表 哈希表(Hash Table, 又称为散列表),是一种线性表的存储结构。哈希表由一个直接寻址表和一个哈希函数组成。哈希函数h(k)将元素关键字k作为自变量,返回元素的存储下标。...

对python实现二维函数高次拟合的示例详解

在参加“数据挖掘”比赛中遇到了关于函数高次拟合的问题,然后就整理了一下源码,以便后期的学习与改进。 在本次“数据挖掘”比赛中感觉收获最大的还是对于神经网络的认识,在接近一周的时间里,研究...