42

I just recently joined the python3 HypeTrain. However I just wondered how you can use an if statement onto a boolean. Example:

RandomBool = True
# and now how can I check this in an if statement? Like the following:
if RandomBool == True:
    # DoYourThing

And also, can I just switch the value of a boolean like this?

RandomBool1 == True # Boolean states True
if # AnyThing:
    RandomBool1 = False # Boolean states False from now on?
9
  • Did you try and see what happened? Commented Jul 17, 2016 at 16:25
  • well sure i did states an error :( Commented Jul 17, 2016 at 16:25
  • "if Check6228 == False: UnboundLocalError: local variable 'Check6228' referenced before assignmen" Commented Jul 17, 2016 at 16:26
  • You probably did not define your boolean variable then. Commented Jul 17, 2016 at 16:27
  • 4
    Value assignment uses the = operator, == checks for equality. Commented Jul 17, 2016 at 16:27

3 Answers 3

126

You can change the value of a bool all you want. As for an if:

if randombool is True:

works, but you can also use:

if randombool:

If you want to test whether something is false you can use:

if randombool is False

but you can also use:

if not randombool:
Sign up to request clarification or add additional context in comments.

1 Comment

This answer could be completed with the response from @user15547210 I think "if randombool is True:" might be longer than "if randombool:", but it's also more intuitive than both options here. Anyway, the three form the complete set for anyone to choose from.
15

I think You could also just use

if randombool is True:

elif randombool is False:

I don't think you need to use equal signs unless it's an int or float.

Correct me if I'm wrong

1 Comment

This should be voted the right answer!
2

According to PEP 8, it looks like we should just be using

if RandomBool:

or

if not RandomBool:

I believe is compares memory addresses, and PEP 8 says we shouldn't compare bools with ==:

PEP 8 screenshot

See PEP 8 here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.