Python Booleans and Type Conversion

Python booleans (type bool) are the easiest Python Data Types. There are only two things you need to remember: True and False.

Booleans are depictions of 0, or empty (False), and 1 (True), which can be mapped to any Python data type. You can check what the boolean return will be by using the bool() method.

a = []
b = 123
c = -1
d = '\'
e = 'Hello'
f = -123

Running bool()on the above will yield the following:

print(bool(a))
False
print(bool(b))
True
print(bool(c))
True
print(bool(d))
False
print(bool(e))
True
print(bool(f))
True

Type Conversion

Python uses dynamic typing for variables, as discussed in a previous blog post (Integers and Variables). You can take a variable of one data type and cast it into another data type. The perfect example is the built-in method for accepting user input called input. Let’s prompt the user for the year they were born and what year it is now to calculate their approximate age.

year_born = input('What year were you born in: ')
What year were you born in: 1981
 
current_year = input("What year is it: ")
What year is it: 2020
current_year - age
Traceback (most recent call last):
File "", line 1, in
TypeError: unsupported operand type(s) for -: 'str' and 'str'

That isn’t right; I didn’t put quotes around my input; why is it taking it as a string? By default, the input method takes all input as a string.  To change it to an integer, you need to cast it into the int() method.

year_born = int(input('What year were you born in: '))
What year were you born in: 1981
current_year = int(input("What year is it: "))
What year is it: 2020
current_year - year_born
39

There is logic built into the int method that will check to ensure that you don’t try to pass in a non-integer.

test_input = int(input('Tell me a number between 0 and 10: '))
Tell me a number between 0 and 10: Five
Traceback (most recent call last):
File "", line 1, in
ValueError: invalid literal for int() with base 10: 'Five'