您的位置:首页 > 编程语言 > Python开发

python学习每日一题【20200228】来一个Python经典练习题:使用Python打印菱形

2020-03-06 13:39 459 查看
题目:

【Python学习练习题】每日一练(2-28):
题目:打印出图案(菱形)

实现方法:

Python内置函数,center()可以按照当前行的最大值,居中输出

参考答案

思路

# -*- coding: utf-8 -*-
# @Time    : 2020年2月28日
# @Software: PyCharm
# Python学习交流请加个人WX: felix107ye

def printX(i, centerNum):	#逐行打印星号的函数
s = "*"
print((s * i).center(centerNum+2))

def pControl(max1):
for i in range(1 , 2*max1 , 2):
if i <= max1:
printX(i, max1)
else:
printX(2 * max1 - i, max1)

if __name__ == '__main__':
max1 = int(input("请输入:"))
if max1%2 == 1:
pControl(max1)
else:
pControl(max1+1)	#兼容输入的是偶数不输出标准菱形的问题

输出

请输入:9
*
***
*****
*******
*********
*******
*****
***
*

Process finished with exit code 0

请输入:6
*
***
*****
*******
*****
***
*

Process finished with exit code 0
其他参考答案
#来源:百雨 https://blog.csdn.net/sinat_38068807/article/details/88562501
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

输出

请输入菱形边长:
6
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * *
* * * *
* * *
* *
*

Process finished with exit code 0
  • 点赞
  • 收藏
  • 分享
  • 文章举报
晓风学Python 发布了11 篇原创文章 · 获赞 1 · 访问量 456 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: