Python中使用循环语句打印三角形菱形

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python中使用循环语句打印三角形菱形相关的知识,希望对你有一定的参考价值。

前言:在学习开发语言循环语句的使用过程中,经常会打印各种形状来验证对循环语句的熟练掌握程度,接下来就使用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

以上是关于Python中使用循环语句打印三角形菱形的主要内容,如果未能解决你的问题,请参考以下文章

Java 写三角形 空心三角形 菱形 空心菱形

请问c++如何用循环语句打印下面的图形?

用java打印菱形。

python中IF及循环习题

8.Python基础语法续光说不练假把式,上题

8.Python基础语法续光说不练假把式,上题