One line if-condition-assignment

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

    num1 = 10 + 10*(someBoolValue is True)
    

    That's my new final answer. Prior answer was as follows and was overkill for the stated problem. Getting_too_clever == not Good. Here's the prior answer... still good if you want add one thing for True cond and another for False:

    num1 = 10 + (0,10)[someBoolValue is True]
    

    You mentioned num1 would already have a value that should be left alone. I assumed num1 = 10 since that's the first statement of the post, so the operation to get to 20 is to add 10.

    num1 = 10
    someBoolValue = True
    
    num1 = 10 + (0,10)[someBoolValue is True]
    
    print(f'num1 = {num1}\nsomeBoolValue = {someBoolValue}')
    

    produced this output

    num1 = 20
    someBoolValue = True
    

提交回复
热议问题