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
wuwukai007
V2EX  ›  Python

python2.7 None < 5 return True, python3 就直接报错了

  •  
  •   wuwukai007 · 2021-06-17 22:46:12 +08:00 · 1415 次点击
    这是一个创建于 1036 天前的主题,其中的信息可能已经有所发展或是发生改变。
    x = {'q2':2}
    if x.get('q1',None) < 5:
      # todo
    

    字典取值 默认值 None,代码竟然没报错,还到 todo 里面执行了!

    3 条回复    2021-06-17 23:26:56 +08:00
    dreampuf
        1
    dreampuf  
       2021-06-17 23:20:31 +08:00
    先用 `variable is None` 判断。`dict.get` default 填 None 是坑。Python2 不同类型比较按照类型名称字符大小比较,'i'nt 总是小于 'S'tr 。其中 `None` 是最小的类型,比任何类型都小。

    https://stackoverflow.com/questions/8961005/comparing-none-with-built-in-types-using-arithmetic-operators
    LeeReamond
        2
    LeeReamond  
       2021-06-17 23:23:19 +08:00
    @dreampuf 感觉不是一个良好的设计,说不出什么逻辑联系,只能当做特例来记,也不起到多少方便的作用
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5246 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 08:42 · PVG 16:42 · LAX 01:42 · JFK 04:42
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.