我想创建简单的代码来测试数字是奇数还是偶数。
我正在使用 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/