2
def setBoolean(status):
    if status:
        status = False
    else:
        status = True

status = True
setBoolean(status)

I want a button click to set a variable to False if True, and True if False, i.e. the opposite of what it is. How do I do this with the shortest length of code?

Hari5000
  • 371
  • 2
  • 10

4 Answers4

6

You can use not as

def setBoolean(status):
    status = not status
Pavneet_Singh
  • 36,884
  • 5
  • 53
  • 68
2
def setBoolean(status):
    return not status
sushanth
  • 8,275
  • 3
  • 17
  • 28
Fredrik
  • 484
  • 4
  • 13
  • In the code I'm working on, the variable needing to be changed is actually a global which will need to be constantly changed at the click of a button. I simplified things for the sake of finding out how to reverse the boolean itself. – Hari5000 Jun 17 '20 at 13:32
0

Try

status = True
status = not status
giando.c
  • 56
  • 1
  • 6
  • 1
    While this code may resolve the OP's issue, it is best to include an explanation as to how your code addresses the OP's issue. In this way, future visitors can learn from your post, and apply it to their own code. SO is not a coding service, but a resource for knowledge. Also, high quality, complete answers are more likely to be upvoted. These features, along with the requirement that all posts are self-contained, are some of the strengths of SO as a platform, that differentiates it from forums. You can edit to add additional info &/or to supplement your explanations with source documentation. – ysf Jun 17 '20 at 18:50
0

The shortest way is

status ^= True
Pyprohly
  • 1,128
  • 1
  • 11
  • 10