Swapping 1 with 0 and 0 with 1 in a Pythonic way

前端 未结 16 2059
夕颜
夕颜 2020-12-23 13:50

In some part of my Python program I have a val variable that can be 1 or 0. If it\'s 1 I must change to 0, if it\'s 0 I must change to 1.

How do you do it in a Pytho

16条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-23 14:19

    Here's a simple way:

    val = val + 1 - val * 2
    

    For Example:

    If val is 0

    0+1-0*2=1
    

    If val is 1

    1+1-1*2=0
    

提交回复
热议问题