How to do variable assignment inside a while(expression) loop in Python?

前端 未结 6 1872
离开以前
离开以前 2020-12-08 22:30

I have the variable assignment in order to return the assigned value and compare that to an empty string, directly in the while loop.

Here is how I\'m doing it in PH

6条回答
  •  醉话见心
    2020-12-08 22:40

    No, sorry. It's a FAQ, explained well here:

    In Pydocs, and Fredrik Lundh's blog.

    The reason for not allowing assignment in Python expressions is a common, hard-to-find bug in those other languages.

    Many alternatives have been proposed. Most are hacks that save some typing but use arbitrary or cryptic syntax or keywords, and fail the simple criterion for language change proposals: it should intuitively suggest the proper meaning to a human reader who has not yet been introduced to the construct.

    An interesting phenomenon is that most experienced Python programmers recognize the while True idiom and don’t seem to be missing the assignment in expression construct much; it’s only newcomers who express a strong desire to add this to the language.

    There’s an alternative way of spelling this that seems attractive:

    line = f.readline() while line:
        ... # do something with line...
        line = f.readline()
    

提交回复
热议问题