1.5. Python Data Types#
Variables can store different types of data which are used to do different things.
Data type |
Class |
Description |
---|---|---|
Integer |
|
Integer values, e.g., |
Float |
|
Floating point values (decimals), e.g., |
Complex |
|
Complex numbers, e.g., |
Boolean |
|
Boolean values, e.g., |
String |
|
Character string, e.g., |
List |
|
A list of elements, e.g., |
Python automatically use the appropriate data type for the value being assigned to a variable. The data type can be determined using the type()
command.
type(variable)
Enter the following commands into the console.
In [30]: type(-1)
Out[30]: int
In [31]: type(1.5)
Out[31]: float
In [32]: type(1 + 2j)
Out[32]: complex
In [33]: type(True)
Out[33]: bool
In [34]: type("Hello")
Out[34]: str
In [35]: type([1, 1.5, "hello", 1 + 2j])
Out[35]: list
1.5.1. Casting data types#
We can change the data type for a variable using casting with the following functions
int()
- returns an integer number from an input of a floating point number or stringfloat()
- returns a floating point number from an input of an integer or stringstr()
- returns a string from a range of data types.
Lets try casting between different data types. Enter the following commands into the console.
In [36]: int(1.23)
Out[36]: 1
In [37]: int("123")
Out[37]: 123
In [38]: float(123)
Out[38]: 123.0
In [39]: float("123")
Out[39]: 123.0
In [40]: str(123)
Out[40]: '123'
In [41]: str(1.23)
Out[41]: '1.23'
In [42]: str(1 + 2j)
Out[42]: '(1+2j)'