One line if-condition-assignment

前端 未结 14 2640
挽巷
挽巷 2020-12-02 08:46

I have the following code

num1 = 10
someBoolValue = True

I need to set the value of num1 to 20 if someBoolV

14条回答
  •  余生分开走
    2020-12-02 09:36

    If one line code is definitely going to happen for you, Python 3.8 introduces assignment expressions affectionately known as “the walrus operator”.

    :=

    someBoolValue and (num := 20)
    

    The 20 will be assigned to num if the first boolean expression is True. The assignment must be inside parentheses here otherwise you will get a syntax error.

    num = 10
    someBoolValue = True
    
    someBoolValue and (num := 20)
    print(num) # 20
    
    num = 10
    someBoolValue = False
    
    someBoolValue and (num := 20)
    print(num) # 10
    

提交回复
热议问题