You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python程序输出不符合预期,需调整打印逻辑得到目标结果

问题解决:让Python程序仅输出最终拼接结果

原代码在循环内部每次拼接后就执行print(output),导致输入1345时会逐行输出中间过程。要实现只输出最终结果,只需调整print语句的位置:

修改后的代码

phone = input("Phone: ")
digits_mapping = {
    "1": "One",
    "2": "Two",
    "3": "Three",
    "4": "Four"
}
output = ""
for ch in phone:
    output += digits_mapping.get(ch, "!") + " "
print(output)  # 将print移到循环外部,仅输出最终结果

说明

原代码中print(output)位于for循环内部,每循环一次就会输出当前拼接的output内容。把它移到循环结束后,就能确保只输出完整拼接后的最终字符串,输入1345时会得到预期结果:One Three Four !

内容的提问来源于stack exchange,提问作者Mirco Susan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 11:20:30