Python 打印字母 I 星型图案的程序

本文展示了如何使用 for 循环、while 循环和函数(带有示例)编写 Python 程序来打印字母 I 星型图案。

下面的字母 I 星型图案示例接受用户输入的行数,嵌套的 for 循环迭代这些行。 If else 条件用于在第一行和最后一行以及中间列打印星号,以获得字母 I 的星型图案并跳过其他行。

rows = int(input("Enter Alphabet I of Stars Rows = "))
print("====The Alphabet I Star Pattern====")

for i in range(rows):
    for j in range(rows):
        if i == 0 or i == rows - 1 or j == rows // 2:
            print("*", end="")
        else:
            print(end=" ")
    print()
Enter Alphabet I of Stars Rows = 9
====The Alphabet I Star Pattern====
*********
    *    
    *    
    *    
    *    
    *    
    *    
    *    
*********

上面的代码打印了字母 I 的星型图案;下面的代码检查偶数并添加一个额外的数字,以使垂直线保持在中间。

rows = int(input("Enter Alphabet I of Stars Rows = "))
print("====The Alphabet I Star Pattern====")

if rows % 2 == 0:
    rows += 1
for i in range(rows):
    for j in range(rows):
        if i == 0 or i == rows - 1 or j == rows // 2:
            print("*", end="")
        else:
            print(end=" ")
    print()
Python Program to Print Alphabetical I Star Pattern

使用 while 循环打印字母 I 星型图案的 Python 程序

这个程序使用 while 循环而不是 for 循环来迭代字母 I 图案的行,并在每个位置打印星号。有关更多星型图案程序 >> 点击此处

rows = int(input("Enter Alphabet I of Stars Rows = "))

if rows % 2 == 0:
    rows += 1

i = 0
while i < rows:
    j = 0
    while j < rows:
        if i == 0 or i == rows - 1 or j == rows // 2:
            print("*", end="")
        else:
            print(end=" ")
        j = j + 1
    print()
    i += 1
Enter Alphabet I of Stars Rows = 13

*************
      *      
      *      
      *      
      *      
      *      
      *      
      *      
      *      
      *      
      *      
      *      
*************

在此程序示例中,我们创建了一个 IPattern 函数,该函数接受行数和用于打印给定符号的字母 I 图案的符号或字符。

def IPattern(rows, ch):
    if rows % 2 == 0:
        rows += 1
    for i in range(rows):
        for j in range(rows):
            if i == 0 or i == rows - 1 or j == rows // 2:
                print('%c' %ch, end='')
            else:
                print(end=" ")
        print()


row = int(input("Enter Alphabet I of Stars Rows = "))
sy = input("Symbol for I Star Pattern = ")
IPattern(row, sy)
Enter Alphabet I of Stars Rows = 10
Symbol for I Star Pattern = ^
^^^^^^^^^^^
     ^     
     ^     
     ^     
     ^     
     ^     
     ^     
     ^     
     ^     
     ^     
^^^^^^^^^^^