首页 > 解决方案 > Python中的星星组成的正方形

问题描述

你们中有人知道像 JetBrains Academy 这样的东西吗?你能帮我完成这个任务吗?我当然知道这很简单,但我真的做不到。我已经尝试了很多次。

https://hyperskill.org/learn/step/6715

标签: pythondesign-patternssquare

解决方案


正方形中唯一变化的是内部,所以只需检查您是在第一行还是最后一行。

不是最有效的,但 python 让它变得简单。

size = 4
for i in range(size):  # each loop prints a row
   print(*
      ['*'] +  # first star in the row
      ['*' if i in [0, size-1] else ' '] * (size-2) +  # inside stars of the row
      ['*']  # last star in the row
   )

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

推荐阅读