Back to Course

Introduction to Python

0% Complete
0/0 Steps
  1. Python: Basics
    14Topics
    |
    15 Quizzes
  2. Python: Control Flow
    12Topics
    |
    12 Quizzes
  3. Python: Errors
    5Topics
    |
    5 Quizzes
Lesson 2, Topic 3
In Progress

Python: True and False

Yasin Cakal 11 Oct 2021
Lesson Progress
0% Complete

Before we continue, let’s discuss True and False. You may notice that they appear in a different color than variables or strings when typed in a code editor (with uppercase T and F). This is because True and False have their own unique type: bool.

The only bool types are True and False, and any variable assigned one of these values is referred to as a boolean variable. Numerous methods exist for creating Boolean variables. The simplest method is to assign a variable to True or False:

bool_var1 = True
bool_var2 = False

Now, be careful that the letters T and F are capitalized because if they are lower case, Python will interpret them as variables named true and false. Also, make sure that they are not inside quotation marks because they will be assigned as String variables. To can check the type of a variable with the type() function as shown below:

# A variable can be named lower case true
# But, this is not recommended.
true = 0

# This sets var1 = 0
var1 = true
print(type(var1))

# This is just a String.
var2 = "True"
print(type(var2))

# This is done correctly.
var3 = True
print(type(var3))

Output:

<class 'int'>
<class 'str'>
<class 'bool'>

Additionally, you can assign a variable to a boolean expression as shown below:

bool_var3 = 2 + 2 == 4 # True
bool_var4 = 3 - 2 != 1 # False

These variables now contain boolean values, which means that when they are referenced, they will return only the True or False values of the expression to which they were assigned.

%d bloggers like this: