V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
davidxj
V2EX  ›  Python

请教一个 Python 变量是不是空的判断报错问题

  •  
  •   davidxj · 2019-08-22 15:10:31 +08:00 · 1873 次点击
    这是一个创建于 1681 天前的主题,其中的信息可能已经有所发展或是发生改变。

    我在写 python 脚本的时候,遇到需要判断一个变量是否为空的情况,如果为空就 break 出去,不为空就继续。其中不为空的时候运行没有问题,但是为空的时候就会报错:TypeError: object of type 'NoneType' has no len() 然后大循环就走不下去了。请问还有什么方法判断且不会报错,谢谢

    smallpython
        1
    smallpython  
       2019-08-22 15:13:45 +08:00
    这个提示就是 None 对象没有 len 方法
    你得先判断这个变量是不是 None
    如果不是 None 才可以用 len 方法
    gzlock
        2
    gzlock  
       2019-08-22 15:15:12 +08:00
    a = ''
    # a = None
    # a = {}
    if a and len(a):
    print('Yes')
    else:
    print('No')

    上面三个情况的 a 都是输出 No
    viiii
        3
    viiii  
       2019-08-22 15:18:10 +08:00
    ```python
    if a is None:
    pass
    ```
    这样写呢?
    Yourshell
        4
    Yourshell  
       2019-08-22 15:21:29 +08:00 via iPhone
    不是数组用 len 干嘛
    davidxj
        5
    davidxj  
    OP
       2019-08-22 15:22:43 +08:00
    哈哈,菜鸟,谢谢楼上各位教我,感谢感谢
    aaronhua
        6
    aaronhua  
       2019-08-22 16:11:03 +08:00
    这个变量是调用某个接口的返回值吧
    自己写
    if a:
    do_something
    就完事了
    (然后过一段时间,你就看不懂自己的代码了,手动狗头)
    davidxj
        7
    davidxj  
    OP
       2019-08-23 09:48:46 +08:00
    @aaronhua python 的 requests 返回的下一页的 url,最后一页不存在这个参数,所以为 none,已经处理完了,按照楼上的判断了是不是 none 就行了
    aaronhua
        8
    aaronhua  
       2019-08-23 10:06:16 +08:00
    @davidxj if a:这种写法不推荐的,空字符串,空列表,空字典,None 都会判定为 False,但是可读性不是很好。所以用 if a is None:更好,我只是调侃下。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2869 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 13:10 · PVG 21:10 · LAX 06:10 · JFK 09:10
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.