Python 2.x gotchas and landmines

后端 未结 23 2374
北恋
北恋 2020-11-28 17:47

The purpose of my question is to strengthen my knowledge base with Python and get a better picture of it, which includes knowing its faults and surprises. To keep things sp

23条回答
  •  北荒
    北荒 (楼主)
    2020-11-28 18:11

    There was a lot of discussion on hidden language features a while back: hidden-features-of-python. Where some pitfalls were mentioned (and some of the good stuff too).

    Also you might want to check out Python Warts.

    But for me, integer division's a gotcha:

    >>> 5/2
    2
    

    You probably wanted:

    >>> 5*1.0/2
    2.5
    

    If you really want this (C-like) behaviour, you should write:

    >>> 5//2
    2
    

    As that will work with floats too (and it will work when you eventually go to Python 3):

    >>> 5*1.0//2
    2.0
    

    GvR explains how integer division came to work how it does on the history of Python.

提交回复
热议问题