英文:
Why must my code include line = '' + '-' instead of line = '-'
问题
代码1输出:
World
-----
代码2输出:
World
-
为什么代码2没有与代码1相同的输出?
我真的不明白。
英文:
CODE 1
name = 'World'
line = ''
for char in name:
line = line + '-'
print(name)
print(line)
Versus
CODE 2
name = 'World'
line = ''
for char in name:
line = '-'
print(name)
print(line)
Why doesn't code 2 have the output
World
-----
as well? I really don't get it
答案1
得分: 3
只要考虑这实际意味着的是:
for char in name:
line = '-'
for 关键字告诉解释器遍历name
中的所有字符。对于World
中的每个字符,它将运行一次line = '-'
。
第一次执行line = '-'
时,变量line
被设置为'-'
。
但第二次和第三次也是如此。
这是两个程序之间的区别。在第一个程序中,你执行line = line + '-'
。你取当前的line
并在末尾添加一个额外的'-'
。
英文:
Just think about what this actually means:
for char in name:
line = '-'
The for keyword tells the interpreter to iterate over all characters in name
. It will run line = '-'
once for every character in World
.
The first time line = '-'
get's executed, the variable line
gets set to '-'
.
But so does it the second time. And the third time.
That's the difference between the two programs. In the first program you do line = line + '-'
. You take the current line
and add a further '-'
at the end
答案2
得分: 1
问题在于循环中的那一行没有聚合“-”字符。
要解决这个问题,你有两个选项:
- 像你在你的第一段代码中所做的那样。
for char in name:
line = line + '-'
- 也可以这样。
for char in name:
line += '-'
英文:
The problem you have is that line in loop is not aggragating the -
char.
For doing so you have two options:
- Like you did in your first code.
for char in name:
line = line + '-'
- Like this.
for char in name:
line += '-'
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论