1.5. Python Data Types#

Variables can store different types of data which are used to do different things.

Table 1.3 Python Data Types#

Data type

Class

Description

Integer

int

Integer values, e.g., -1, 0, 1, 99

Float

float

Floating point values (decimals), e.g., 1.5, 2.718, 3.1415927

Complex

complex

Complex numbers, e.g., 1 + 2j (note the use of j for the imaginary number)

Boolean

bool

Boolean values, e.g., True or False

String

str

Character string, e.g., "hello world"

List

list

A list of elements, e.g., [1, 1.5, "hello", 1 + 2j]

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 string

  • float() - returns a floating point number from an input of an integer or string

  • str() - 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)'