def valid_month(month):
if month:
cap_month = month.capitalize()
if cap_month in months:
return cap_month
第二行那个if的作用是什么?它会检查是否存在参数吗?
请您参考如下方法:
在python中,一个空字符串,或者一个空列表或集合等在 bool 上下文中都是False,同样None也是False在 bool 上下文中(数字 0 也为 False)(即在 if 语句中使用时),检查 if month: ,检查月份是否不是 None 或 month 不是空字符串(我猜 month 是字符串,因为你在上面调用了 capitalize())。
只有当月份不为空且月份不为None时,才会执行if中的语句。
显示此行为的示例 -
>>> s = ''
>>> if not s:
... print("Blah")
...
Blah
>>> s = 'abcd'
>>> if s:
... print("Blah1")
...
Blah1
>>> s = ''
>>> if s:
... print("Will not print")
...
>>> s = None
>>> if s:
... print("Will not print")
Python 引用 Truth value testing .
