前言:在学习开发语言循环语句的使用过程中,经常会打印各种形状来验证对循环语句的熟练掌握程度,接下来就使用python来打印多种形状练习。
如下示例中:变量i用于控制外层循环(图形行数),j用于控制空格的个数,k用于控制星号(*)的个数
1. 打印三角形
1.1 打印直角三角形
#/usr/bin/python rows = int(raw_input(‘please input a rows:‘)) i=j=k=1 if rows >= 3: for i in range(0,rows+1): for k in range(0,i): print ‘*‘, # 注意这里的",",一定不能省略,可以起到不换行的作用 k = k+1 print ‘\n‘ i = i+1 else: print (‘Please enter a number that greater than or equal to 3,thank you!‘)
1.2 打印空心等边三角形
#/usr/bin/python rows = int(raw_input(‘please input a rows:‘)) for i in range(0,rows): for j in range(0,rows-i-1): print " ", j += 1 for k in range(0,2*i+1): if k == 0 or k == 2*i: print "*", else: if i+1==rows and k%2==0: print "*", else: print " ", k += 1 print "\n" i += 1
2. 打印菱形
2.1 打印实心菱形
#/usr/bin/python rows = int(raw_input(‘please input a rows that rather than 2 :‘)) for i in range(0,rows): for j in range(0,rows-(i+1)): print " ", j += 1 for k in range(0,(rows-1)*i+1): if k>=2*i+1 : print " ", else: print "*", k += 1 print "\n" i += 1 for i in range(0,rows-1): for j in range(0,i+1): print " ", j += 1 for k in range(0,2*((rows-1)-i)-1): print "*", k += 1 print "\n" i += 1
2.2 打印空心菱形
# 打印空心菱形先打印上半部分rows行,在打印下半部分rows-1行
#/usr/bin/python rows = int(raw_input(‘please input a rows:‘)) for i in range(0,rows): for j in range(0,rows-(i+1)): print " ", j += 1 for k in range(0,(rows-1)*i+1): if k == 0 or k == 2*i: print "*", else: print " ", k += 1 print "\n" i += 1 for i in range(0,rows-1): for j in range(0,i+1): print " ", j += 1 for k in range(0,2*((rows-1)-i)-1): if k == 0 or k==2*((rows-1)-i)-2: print "*", else: print " ", k += 1 print "\n" i += 1
# 网上也有些朋友先打印上半部分rows-1行,然后打印下半部分rows行
#/usr/bin/python rows = int(raw_input(‘please input a rows:‘)) for i in range(0,rows): for j in range(0,rows-i): print " ", j += 1 for k in range(0,2*i-1): if k == 0 or k == 2*i-2: print "*", else: print " ", k += 1 print "\n" i += 1 for i in range(0,rows): for j in range(0,i): print " ", j += 1 for k in range(0,2*(rows-i)-1): if k == 0 or k == 2*(rows-i)-2: print "*", else: print " ", k += 1 print "\n" i += 1
时间: 2024-10-18 05:27:07