为什么每一行都执行打印语句,当目标只是在列表底部打印一次?

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

Curious why print statement is executed with every line, when the goal is only to have it print once, at the bottom of the list

问题

requested_trades = ['仅做多', '仅做空', '中性仓位']
for requested_trade in requested_trades:
  print(f"我的交易清单: {requested_trade}。")

print("只在底部出现“执行良好”。")
英文:

Code below:

requested_trades = ['long only', 'short only', 'neutral position']
for requested_trade in requested_trades:
  print(f"My Trade List: {requested_trade}.")

  print("\nExecute them well")

The output:

> lang-none
> My Trade List: long only.
>
> Execute them well
> My Trade List: short only.
>
> Execute them well
> My Trade List: neutral position.
>
> Execute them well
>

I was under the belief "Execute them well" should only appear at the bottom line.

答案1

得分: 1

Python不使用花括号或关键词如do/end来定义块。它使用空白缩进。在相同级别缩进的任何内容都属于该块,即使你插入一个空白行也一样。

以下内容将实现你的期望:

requested_trades = ['long only', 'short only', 'neutral position']
for requested_trade in requested_trades:
  print(f"My Trade List: {requested_trade}.")

print("执行它们很好")
英文:

Python doesn't use curly braces or keywords such as do/end to define blocks. It uses white-space indentation. Anything indented at the same level is part of that block, even if you put in a blank newline.

The following will do what you expect:

requested_trades = ['long only', 'short only', 'neutral position']
for requested_trade in requested_trades:
  print(f"My Trade List: {requested_trade}.")

print("\nExecute them well")

huangapple
  • 本文由 发表于 2023年3月7日 04:45:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/75655672.html
匿名

发表评论

匿名网友

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

确定