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

前端 未结 6 1848
离开以前
离开以前 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:50

    PEP 572 proposes Assignment Expressions and has already been accepted. Starting with Python 3.8, you will be able to write:

    while name := input("Name: "):
        names.append(name)
    

    Quoting the Syntax and semantics part of the PEP for some more examples:

    # Handle a matched regex
    if (match := pattern.search(data)) is not None:
        # Do something with match
    
    # A loop that can't be trivially rewritten using 2-arg iter()
    while chunk := file.read(8192):
       process(chunk)
    
    # Reuse a value that's expensive to compute
    [y := f(x), y**2, y**3]
    
    # Share a subexpression between a comprehension filter clause and its output
    filtered_data = [y for x in data if (y := f(x)) is not None]
    

提交回复
热议问题