One line if-condition-assignment

前端 未结 14 2552
挽巷
挽巷 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

    In one line:

    if someBoolValue: num1 = 20
    

    But don’t do that. This style is normally not expected. People prefer the longer form for clarity and consistency.

    if someBoolValue:
        num1 = 20
    

    (Equally, camel caps should be avoided. So rather use some_bool_value.)

    Note that an in-line expression some_value if predicate without an else part does not exist because there would not be a return value if the predicate were false. However, expressions must have a clearly defined return value in all cases. This is different from usage as in, say, Ruby or Perl.

提交回复
热议问题