Python Data Types
1. Overview of Data Types:
Python is a dynamically typed language, meaning you don't need to declare the type of a variable explicitly. Here's a summary of some commonly used data types in Python:
- Integer (
int
): Whole numbers without any decimal point, e.g.,5
,-10
,100
. - Float (
float
): Numbers with a decimal point or numbers written in exponential form, e.g.,3.14
,-0.001
,2.5e2
. - String (
str
): Ordered sequence of characters enclosed within single, double, or triple quotes, e.g.,"hello"
,'world'
,'''multiline string'''
. In most cases, single quotes (' '
) and double quotes (" "
) can be used interchangeably - Boolean (
bool
): Represents truth values,True
orFalse
. Notice that the first letter is always capitalized while the rest remains lowercase.
We can get the type of a variable or an object using function type()
as shown below.
x = 5
lyrics = """
We were both young when I first saw you~
I close my eyes and the flashback starts~
I'm standing there on a balcony in summer air~
""" # Multiline string with triple double quotes (triple single quotes also works).
print(f"The type of x is {type(x)}")
print(f"The type of 5 is {type(5)}")
print(f"The type of 3.14 is {type(3.14)}")
print(f"The value of 5e2 is {5e2}") # 5e2 is 500.0 expressed in scientific notation
print(f"The type of 5e2 is {type(5e2)}")
print(f"The type of 'Hello' is {type('Hello')}")
print(f"The type of True is {type(True)}")
print(f"The type of variable lyrics is {type(lyrics)}")
The type of x is <class 'int'>
The type of 5 is <class 'int'>
The type of 3.14 is <class 'float'>
The value of 5e2 is 500.0
The type of 5e2 is <class 'float'>
The type of 'Hello' is <class 'str'>
The type of True is <class 'bool'>
The type of variable lyrics is <class 'str'>
It's easy to mix up variable names with strings. Let's clarify the difference between the two with an example:
name = "Taylor Swift" # Here, 'name' is a variable storing the value "Taylor Swift"
print(name)
print("name") # "name" within double quotes is a string, not a variable
Taylor Swift
name
2. Data Type conversion
Converting between different data types is a common task in programming. Python provides built-in functions to convert data from one type to another. In this section, we'll explore how to convert float, string, and boolean , integers between each other.
Converting Float, String, Boolean to Integer:
You can convert a floating-point number to an integer using the int()
function. This function truncates the decimal part of the float, effectively rounding towards zero. After applying this function to variables, the variable type becomes int
.
float_num = 3.75
print(int(float_num)) # convert a floating-point number to integer
float_neg_num = -3.75
print(int(float_neg_num)) # convert a negative floating-point number to integer
3
-3
To convert a string to an integer, you can use the int()
function as well. This function parses the string and returns an integer if the string represents a valid integer literal. If the string contains non-numeric characters, it will raise a ValueError
. A ValueError
arises when a function receives an argument that doesn't match its expected input type, suggesting that the function is unable to proceed.
str_num = "123"
int_num = int(str_num) # convert the string to integer
print(int_num)
123
Booleans in Python (True
and False
) can be converted to integers where True
is equivalent to 1
, and False
is equivalent to 0
. You can use the int()
function or directly perform arithmetic operations to achieve this conversion.
bool_true = True
bool_false = False
int_true = int(bool_true) # convert True to integer
int_false = int(bool_false) # convert False to integer
print(int_true)
print(int_false)
1
0
Below is a summary of the content above:
- Use
int()
to convert float, string, and boolean values to integers. - When converting from float to int, the decimal part is truncated.
- For strings, ensure that the string represents a valid integer literal; otherwise, a
ValueError
will be raised. - Booleans are converted to integers as 1 (
True
) or 0 (False
).
print(int(3.75)) # Float to Integer
print(int("123")) # String to Integer
print(int(True)) # Boolean True to Integer
print(int(False)) # Boolean False to Integer
try: # String to Int with Non-numeric Characters
print(int("abc")) # Raises ValueError
except ValueError as e:
print("ValueError:", e)
3
123
1
0
ValueError: could not convert string to float: 'abc'
Converting Integer, String, Boolean to Float:
Similarly, we can convert integers
, strings
, and boolean
to float
using the function float()
.
- When converting from
int
tofloat
, the decimal part is added. - For
strings
, ensure that the string represents a valid integer literal; otherwise, aValueError
will be raised. Booleans
are converted tointegers
as 1.0 (True
) or 0.0 (False
).- After applying this function to variables, the variable type becomes
<class 'float'>
.
print(float(5)) # Integer to Float
print(float("3.14")) # String to Float
print(float("5e2")) # String to Float with Scientific Notation
print(float(" 3.14 ")) # String to Float with Leading/Trailing Whitespaces
try: # String to Float with Non-numeric Characters
print(float("abc")) # Raises ValueError
except ValueError as e:
print("ValueError:", e)
print(float(True)) # Boolean to Float
print(float(False))
5.0
3.14
500.0
3.14
ValueError: could not convert string to float: 'abc'
1.0
0.0
Converting Integer, Float, Boolean to String:
Similarly, we can convert integers
, float
, and boolean
to strings
using the function str()
. The function basically adds two quotes around the variable value and converts the variable type to <class 'str'>.
print(f"The type of str(123) is {type(str(123))}") # Converting Integers to Strings
print(f"The type of str(3.14) is {type(str(3.14))}") # Converting Floats to Strings
print(f"The type of str(True) is {type(str(True))}") # Converting Bools to Strings
The type of str(123) is <class 'str'>
The type of str(3.14) is <class 'str'>
The type of str(True) is <class 'str'>
Converting Integer, String, Boolean to Float:
Converting data to boolean values in Python follows simple rules:
- For numerical types (floats and integers), non-zero values are
True
, while zero isFalse
. - For strings, empty strings are False, while non-empty strings are
True
. - For collections and None, empty values are False, while non-empty or
None
values areTrue
. - The function converts the variable type to
<class 'float'>
print(bool(0), bool(10), bool(-5.5)) # Converting Floats to Bools
print(bool(''),bool("Hi")) # Converting Strings to Bools
print(bool(0.0), bool(0.1)) # Converting Floats to Bools
print(bool(None)) # Converting None to Bools
False True True
False True
False True
False