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
相关产品推荐
相关产品推荐

