python - 如何通过嵌套循环在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.
* * * * * * * * * * * * * * * * * * * * *
解决方案
rows = 5
cols = 23
for i in range(rows):
print('*' + ('*' if i in (0,rows-1) else ' ') * (cols-2) + '*')
输出
***********************
* *
* *
* *
***********************
所有行都以星号开头和结尾,只有顶部和底部填充,中间行都使用空格代替。
推荐阅读
- python - 安装 MySQL-python==1.2.5 时出错
- php - 循环内codeigniter中未定义的偏移量
- html - 这个网站的图标来自哪里
- php - 类 App\Listeners\Request 不存在
- php - 循环通过 json-data
- java - GStreamer 分割 MP4 文件
- php - 如何拒绝执行特定 apache 目录上的任何文件?
- javascript - 如何在 React 中显示图像滑块
- regex - 正则表达式将单词大写
- actionscript - ActionScript 3.0 和 'TypeError: Error#1034: type Coercion failed'