3. Data Types

See: https://www.w3schools.com/python/python_datatypes.asp

3.1. Data type categories

Type Category

Data Type

TextType

str

NumericTypes

int, float, complex

SequenceTypes

list, tuple, range

MappingType

dict

SetTypes

set, frozenset

BooleanType

bool

BinaryTypes

bytes, bytearray, memoryview

NoneType

NoneType


3.2. Data type examples

Example

Data Type

Type Category

Mutability

Ordered

Structure

text = “Hello, World!”

str

Text Type

Immutable

Ordered

in single ‘’ or double quotes “”

integer = 42

int

Numeric Type

Immutable

Unordered

whole numbers

floating_point = 3.14

float

Numeric Type

Immutable

Unordered

decimals

complex_number = 1 + 2j

complex

Numeric Type

Immutable

Unordered

real + imaginary numbers

my_list = [1, 2, 3, 4]

list

Sequence Type

Mutable

Ordered

square brackets []

my_tuple = (1, 2, 3, 4)

tuple

Sequence Type

Immutable

Ordered

parentheses ()

my_range = range(1, 10)

range

Sequence Type

Immutable

Ordered

range function

my_set = {1, 2, 3, 4}

set

Set Type

Mutable

Unordered

{} with unique items

my_frozenset = frozenset([1, 2, 3, 4])

frozenset

Set Type

Immutable

Unordered

frozenset() with unique items

my_dict = {“name”: “Anne”, “age”: 28}

dict

Mapping Type

Mutable

Ordered

{} with key-value pairs

is_valid = True

bool

Boolean Type

Immutable

Unordered

True or False

nothing = None

NoneType

None Type

Immutable

Unordered

None

my_bytes = b”Hello”

bytes

Binary Type

Immutable

Unordered

b”” or b’’

my_ba = bytearray([65, 66, 67])

bytearray

Binary Type

Mutable

Unordered

bytearray()


3.3. Strings

A string is a sequence of characters surrounded by either single quotation marks (' ') or double quotation marks (" ").

  • Using Quotes Within Strings: - If your text contains single quotes, you can use double quotes to enclose the string.

    • Example: "It's a nice day."

    • If your text contains double quotes, you can use single quotes to enclose the string. - Example: 'Jane said "Go now", then left.'`

  • Using Both Quotes Within Strings: - If your text contains both single and double quotes, you can use triple quotes to enclose the string.

    • Example: '''My favourite quote from Jane's essay was "Go now". Short and sweet.'''

  • Escaping Quotes: - You can use the backslash (``) to escape quotes within a string, forcing them to be used literally.

    • Example: ‘It's a nice day.’

  • Triple Quotes for Documentation and Multi-line Strings: - Triple quotes (either ''' or """) are used for documentation strings (docstrings) and multi-line strings.

    • Example of a docstring for a function:

      def square_number(n):
          """
          This function returns the square of a given number.
      
          Parameters:
          n (int or float): The number to be squared.
      
          Returns:
          int or float: The square of the input number.
          """
          return n ** 2
      
    • Example of a multi-line string:

      """This is a multiline string.
      It can span multiple lines.
      You can include line breaks."""
      

3.4. Numbers

Numbers are written without quotes.
An integer is a whole number.
e.g. 2
A float is a decimal.
e.g. 3.5

3.5. Booleans

Booleans have the value True or False.


3.6. Types

The type() function can be used to get the data type for a variable.

# String
print(type('hello'))   # <class 'str'>

# Integer
print(type(1))         # <class 'int'>

# Float
print(type(1.64))      # <class 'float'>

# Boolean
print(type(True))      # <class 'bool'>

# None
print(type(None))      # <class 'NoneType'>

Questions

  1. Predict the output from print(type('123')).

  2. Predict the output from print(type(123)).

  3. Predict the output from print(type('False')).


3.7. Type casting

See: https://www.w3schools.com/python/python_casting.asp

The conversion of one type to another is called type casting.
Data types can’t be mixed so type casting is needed to convert data to the same type so that they can be used together.

3.7.1. Converting numbers to strings

str() converts a number to a string with a number in it

j = str(3.01) # j will be "3.01"
An integer can be converted to a string using the str() function.
The premierships integer is converted to a string so it can be combined with the rest of the strings for printing.
team = 'Richmond'
premierships = 11
print(team + ' has won ' + str(premierships) + ' premierships.')

3.7.2. Converting numbers as strings to numbers

int() converts a string consisting of an integer to an integer number

c = int("3")      # c will be 3

float() converts a string consisting of a decimal to a decimal number

g = float("4.23") # g will be 4.23

Questions

  1. Predict the output from print(int(2.5)).

  2. Predict the output from print(int("3")).

  3. Predict the output from print(float(1)).

  4. Predict the output from print(float("4.23")).

  5. Predict the output from print(str(3.01)).