在Python中编写嵌套循环

0 投票
1 回答
40 浏览
提问于 2025-04-13 21:17

我是一名Python初学者,正在尝试写一个嵌套循环,但输出的结果没有按照行和列排列符号,而是呈现为一列直竖的样子……这是我的代码……请帮我修正一下

rows = int(input("Enter the number of rows: "))
columns = int(input("Enter the number of columns: "))
symbol = input("Enter the symbol to use: ")

for i in range(rows):
   for j in range(columns):
      print(symbol)
   print()

我问过我的同学,但没有人知道问题出在哪里

1 个回答

0

你可以调用 print() 几次(行数 * 列数),或者在每一轮外层循环(行)中只调用一次,通过构建一个合适长度的字符串来实现,方法如下:

rows = 10
columns = 15
symbol = "*"

for _ in range(rows):
    row = ""
    for _ in range(columns):
        row += symbol
    print(row)

当然,你其实不需要使用嵌套循环就能达到你想要的输出效果。你可以直接这样做:

print(*[symbol * columns for _ in range(rows)], sep="\n")

撰写回答