Python (Part 3): Variables and Data Types

Variables and Data Types

  • 1 Overview
  • 2 Variables
  • 3 Data Types
    • 3.1 Numeric Types
    • 3.2 String Types
    • 3.3 Sequence Types
      • 3.3.1 List Types
      • 3.3.2 Tuples
      • 3.3.3 Range
    • 3.4 Mapping Types
    • 3.5 Set Types
    • 3.6 Boolean Types
    • 3.7 Binary Types
      • 3.7.1 Bytes
      • 3.7.2 Bytearray
      • 3.7.3 Memoryview
    • 3.8 NoneType
  • 4 Summary

Hello everyone, I am Ouyang Fangchao, and my public account shares the same name.Python (Part 3): Variables and Data Types

1 Overview

This section introduces variables and basic data types, including the dynamic typing feature of variables, numeric types, string types, sequence types (lists, tuples, range), mapping types (dictionaries), set types (set, frozenset), boolean types, and binary types (bytes, bytearray, memoryview). Simple examples are provided to illustrate the characteristics and typical usage of NoneType.

2 Variables

In Python, variables do not need to be declared, and there is no syntax for declaring variables; they are created when a value is first assigned to them.

a = 10

When assigning a value to a variable, there is no need to declare the variable’s type. Furthermore, after assigning a value to a variable, you can assign a different type of data to that variable again. Therefore, Python is a dynamically typed language, and its variables are not bound to a fixed data type.

b = 10
b = "Peter"

In Python, everything is an object, so a variable points to an object in memory, and that object has a type.

a = 90
b = a
# The id() function can be used to check the object identity
print(id(a))
print(id(b))

In the example above, the object 90 is first created, then a references this object, and subsequently, b also references this object. The two output statements below will show the same content because they reference the same object 90.

3 Data Types

The built-in data types in Python are as follows.

3.1 Numeric Types

Numeric types include int, float, and complex, which correspond to integers, floating-point numbers, and complex numbers, respectively.

a = 10
b = 1.09
c = 1 + 4j
print(type(a))
print(type(b))
print(type(c))

The type() function can be used to check the type of the object referenced by a variable, so the output of the above program is:

<class 'int'>
<class 'float'>
<class 'complex'>

3.2 String Types

The string type in Python is str.

a = "10"
print(type(a))

The output of the above program is:

<class 'str'>

3.3 Sequence Types

Sequence types, as the name suggests, store data in an ordered manner. Sequence types are further divided into list, tuple, and range.

3.3.1 List Types

A list, or list type, can store multiple data items, which are stored in order, and new elements are added to the end of the list.

mylist = ["apple", "banana", "orange"]
print(type(mylist))
print(mylist)

The output is:

<class 'list'>
['apple', 'banana', 'orange']

3.3.2 Tuples

A tuple is also an ordered sequence used to store multiple data items. Note that tuples are immutable; once created, the items in a tuple cannot be modified, added, or deleted.

3.3.3 Range

Range is the type of the object returned by the range() function, which is a sequence of numbers that can be converted to a list.

r = range(10)
print(type(r))
print(list(r))

The output of the above program is:

<class 'range'>
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

3.4 Mapping Types

The mapping type in Python is dict, also known as a dictionary. It is a structure that stores key-value pairs, where keys and values are separated by commas, and key-value pairs are separated by commas, with the entire dictionary enclosed in curly braces. Keys must be unique; otherwise, they will be overwritten, but values do not have to be unique.

mydict = {"name": "Peter", "address": "Test Road"}
print(type(mydict))
print(mydict)

The output is as follows:

<class 'dict'>
{'name': 'Peter', 'address': 'Test Road'}

The above example demonstrates the process of creating a field and outputting its contents.

3.5 Set Types

A set is a container used to store data items with two characteristics: unordered and disallowing duplicates. A set can be created by placing data items in curly braces and separating them with commas. There are two types of sets: set and frozenset.

