Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Syntax for an If statement using a boolean

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?
like image 342
Lucidity Avatar asked Jul 17 '16 16:07

Lucidity


People also ask

What is the syntax of boolean?

Syntax to Declare Boolean Data Types in C: To declare a boolean data type in C we have to use a keyword named bool followed by a variable name. bool var_name; Here, bool is the keyword denoting the data-type and var_name is the variable name. A bool takes in real 1 bit, as we need only 2 different values(0 or 1).

How do you compare a boolean in if condition?

The if statement will evaluate whatever code you put in it that returns a boolean value, and if the evaluation returns true, you enter the first block. Else (if the value is not true, it will be false, because a boolean can either be true or false) it will enter the - yep, you guessed it - the else {} block.

Can you use == with Booleans?

Boolean values are values that evaluate to either true or false , and are represented by the boolean data type. Boolean expressions are very similar to mathematical expressions, but instead of using mathematical operators such as "+" or "-", you use comparative or boolean operators such as "==" or "!".

Can we use boolean object in if?

Yes you can use Boolean / boolean instead. First one is Object and second one is primitive type. On first one, you will get more methods which will be useful.


2 Answers

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

if randombool == True: 

works, but you can also use:

if randombool: 

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

if randombool == False 

but you can also use:

if not randombool: 
like image 179
Mathime Avatar answered Oct 05 '22 10:10

Mathime


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

like image 22
user15547210 Avatar answered Oct 05 '22 12:10

user15547210