One line if-condition-assignment

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

    Here is what i can suggest. Use another variable to derive the if clause and assign it to num1.

    Code:

    num2 =20 if someBoolValue else num1
    num1=num2
    
    0 讨论(0)
  • 2020-12-02 09:45

    You can do it this way.

    try:
        a = [i for i in [20] if False][0]
    except IndexError:
        print("Do what ever you want here")
    

    You can solve your problem this way but, using 'try/except block' is not the best practice for python.

    0 讨论(0)
提交回复
热议问题