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

Python故事脚本输出异常求助:结果不符合预期

Python脚本输出异常问题排查

问题描述

编写短故事脚本时,运行Python代码得到异常输出:

  • 预期输出:Nick went to Costco to buy 12 different types of donuts.
  • 实际输出:NickCostco12donutsNick went to Costco to buy 12 different types of donuts.

原代码如下:

first_name = input ('Nick')

generic_location = input ('Costco')

whole_number = input ('12')

plural_noun = input ('donuts')

print(first_name, 'went to', generic_location, 'to buy', whole_number, 'different types of', plural_noun)

错误原因

input()函数的参数是控制台显示的提示文本,不是默认输入值。你把目标输入内容写在input的参数里,运行时这些文本会直接被打印到控制台;加上你后续又手动输入了相同的内容,就导致提示文本和输入内容重复输出,最终出现多余的NickCostco12donuts前缀。

修正方案

根据需求选择两种方式之一:

方式1:直接固定值(无需用户输入)

如果不需要动态输入内容,直接给变量赋值即可:

first_name = 'Nick'
generic_location = 'Costco'
whole_number = '12'
plural_noun = 'donuts'

print(first_name, 'went to', generic_location, 'to buy', whole_number, 'different types of', plural_noun)

方式2:带提示语的输入(支持默认值)

如果需要用户输入,同时提供默认值(用户直接回车则使用默认值),可使用以下写法:

first_name = input("请输入名字(默认Nick):") or "Nick"
generic_location = input("请输入地点(默认Costco):") or "Costco"
whole_number = input("请输入数字(默认12):") or "12"
plural_noun = input("请输入复数名词(默认donuts):") or "donuts"

print(first_name, 'went to', generic_location, 'to buy', whole_number, 'different types of', plural_noun)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 22:25:28