while 循环
Write a Python program to display the following pattern using two, nested while loops:
***
* *
* *
* *
* *
* *
***
Create the variable output23 and use it inside the while loop to construct the string that you want to display at the end of the program. The pattern is 5 characters wide by 7 characters tall (not including newlines).
You might consider a solution where two nested while loops control which horizontal line you are creating with an interior, nested loop that considers which vertical column you are addressing like:
row = 0
column = 0
while row < 7:
while column < 5:
# do something to output23 for this (row, column)...
column += 1
# add a newline then...
column = 0
row += 1
求解,这个没有规律可循呀,😭 这个问题可以使用两个嵌套的while循环来解决。以下是一个Python程序,用两个嵌套的while循环显示所需模式:
output23 = ''
row = 0
while row < 7:
column = 0
while column < 5:
if row == 0 or row == 6 or column == 0 or column == 4:
output23 += '*'
else:
output23 += ' '
column += 1
output23 += '\n'
row += 1
print(output23)
这段代码会产生如下模式的输出:
*****
* *
* *
* *
* *
* *
*****
每个星号(*)代表模式的一部分,空格( )代表模式中的空白部分。
希望能帮到你!如果你还有其他问题,请随时提问。
如果问题已经解决,请设置最佳答案 这个问题可以使用两个嵌套的 while 循环来解决。外层循环控制行数,内层循环控制列数。在每个位置上,根据当前的行数和列数来确定输出的字符。
下面是解决这个问题的代码示例:
output23 = ""
row = 0
while row < 7:
column = 0
while column < 5:
if row == 0 or row == 6 or column == 0 or column == 4:
output23 += "*"
else:
output23 += " "
column += 1
output23 += "\n"
row += 1
print(output23)
在这个代码中,我们使用了一个名为output23的变量来构建最终要显示的字符串。外层循环while row < 7控制行数,内层循环while column < 5控制列数。在每个位置上,我们使用了一系列的条件判断来确定输出的字符。当行数为 0、6 或者列数为 0、4 时,输出星号* ,否则输出空格。在每一行的末尾,我们添加一个换行符\n 。
最后,我们打印输出output23 ,即可得到所需的图案。
页:
[1]