这个简单的for嵌套循环的逻辑是什么?

问题描述 投票:0回答:1

我正在开始我的Python之旅,我遇到了这个嵌套循环。 我无法理解这个加号的逻辑,我真的无法理解为什么我们在最后需要最后一个 print() 语句。

rows = int(input("How many rows?: "))
columns = int(input("How many columns?: "))
symbol = input("Enter a symbol to use: ")


for i in range(rows):
    for j in range(columns):
       print(symbol, end="")
    print()
python
1个回答
0
投票

嵌套循环内的

print
调用具有
end=""
。这意味着每个打印都以空字符串结尾。

使用默认设置

end='\n'
,您可以创建换行符。添加最后一个
print
(隐含的 `end=' ') 因此,每一行都在一个新行上开始:

rows = int(input("How many rows?: "))
columns = int(input("How many columns?: "))
symbol = input("Enter a symbol to use: ")

for i in range(rows):
    for j in range(columns):
       print(symbol, end="")
    print()
    
# inputting: 2, 2, AAPL

# prints:

AAPLAAPL
AAPLAAPL

# without `print()` that would be: AAPLAAPLAAPLAAPL

没有

© www.soinside.com 2019 - 2024. All rights reserved.