ใช้ nested loop และ range สร้างรูปแบบพีระมิดต่างๆ ด้วยอักขระ * หรือ @
Pattern 1: Right-angle Triangle (ซ้ายล่าง)
def pyramid1(rows):
for i in range(1, rows+1):
print("* " * i)
pyramid1(5)
* * * * * * * * * * * * * * *
Pattern 2: Right-angle Triangle (ขวาล่าง)
def pyramid2(rows):
for i in range(1, rows+1):
spaces = " " * (rows - i)
stars = "* " * i
print(spaces + stars)
pyramid2(5)
*
* *
* * *
* * * *
* * * * *
Pattern 3: Isosceles Triangle (เท่าเทียม)
def pyramid3(rows):
for i in range(1, rows+1):
spaces = " " * (rows - i)
stars = "* " * i
print(spaces + stars)
pyramid3(5)
* * * * * * * * * * * * * * *
Pattern 4: Equilateral Triangle (สมมาตร) ใช้ @
def pyramid4(rows):
for i in range(1, rows+1):
spaces = " " * (rows - i)
stars = "@ " * i
print(spaces + stars)
pyramid4(5)
@ @ @ @ @ @ @ @ @ @ @ @ @ @ @
สรุป
คีย์คือการคำนวณจำนวน space และ star ให้ถูกต้องในแต่ละแถว