Python 模类型错误

标签 python python-2.7

我想创建简单的代码来测试数字是奇数还是偶数。 我正在使用 Python 2.7.3 .

def oddoreven(a):
    try: int(a)
    except: return "Error"
    if a%2==0: return 1
    else: return 0

相反,代码失败并出现错误:TypeError: not all arguments converted during string formatting.错误指向以 if a%2==0... 开头的行.

在研究这个问题时,我发现一些例子表明像这样的代码应该可以工作。例如,这个问题的答案提供了与解决方案类似的代码:python - checking odd/even numbers and changing outputs on number size

那么我的代码有什么问题呢?

最佳答案

这是因为您首先测试 a 是否可以转换为 int(这没问题),但随后您忽略了此测试并继续使用 您在参数中提供的字符串

Python 是一种动态类型语言,也是一种强类型,这意味着您可以在变量声明后更改它的类型,但这种更改必须明确的(more about this here)。

在您的情况下,这意味着如果 a 是字符串,您不能执行 if a % 2 == 0

例如,您可以这样做:

def oddoreven(a):
    try:
        my_int = int(a)
    except TypeError:
        return "The argument provided could not be converted into an int"
    if my_int % 2 == 0:
        return 1
    else:
        return 0

关于Python 模类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29477664/

相关文章:

python - 如何将 ForeignKey 上的引用设置为 null - Django

python - 为什么 PyCharm 显示无效的 unicode 字符?

python - in 语句仅对 python 中的列表起作用一次

python - 无法将数组数据从 dtype ('O' ) 转换为 dtype ('float64' )

Python pyqt 多线程脉冲进度条

python - 在 Jython 中使用 .pyd 库

python - 如何让我的 python 应用程序在继续之前等待某个子进程

python - 处理 couchdb 通知的外部进程导致崩溃

python - 如何批量执行for循环?

python-2.7 - 如何使用 PyQT 提示跟随 slider 的处理程序?