为什么我的代码必须包含 line = ” + ‘-‘ 而不是 line = ‘-‘?

huangapple go评论96阅读模式
英文:

Why must my code include line = '' + '-' instead of line = '-'

问题

代码1输出:

  1. World
  2. -----

代码2输出:

  1. World
  2. -

为什么代码2没有与代码1相同的输出?
我真的不明白。

英文:

CODE 1

  1. name = 'World'
  2. line = ''
  3. for char in name:
  4. line = line + '-'
  5. print(name)
  6. print(line)

Versus

CODE 2

  1. name = 'World'
  2. line = ''
  3. for char in name:
  4. line = '-'
  5. print(name)
  6. print(line)

Why doesn't code 2 have the output

  1. World
  2. -----

as well? I really don't get it

答案1

得分: 3

只要考虑这实际意味着的是:

  1. for char in name:
  2. line = '-'

for 关键字告诉解释器遍历name中的所有字符。对于World中的每个字符,它将运行一次line = '-'

第一次执行line = '-'时,变量line被设置为'-'
但第二次和第三次也是如此。

这是两个程序之间的区别。在第一个程序中,你执行line = line + '-'。你取当前的line并在末尾添加一个额外的'-'

英文:

Just think about what this actually means:

  1. for char in name:
  2. 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

问题在于循环中的那一行没有聚合“-”字符。

要解决这个问题,你有两个选项:

  1. 像你在你的第一段代码中所做的那样。
  1. for char in name:
  2. line = line + '-'
  1. 也可以这样。
  1. for char in name:
  2. line += '-'
英文:

The problem you have is that line in loop is not aggragating the - char.

For doing so you have two options:

  1. Like you did in your first code.
  1. for char in name:
  2. line = line + '-'
  1. Like this.
  1. for char in name:
  2. line += '-'

huangapple
  • 本文由 发表于 2023年6月19日 17:30:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/76505329.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定