โค้ดภาษา Python แสดงตัวเลข 1-9 เป็นรูปหลังคา หลักการทำงานจะเป็นลูปเพื่อแสดงรายการแต่ละบรรทัด และจะมีลูปย่อย 1 แสดงพื้นที่ว่าง (ซ้าย) จากนั้นก็จะแสดงตัวเลขแบบไม่ขึ้นไม่บรรทัดใหม่ และลูปย่อย 2 แสดงพื้นที่ว่าง (ขวา) จากนั้นก็จะแสดงตัวเลขพร้อมทั้งขึ้นบรรทัดใหม่
ตัวอย่างโค้ด Python
# -------------------------------------------------------#
# Author : Computer for Education #
# Author URI: https://www.computerforedu.com #
# Facebook : https://www.facebook.com/computerforedu #
# -------------------------------------------------------#
max_num = 9
n = 0
while n < max_num:
n += 1
space = max_num - n
for s in range(space):
print(" ", end=' ')
print(n, end=' ')
if n == 1:
print("")
continue
space = (n * 2) - 1
for s in range(2, space):
print(" ", end=' ')
print(n)
แสดงผล

