Example
#coding:utf-8
rows = int(raw_input('Enter the number of columns:'))
i = j = k = 1 # Declare variables: i is used to control the outer loop (number of pattern lines), j is used to control the number of spaces, and k is used to control the number of *'s
# Isosceles right triangle 1
print "Isosceles right triangle 1"
for i in range(0, rows):
for k in range(0, rows - i):
print " * ", # Note the "," here, it must not be omitted, it can prevent line breaks
k += 1
i += 1
print "\n"
# Print a solid equilateral triangle
print "Print a hollow equilateral triangle; here, removing the if-else condition makes it solid."
for i in range(0, rows + 1):# Variable i controls the number of lines
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:# Because the first number starts from 0, if it is even, print '*'; if odd, print a space.
print "*",
else:
print " ", # Note the "," here, it must not be omitted, it can prevent line breaks
else:
print "*",
else:
print " ",
k += 1
print "\n"
i += 1
# Print a diamond
print "Print a hollow equilateral diamond; here, if you remove the if-else condition check, it will be solid."
for i in range(rows):# Variable i controls the number of lines
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 "\n"
i += 1
# The lower half of the diamond
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 "\n"
i += 1
#Solid square
print "Solid square"
for i in range(0, rows):
for k in range(0, rows):
print " * ", # Note the "," here, it must not be omitted, it can prevent line breaks
k += 1
i += 1
print "\n"
#Hollow square
print "Hollow square"
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:
# Because visually it looks more like a square, spaces are added on both sides here to increase the distance.
print " * ", # Note the "," here, it must not be omitted, it can prevent line breaks
else:
print " ", # There are three spaces here
else:
print " * ", # Here spaces are added on both sides of *
k += 1
i += 1
print "\n"
Execution output result:
输入列数: 4
等腰直角三角形1
* * * *
* * *
* *
*
打印空心等边三角形,这里去掉if-else条件判断就是实心的
*
* *
* *
* * * *
打印空心等菱形,这里去掉if-else条件判断就是实心的
*
* *
* *
* *
* *
* *
*
实心正方形
* * * *
* * * *
* * * *
* * * *
空心正方形
* * * *
* *
* *
* * * *