Python循环中print重复执行问题:如何让指定内容仅打印一次?
解决方法
你的问题核心是缩进错误,导致目标语句被包含在循环体内重复执行。
先看你的原代码:
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")
print("\nExecute them well")和循环内的打印语句缩进相同,意味着它是循环的一部分,每遍历一个列表元素就会执行一次。
修改方式很简单,把这句代码的缩进移除,放到for循环的外面:
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")
调整后,循环会先完整输出所有交易条目,之后才执行一次print("\nExecute them well"),完全符合你的需求。
内容的提问来源于stack exchange,提问作者josh powell
相关产品推荐
相关产品推荐

