编写一个使用 While 循环和 For 循环打印方形星形图案的 Python 程序,并附带示例。
使用 For 循环打印方形星形图案的 Python 程序
此 Python 程序允许用户输入正方形的任意边长。此边长决定正方形的总行数和列数。接下来,此程序使用 For 循环打印星号,直到达到用户指定的行数和列数。
# Python Program to Print Square Star Pattern
side = int(input("Please Enter any Side of a Square : "))
print("Square Star Pattern")
for i in range(side):
for i in range(side):
print('*', end = ' ')
print()

使用 While 循环显示方形星形图案的 Python 程序
在此 Python 程序中,我们将 For 循环替换为 While 循环。
# Python Program to Print Square Star Pattern
side = int(input("Please Enter any Side of a Square : "))
i = 0
print("Square Star Pattern")
while(i < side):
j = 0
while(j < side):
j = j + 1
print('*', end = ' ')
i = i + 1
print('')
Please Enter any Side of a Square : 12
Square Star Pattern
* * * * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * * * * * *
>>>
显示方形星形图案的 Python 程序
在此 Python 程序中,我们将星号替换为 $ 符号。因此,它会打印美元符号,直到达到用户指定的行数和列数。
# Python Program to Print Square Star Pattern
side = int(input("Please Enter any Side of a Square : "))
print("Square Star Pattern")
for i in range(side):
for i in range(side):
print('$', end = ' ')
print()
Please Enter any Side of a Square : 15
Square Star Pattern
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $
>>>
评论已关闭。