Logo

Developer learning path

Python

Boolean Types in Python

Boolean Types

26

#description

Boolean types in Python are used to represent the truth values of True or False. These are essential elements in programming as they enable us to make decisions in our code based on whether a statement is true or false.

To create a boolean value, we can use the keywords 'True' or 'False' or we can use comparison operators like '==', '!=', '<', '<=', '>', or '>=' which evaluate to either True or False.

For example:

                    
x = 10
y = 5

# Equals
print(x == y)       # False

# Not equals
print(x != y)       # True

# Less than
print(x < y)        # False

# Greater than
print(x > y)        # True
                  

Boolean types can also be combined using logical operators such as 'and', 'or' and 'not' to create more complex conditions.

For example:

                    
x = 10
y = 5
z = 2

print(x > y and x > z)      # True
print(y > x or z > y)       # True
print(not x == y)           # True
                  

These boolean expressions can be used in conditional statements like 'if', 'elif', and 'else' which allows us to control the flow of our program.

Here is an example:

                    
x = 5
y = 10

if x < y:
    print("x is less than y")
elif x > y:
    print("x is greater than y")
else:
    print("x is equal to y")
                  

This will output: "x is less than y"

March 25, 2023

If you don't quite understand a paragraph in the lecture, just click on it and you can ask questions about it.

If you don't understand the whole question, click on the buttons below to get a new version of the explanation, practical examples, or to critique the question itself.