Concept: Casting
Each of the four primary data types can be converted to another type using the cast functions: str(), int(), float(), and bool().
While almost everything can be cast to a string, not everything can be cast to an integer or float. For example, the string "Hello World" cannot be cast to an integer or float, but the string "42" can be cast to an integer and the string "3.14" can be cast to a float.
If you try to cast a string that cannot be converted to an integer or float, you will get a ValueError:
# This will raise a ValueError
int("Hello World") # ValueError: invalid literal for int() with base 10: 'Hello World'
# This will successfully cast the string to an integer
int("42") # 42
# This will successfully cast the string to a float
float("3.14") # 3.14
# This will cause a ValueError because the string contains a decimal point
int("3.14") # ValueError: invalid literal for int() with base 10: '3.14'Everything can be cast to a boolean, but the result may not be what you expect. For example, the string "False" is not the same as the boolean value False. The string "False" is a non-empty string, so it will be cast to True when converted to a boolean. There are only a few values that will be cast to False, everything else will be cast to True:
| Value | Cast to Boolean |
|---|---|
0 | False |
0.0 | False |
"" | False |
None | False |
| Everything else | True |