5.7. Combining Data Types

5.7.1. Casting, Calculation, and Concatination

Python is a loosely typed programming language, meaning that variables do not need to be explicitly declared alongside their data type, and they can sometimes dynamically change type to suit a particular requirement.

5.7.1.1. Casting

Sometimes it is useful to explicitly force a variable to change from one data type to another. We can do this with type casting, re-assigning variables the basic data types int, float, string, or boolean. The syntax doing this is:

float(variable)  # re-assigns a variable as data type "float"

int(variable)  # re-assigns a variable as data type "int"

str(variable)  # re-assigns a variable as data type "str"

bool(variable)  # re-assigns a variable as data type "boolean"

Casting to float will add a decimal place to an integer, or convert the string "3.0" to the float 3.0. The boolean False will be converted to 0.0 and True to 1.0

float(3)
3.0
float("3.0")
3.0
float(True)
1.0

Casting from float to int will truncate the decimal place, not round it (if you want to round a number to the nearest integer, use the built-in function round()) Booleans True and False are converted to 1 and 0.

int(2.0)
2
int(2.9)
2
round(2.9)
3
int(False)
0
int("19")
19

Casting to a string will return a string containing the number or boolean value

str(29)
'29'
str(29.1)
'29.1'
str(True)
'True'

Casting to boolean will return False for the integer 0, float 0.0 or empty string “”, and True for pretty much anything else

bool(0)
False
bool(1.0)
True
bool('')
False
bool("pirates")
True

Casting only works within a valid range of variables that can be converted. Invalid type casts will raise an error:

int("fourteen")
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/tmp/ipykernel_3339847/536369517.py in <module>
----> 1 int("fourteen")

ValueError: invalid literal for int() with base 10: 'fourteen'

5.7.1.2. Calculations

For many operations, type casting occurs automatically. Python’s built-in mathematical functions work with any combination of int and float data types, and the python interpreter will assign the output as type int if possible, or float if not.

ans = 6 + 2
ans
8
type(ans)
int
ans = 8 - 5.2
ans
2.8
type(ans)
float

Similarly for multiplication and division:

ans = 4 * 2
type(ans)
int
ans = 5 / 2
type(ans)
float

5.7.1.3. Concatenation/Formatted Strings

Often, we would like to stick strings together, or express a numerical value within an existing string. The python syntax offers several ways to do this.

  1. The + operator works to concatenate strings together, i.e. take the string to the right of the operator and stick it to the end of the string on the left

str1 = "race"
str2 = "car"

str1 + str2
'racecar'

However, this doesn’t work for combinations of string and numeric data types, as the + operator has a different meaning for int and float – the interpreter can’t figure out whether to add numeric values or concatenate strings.

num = 3
print(num + " blind mice")
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/tmp/ipykernel_3339847/3430437526.py in <module>
      1 num = 3
----> 2 print(num + " blind mice")

TypeError: unsupported operand type(s) for +: 'int' and 'str'

There are a few ways to overcome this problem.

A) Using type casting:

print(str(3) + " blind mice")
3 blind mice

B) Use a tuple containing strings and numeric data:

print(3, "blind mice")
3 blind mice

C) Using f string literals. Type the letter f at the beginning of a string, then insert any variable inside of curly brackets {variable} and it will format the variable into the string (This is the best way that will work in the largest variety of contexts):

print(f"{3} blind mice")
3 blind mice