[英]Python: I'm confused with spaces in between characters
所以我正在輸出一個由用戶輸入的字符組成的三角形,用戶還輸入三角形的高度(高度也等於底邊)。
該程序還希望我在打印的每個字符之間有空格。 我有兩種方法可以正確地 output 我想要什么。 我只想了解 space = space + value... 行的作用。
我只是想出了如何去做,因為我知道我必須使用“for”循環並且幾乎只是弄亂了我在循環中放置的變量。
抱歉,問題太多了,循環讓我很困惑
triangle_char = input('Enter a character:\n')
triangle_height = int(input('Enter triangle height:\n'))
space = ''
for i in range(0, triangle_height, 1):
for value in triangle_char: #if this loop is not here, and I do print(i * triangle_char), it will only output a triangle with height of 2. why?
space = space + value + ' ' #what does this do?
print(space)
#beneath is the 2nd version of the code
counter = 1
space = ''
for value in range(triangle_height):
while counter <= triangle_height:
for value in triangle_char: #how can there be a value in just a character?
space = space + value + ' '
print(space)
TLDR:讀這個
range(a, b)
返回 [a, b) 范圍內的整數。 因此,在第 4 行中,您的代碼將從0
開始循環i
直到triangle_height-1
。 因此,在您打印0 * triangle_char
時的第一次迭代中,它會打印一個空字符串(無)。
另請注意,此行中的 for 循環是多余的。 當遍歷預期長度為 1 的字符串時,它只會將value
賦給triangle_char
。
space = space + value + ' '
將value + ' '
的值連接到 space。 這有效地將值triangle_char
和一個空格添加到space
的末尾。
與許多低級語言不同,python 中沒有字符。相反,python 將所有字符都視為字符串。 因此,這一行將循環遍歷長度為 1 的字符串的字符。
space = space + value + ' '
是做什么的? space = space + value + ' '
將添加value
和一個空格 (
) 到變量space
的值,然后用這個新值覆蓋space
的舊值。
也許以不同的方式命名變量會有所幫助,例如
# create a blank message to start off with
message = ""
# add the user-entered value and a space to the message
message = message + value + ' '
# print out the message
print(message)
print(i * triangle_char)
只有 output 是一個高度為 2 的三角形? 我懷疑您看到這個時輸入的三角形高度值是 3。 如果您輸入的高度為 5,您將看到 5 行,但第一行將為空白,因為在循環的第一次迭代中i
為 0 並且0 * triangle_char
將為空白字符串。 所以三角形的表觀高度總是比triangle_height
小 1。 這是一個高度為 5 的示例。
>>> triangle_char = "+"
>>> triangle_height = 5
>>> for i in range(0, triangle_height, 1):
... print(i * triangle_char)
<=== this is the first blank line
+
++
+++
++++
Python 中的一個字符實際上是一個長度為 1 的字符串。 Python 允許您迭代/循環遍歷字符串,當您這樣做時 go 一次遍歷字符串中的所有字符。 因此,當您遍歷“字符”時,它只有一個值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.