# Integer set
myintset = {1, 3, 4}
# Mixed type set
myset = {1, "test", (1, 3, 4)}
print(myintset)
print(myset)

The output is:

{1, 3, 4}
<class 'set'>
{1, 'test', (1, 3, 4)}
<class 'set'>

Frozenset is a new class with the characteristics of a set; once created, its data items cannot be changed:

fset = frozenset([1, 2, 3])
print(type(fset))
print(fset)

The output is:

<class 'frozenset'>
frozenset({1, 2, 3})

3.6 Boolean Types

Boolean types are used to represent logical values: True and False. Note that True and False are keywords in Python and must be capitalized. At a lower level, True is actually 1, and False is 0. Other types of objects in Python will be automatically converted to boolean values in a boolean context: zero, None, empty sequences (empty strings, empty lists, empty tuples), empty dictionaries, etc., will be converted to False, while other values default to True. The built-in function bool() can be used to convert any value to a boolean, and the conversion rules conform to the truth evaluation mentioned earlier.

Simple example:

a = True
b = False

print(a and b)
print(a or b)
print(not a)
print(True + True)
print(bool(0))
print(bool([1, 2, 3]))
print(b)

The output is:

False
True
False
2
False
True
False

3.7 Binary Types

Python has three main binary types: bytes (byte strings), bytearray (byte arrays), and memoryview (memory views). These are important data types for handling non-text data (images, audio, video files, etc.).

3.7.1 Bytes

Bytes represent a sequence of bytes and are immutable. They can be defined using the bytes() function or by adding a b prefix in front of the string.

b = b'hello'  # Directly define bytes using b''
print(b)
print(b[1])
# b[1] = 90  # Cannot modify bytes, will raise an error

3.7.2 Bytearray

Bytearray represents a mutable sequence of bytes, allowing modification of data items (elements). A byte array can be created using the bytearray() function.

ba = bytearray(b'hello')
print(ba)
ba[1] = 100  # Modify the second byte
print(ba)
ba.append(33)  # Add a new byte
print(ba)

The output of the above program is as follows:

bytearray(b'hello')
bytearray(b'hdllo')
bytearray(b'hdllo!')

3.7.3 Memoryview

Memoryview provides different forms of access to existing binary data without copying the data.

# Create a mutable bytearray object
data = bytearray(b'hello world')

# Create a memoryview object pointing to the data memory
mv = memoryview(data)

# Output the integer value of the first byte, 104 represents 'h'
print(mv[0])

# Modify the data in the memoryview, which actually modifies the underlying bytearray
mv[0] = 72  # Change the ASCII code of 'h' (104) to 'H' (72)

print(data)  # Output the modified bytearray content: bytearray(b'Hello world')

The output of the above program is:

104
bytearray(b'Hello world')

3.8 NoneType

NoneType is a very special and unique type that has only one value—None. None is typically used to represent the absence of a value or a null value, commonly seen when a function does not have a clear return value or when a variable has not been assigned a value. The NoneType type has only one instance, which is None, and is a singleton object in Python, often used to indicate missing values, uninitialized values, or special empty states. It is different from False, 0, and empty strings, as it represents a state of “nothing.” When checking if a variable is None, it is recommended to use the is operator (e.g., variable is None) rather than ==, because None is a singleton, and using is is more accurate.

def find_item(items, target):
    for item in items:
        if item == target:
            return item
    # Return None if not found
    return None

result = find_item(['apple', 'banana'], 'orange')
if result is None:
    print('Target not found')
else:
    print('Found target item:', result)

4 Summary

In Python, variables do not require type declaration; their types are dynamically determined upon assignment. The rich variety of data types supports diverse data storage and manipulation, while binary types are suitable for handling non-text files and data streams. NoneType indicates a missing or null state.I am Ouyang Fangchao; when things are done well, interest naturally follows. If you like my article, feel free to like, share, comment, and follow. See you next time.

Leave a Comment