首页 > 解决方案 > 如何通过嵌套循环在python中创建一个*框?

问题描述

我正在尝试通过嵌套循环创建一个 *box。那么我如何创建盒子?

我试图通过一些除法、乘法、减法、模块来创建逻辑。我不知道有什么问题?

for colm in range(1,5):
    print('* ',end='')
    for row in range(1,21):
        if (colm==1) or (colm==4) or (row==20  and colm==2) or (row==20 and colm==3) :
            print('*',end=' ')
    print('')

输出:

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

我期望:

* * * * * * * * * * * * * * * * * * * * * 
*                                       *  <---- I want * here.
*                                       *  <---- I want * here.
* * * * * * * * * * * * * * * * * * * * *

标签: pythonpython-3.x

解决方案


rows = 5
cols = 23
for i in range(rows):
    print('*' + ('*' if i in (0,rows-1) else ' ') * (cols-2) + '*')

输出

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

所有行都以星号开头和结尾,只有顶部和底部填充,中间行都使用空格代替。


推荐阅读