One line if-condition-assignment

前端 未结 14 2444
挽巷
挽巷 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:23

    If you wish to invoke a method if some boolean is true, you can put else None to terminate the trinary.

    >>> a=1
    >>> print(a) if a==1 else None
    1
    >>> print(a) if a==2 else None
    >>> a=2
    >>> print(a) if a==2 else None
    2
    >>> print(a) if a==1 else None
    >>>
    
    0 讨论(0)
  • 2020-12-02 09:25

    For the future time traveler from google, here is a new way (available from python 3.8 onward):

    b = 1
    if a := b:
        # this section is only reached if b is not 0 or false.
        # Also, a is set to b
        print(a, b)
    
    0 讨论(0)
  • 2020-12-02 09:25

    You can definitely use num1 = (20 if someBoolValue else num1) if you want.

    0 讨论(0)
  • 2020-12-02 09:25

    Another way num1 = (20*boolVar)+(num1*(not boolVar))

    0 讨论(0)
  • 2020-12-02 09:26

    Use this:

    num1 = 20 if someBoolValue else num1
    
    0 讨论(0)
  • 2020-12-02 09:27
    num1 = 20 * someBoolValue or num1
    
    0 讨论(0)
提交回复
热议问题