Python中使用for循环打印菱形,三角形,空心菱形等图形

三角形

def shape1():
    for i in range(1, 5):
        str1 = "*" * (i * 2 - 1)
        print(str1.center(7))

if __name__ == "__main__":
    shape1()

实心菱形

def shape2():
    for i in range(1, 8):
        if i < 4:
            str2 = "*" * (i * 2 - 1)
        else:
            str2 = "*" * (15 - 2 * i)
        print(str2.center(7))

if __name__ == "__main__":
    shape2()

空心菱形

def shape3():
    s = "*"
    for i in range(1, 8):
        if i == 1 or i == 7:
            str1 = s.center(7)
        elif i < 5:
            str1 = s.rjust(5 - i)
            str1 += s.rjust(2 * i - 2)
        else:
            str1 = s.rjust(i - 3)
            str1 += s.rjust(14 - 2 * i)
        print(str1)

if __name__ == "__main__":
    shape3()

你可能感兴趣的:(Python中使用for循环打印菱形,三角形,空心菱形等图形)