بخشی از مجموعه

Several example codes

~2 دقیقه مطالعه • بروزرسانی ۱۹ مهر ۱۴۰۴

Program Overview

This Python program reads an integer n from the user and prints a triangle with n rows.
In this triangle:
- Only the left and right edges are drawn using asterisks (*) - All inner positions are filled with zeros (0) - Leading spaces are used to keep the triangle symmetric


Python Code:


n = int(input("Enter number of rows: "))

for i in range(n):
    line = ""
    for j in range(n - i - 1):
        line += " "
    for j in range(i + 1):
        if j == 0 or j == i:
            line += "* "
        else:
            line += "0 "
    print(line.rstrip())

Sample Output for n = 5:


    *
   * *
  * 0 *
 * 0 0 *
* 0 0 0 *

Step-by-Step Explanation:

- The outer loop runs n times to print each row
- Leading spaces are printed to align the triangle
- In each row, the first and last positions are filled with *
- All middle positions are filled with 0
- The result is a symmetric triangle with star borders and zero-filled interior





نوشته و پژوهش شده توسط دکتر شاهین صیامی