三角形
等腰直角三角形1 2.7
#coding:utf-8
rows = int(raw_input("输入列数: "))
i = j = k = 1 #声明变量,i用于控制外层循环(图形行数),j用于控制空格的个数,k用于控制*的个数
#等腰直角三角形1
print "等腰直角三角形1"
for i in range(0, rows):
for k in range(0, rows - i):
print " * ", #注意这里的",",一定不能省略,可以起到不换行的作用
k += 1
i += 1
print " "
python:打印直角三角形
coding=utf-8
方式一
i = 1
while i <= 5:
j = 1
while j <=i:
print "*",
j+=1
print " "
i+=1
方式二
for i in range(1, 6):
for j in range(1, i+1):
print "*",
print " "
#打印实心等边三角形
print "打印空心等边三角形,这里去掉if-else条件判断就是实心的"
for i in range(0, rows + 1):#变量i控制行数
for j in range(0, rows - i):#(1,rows-i)
print " ",
j += 1
for k in range(0, 2 * i - 1):#(1,2*i)
if k == 0 or k == 2 * i - 2 or i == rows:
if i == rows:
if k % 2 == 0:#因为第一个数是从0开始的,所以要是偶数打印*,奇数打印空格
print "*",
else:
print " ", #注意这里的",",一定不能省略,可以起到不换行的作用
else:
print "*",
else:
print " ",
k += 1
print " "
i += 1
#打印菱形
print "打印空心等菱形,这里去掉if-else条件判断就是实心的"
for i in range(rows):#变量i控制行数
for j in range(rows - i):#(1,rows-i)
print " ",
j += 1
for k in range(2 * i - 1):#(1,2*i)
if k == 0 or k == 2 * i - 2:
print "*",
else:
print " ",
k += 1
print " "
i += 1
#菱形的下半部分
for i in range(rows):
for j in range(i):#(1,rows-i)
print " ",
j += 1
for k in range(2 * (rows - i) - 1):#(1,2*i)
if k == 0 or k == 2 * (rows - i) - 2:
print "*",
else:
print " ",
k += 1
print " "
i += 1
#实心正方形
print "实心正方形"
for i in range(0, rows):
for k in range(0, rows):
print " * ", #注意这里的",",一定不能省略,可以起到不换行的作用
k += 1
i += 1
print " "
#空心正方形
print "空心正方形"
for i in range(0, rows):
for k in range(0, rows):
if i != 0 and i != rows - 1:
if k == 0 or k == rows - 1:
#由于视觉效果看起来更像正方形,所以这里*两侧加了空格,增大距离
print " * ", #注意这里的",",一定不能省略,可以起到不换行的作用
else:
print " ", #该处有三个空格
else:
print " * ", #这里*两侧加了空格
k += 1
i += 1
print " "
知识点说明:
python ,end=""备注
就是打印之后不换行。在Python2.7中使用“,”
下面是2.7的例子:
def test():
print "hello",
print "world"
在python3中"end="意思是不换行
python打印翻转三角形
一.编写函数如上模式。
提示用户输入一个数n,然后调用displayPattern(n)来显示这种模式。
def displayPattern(n):
dict = {}
for i in range(0, int(n)):
"""
int(i)+ 2:左闭右开
eg: n = 3,
i = 0,打印[1] i = 1,打印[1,2]...
str(j)[::-1] : 单个字符串反转 eg:12 ===>21
键值对形式,添加到字典里面
"""
dict[i] = [str(j)[::-1] for j in range(1,int(i)+ 2)]
listNum = []
# print(dict)
for key,value in dict.items():
"""
{0: ["1"], 1: ["1", "2"], 2: ["1", "2", "3"],3: ["1", "2", "3", "4"],
循环取出字典中的value(对应的列表)
去除[],(将逗号,替换成空格, 将单引号"替换成空)===>添加到list列表
"""
value = str(value).strip("[]").replace(","," ").replace(""","")
listNum.append(value)
# print(value)
for k in range(0,int(n)):
"""
" " * %s : 空格*字符串的形式
% (int(n) - int(k) - 1))))[::-1] : %:格式化标志 int(n) - int(k) - 1:求有多少空格
"""
listNum[k] = (listNum[k] + (eval("" " * %s" % (int(n) - int(k) - 1))))[::-1]
print(listNum[k])
# print(dict)
# print(listNum)
num = int(input("请输入一个数:"))
# 调用函数
displayPattern(num)