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

Python使用input询问年龄时拼接name变量触发TypeError如何解决

Python input()传参报错解决方案

报错原因

input() 函数最多仅支持接收1个字符串参数作为控制台提示语,你用逗号分隔传入了"Hi"、name、"how old are you?"三个独立参数,不符合函数调用规则,因此触发TypeError。

解决方法

将零散的文本和变量拼接为单个完整的字符串再传入input()即可,推荐两种最简写法:

  • f-string写法(Python3.6及以上版本支持,可读性最高)
age = int(input(f"Hi {name} how old are you?"))
  • 字符串拼接写法(兼容所有Python版本)
age = int(input("Hi " + name + " how old are you?"))

修改后完整代码

age = 0
while age < 5 or age > 98: # 符合购买电脑的预期年龄范围
    try:
        age = int(input(f"Hi {name} how old are you?"))
    except ValueError:
        print("You need to enter your age correctly, as an integer. ")
        continue

小提示:原代码中的intger为拼写错误,已修正为正确拼写integer


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 20:51:01