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

Python入门问题:如何实现年龄与名字长度的数值求和?

问题分析

你遇到的问题根源是input()函数返回的内容是字符串类型,所以myAge本质是字符串,和str(len(myName))相加时,Python执行的是字符串拼接操作,而非数值加法,因此会得到214这类拼接结果。

修正后的代码
print('What is your name?')    
myName = input()

print('What is your age?')  
# 将输入的年龄字符串转换为整数类型
myAge = int(input())

# 直接计算数值和(len(myName)返回整数,无需转字符串)
age_sum = myAge + len(myName)

# 用f-string简化输出格式,避免频繁类型转换和拼接
print(f"{myName}, if we add the number of letters in your name to your age then you will be {age_sum} in {len(myName)} years.")
关键修改说明
  • 类型转换:用int(input())把输入的年龄转为整数,确保后续能进行数值运算。
  • 数值求和:直接用整数相加myAge + len(myName),这里len(myName)本身就是整数,不需要额外转字符串。
  • 输出优化:使用f-string(Python 3.6及以上支持)可以直接在字符串中嵌入变量,比多次字符串拼接更简洁易读。

如果你的Python版本低于3.6,也可以用格式化字符串的兼容写法:

print("%s, if we add the number of letters in your name to your age then you will be %d in %d years." % (myName, age_sum, len(myName)))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 07:39:23