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

Python中使用模运算符(%)触发TypeError,请求问题排查解决

问题排查与解决

嘿,这个坑我之前也踩过,一眼就看出问题啦!

错误根源

你这里的核心问题是输入类型不匹配:input()函数获取用户输入后,返回的是字符串(str)类型,而Python里的%运算符对字符串来说是格式化操作(比如"I'm %s years old" % 25这种占位符替换),不是数学意义上的取模运算。所以当你写number % 2时,Python会误以为你要做字符串格式化,但又找不到对应的占位符,直接抛出了类型错误。

快速解决办法

只需要把用户输入的字符串转换成整数类型,用int()函数包裹input()的结果就行:

number = int(input("Enter a number: "))
check = number % 2
if check == 0:
    print("your number is even.")
else:
    print("your number is odd.")

额外优化(可选)

如果担心用户输入非数字内容导致程序崩溃,可以加个异常处理,让程序更健壮:

try:
    number = int(input("Enter a number: "))
    check = number % 2
    if check == 0:
        print("your number is even.")
    else:
        print("your number is odd.")
except ValueError:
    print("请输入有效的整数哦!")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:19:44