英文:
Why does my string output have a missing letter?
问题
我不理解输出
输入
name = 'World'
line = '-'
for char in name:
print(line)
line = line + char
输出
-
-W
-Wo
-Wor
-Worl
为什么没有 -World
非常困惑。第一天学习Python。没有任何其他编程语言的先前知识。
英文:
I don't understand the output
INPUT
name = 'World'
line = '-'
for char in name:
print(line)
line = line + char
OUTPUT
-
-W
-Wo
-Wor
-Worl
why is there no -World
very confused. first day learning python. no prior knowledge of any language
答案1
得分: 0
这是因为在添加字符之前你先打印了这行。
如果你想要打印整个单词,你需要在打印之前设置好 line 变量。
name = 'World'
line = '-'
for char in name:
line = line + char
print(line)
我假设这是为了练习,但如果你只想在单词前面打印连字符,你不需要循环,可以直接写成 print(line + name)
。
英文:
It happens because you are printing the line before adding the character.
If you want to print the whole word you need to set the line variable before printing it.
name = 'World'
line = '-'
for char in name:
line = line + char
print(line)
I assume this is for an exercise, but if you just want to print the word with the dash in front of it, you don't need the loop, and can instead write print(line + name)
.
答案2
得分: 0
问题在于在打印line
之后,您只是将line
和name
连接起来。因此,在循环的最后一次迭代中,它会打印“-Worl”,然后才将“d”添加到line
。如果在循环外再次打印line
,输出将是“-World”。
您可以通过更改循环内部的行顺序来解决此问题:
for char in name:
line = line + char
print(line)
英文:
The problem is that you're only concatenating line
and name
after printing line
. So, on the last iteration of the loop, it prints "-Worl" and then adds the 'd' to line
. If you print line
again outside the loop, the output will be "-World".
You can fix this by changing the order of the lines inside the loop to:
for char in name:
line = line + char
print(line)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论