python 我的直角图案是不完整的,为什么我缺少一些底部的行或列?

dauxcl2d  于 2023-09-29  发布在  Python
关注(0)|答案(2)|浏览(112)

我正在尝试输出一个模式,如:

  1. 🐟
  2. 🐟🐟
  3. 🐟🐟🐟
  4. 🐟🐟
  5. 🐟

我有这个代码:

  1. def get_right_arrow_pattern(max_cols)
  2. emoji = "🐟"
  3. result = ""
  4. max_rows = max_cols
  5. for row in range(1, max_rows+1):
  6. for column in range(1, max_cols+1):
  7. result = "" + result
  8. result += str(emoji)
  9. print(result)
  10. return emoji

但我得到了这样的结果:

  1. 🐟
  2. 🐟🐟
  3. 🐟🐟🐟
  4. 🐟🐟🐟🐟
  5. 🐟
  6. None

这段代码很棘手,因为我的homeowork不允许在函数或for循环中使用print(),而只能用它来显示结果。我只在这段代码中使用它,因为它是唯一有效的,并且是半成功的。

z5btuh9x

z5btuh9x1#

你可以在你的函数中构造一个列表,返回它并在主程序中打印。
举例来说:

  1. def get_right_arrow_pattern(max_cols, emoji = '🐟'):
  2. return [emoji * i for i in range(1, max_cols+1)] + [emoji * i for i in range(max_cols-1, 0, -1)]
  3. print(*get_right_arrow_pattern(3), sep='\n')

输出:

  1. 🐟
  2. 🐟🐟
  3. 🐟🐟🐟
  4. 🐟🐟
  5. 🐟
zyfwsgd6

zyfwsgd62#

您可以通过向现有代码添加一些行来获得所需的输出:

  1. def get_right_arrow_pattern(max_cols):
  2. emoji = "🐟"
  3. result = ""
  4. max_rows = max_cols
  5. for row in range(1, max_rows+1):
  6. result += str(emoji)
  7. print(result)
  8. for row in range(1, max_rows):
  9. result = result[:-1] # This will remove the last character from the string
  10. print(result)
  11. return emoji

您也可以在函数内部不使用print()语句的情况下获得相同的结果。

  1. def get_right_arrow_pattern(max_cols):
  2. emoji = "🐟"
  3. result = ""
  4. max_rows = max_cols
  5. for row in range(1, max_rows+1):
  6. result += emoji*row
  7. result += "\n"
  8. for row in reversed(range(1, max_rows)):
  9. result += emoji*row
  10. result += "\n"
  11. return result

注:

No_of_rows != No_of_columns对于此模式。
逻辑上是No_of_rows == (No_of_columns * 2) - 1
我希望这能帮上忙。

展开查看全部

相关问题