如何在一个if子句中使用多个语句?

时间:2013-03-12 00:53:16

标签: python if-statement

我想在python中执行此操作:

if year and year.isdigit() and year > 0:

但它不起作用。陈述数量是否有限?

有什么想法吗?

1 个答案:

答案 0 :(得分:3)

声明数量不限。如果没有看到“无法正常工作”的确切含义,很难说清楚,但是你可能遇到的是这样的:

>>> year = "2013"
>>> year and year.isdigit() and year > 0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unorderable types: str() > int()

这是因为 - 就像错误所说的那样 - Python不知道如何将字符串与数字进行比较。它只是因为year > 0检查而发生,并且如果你将其限制为,则会得到相同的错误(或者,在Python 2中,它将始终为True - 即使对于像"-20"这样的字符串也是如此) 。如果你明确地将它转换为一个数字来进行检查,这就消失了:

>>> int(year) > 0
True