Boolean Values
If Statements and Boolean Values¶
One of the most important parts of programming is understanding how boolean values and if statements work. Boolean values are those that take on either the value of True or the value of False. The two ways which they are represented are either as True/False or 1/0 respectively. Below you can observe that converting values of True to integer gives back the value 1. For false it returns the value of 0.
#Create a boolean value of True
a = True
print(a)
#Convert and print that boolean value as an integer
print(int(a))
#Create a boolean value of False
a = False
print(a)
#Convert and print that boolean value as an integer
print(int(a))
The opposite conversion can be done by using bool() and passing in either 1 or 0.
#Convert 1 and 0 to be boolean values
print(bool(1))
print(bool(0))
Checking Equality¶
When you use two equal signs, ==, you check if two variables are equal to one and other. If they are then it will return the value True, otherwise it will return False
#You can create a boolean value by checking a condition
print(5 == 5)
This applies to a variable being checked against an actual value as well. The following will also return True.
#Check the variable 5 against 5
a = 5
print(a==5)
Even if one is a floating point number, if the two are equal it still comes back as True.
#Check the variable 5 against 5
a = 5.0
print(a==5)
But of course 5.1 is not equal to 5.
#Check the variable 5.1 against 5
a = 5.1
print(a==5)
Besides checking equality, there are a few other comparisons which we can make, they are:
- a == b : a is equal to b
- a != b : a is not equal to b
- a >= b : a is greater than or equal to b
- a > b : a is greater than b
- a <= b : a is less than or equal to b
- a < b : a is less than b
#Examples of comparisons
print(5 == 5)
print(6 != 5)
print(5 >= 5)
print(5 <= 4)
print(5 > 5)
print(3 < 4)