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

Python初学者求助:字符串与整数相乘的计算器报错问题

问题分析与代码修正

你的代码存在两个核心错误,导致运行报错:

  • 错误地尝试将字符串字面量'what'转换为整数:int('what'),这完全不符合逻辑,因为字符串"what"无法被解析为整数,必然触发报错。
  • 相乘的变量类型不匹配且变量使用错误:input()函数返回的是字符串类型,你没有将次数输入how转换为整数,同时错误地使用了无效转换后的变量去相乘。

修正后的代码如下:

what = input('What do you want me to say? ')
# 直接将次数输入转换为整数类型
how = int(input('How many times do you want me to say it? '))
# 使用字符串乘以整数实现重复输出
print(what * how)

或者分步处理的版本(更清晰):

what = input('What do you want me to say? ')
how_str = input('How many times do you want me to say it? ')
# 将字符串类型的次数转换为整数
how = int(how_str)
print(what * how)

修正后,当你输入字符串"what"和整数5时,会正确输出whatwhatwhatwhatwhat。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 20:32:31