In Python, variables are fundamental building blocks that allow you to store, modify, and access data throughout your code. They provide a way to label data with a descriptive name, making your programs more readable and easier to manage.
In this article, you’ll explore variables in detail, with examples to help you understand how they work in practice.
Numeric Types
- Integer (int)
Represents whole numbers without a decimal point. Integer can be positive, negative, or zero.
Example:
age = 30 - Float (float)
Represents numbers with a decimal point. Floats can represent a wide range of values including fractions.
Example:
temperature = 89.2 - Complex (complex)
Represents complex numbers with both a real and an imaginary part. The imaginary part is denoted by a j.
Example:
complex_number = 7 + 3j
Sequence Types
- String (str)
Represents a sequence of characters enclosed in quotes. Strings can be single-quoted, double-quoted, or triple-quoted.
Example:
greeting = “Hello, world!” - List (list)
An ordered, mutable collection of items. Lists can contain items of different data types and can be modified after creation.
Example:
fruits = [“banana”, “apple”, “peach”, “cherry”, “grapes”] - Tuple (tuple)
An ordered, mutable collection of items. Once created, tuples cannot be modified. Tuples can contain different data types.
Example:
point = (10, 20) - Range (range)
Represents an immutable sequence of numbers, often used for iteration in loops. It can generate a sequence of numbers based on a start, stop, and step.
Example:
numbers = range(1, 10, 2)
# Generates numbers 1, 3, 5, 7, 9
Mapping Types
- Dictionary (dict)
A collection of key-value pairs. Keys are unique, and each key is associated with a value. Dictionaries are mutable.
Example:
person = {“name”: “Isabella”, “age”: 31}
Set Types
- Set (set)
An unordered collection of unique items. Sets do not allow duplicate values and are mutable.
Example:
unique_numbers = {1, 2, 3, 4} - Frozen Set (frozenset)
An immutable version of a set. Once created, elements cannot be added or removed.
Example:
frozen_numbers = frozenset ([1, 2, 3, 4])
Boolean Types
- Boolean (bool)
Represents a value that can be either True or False. Used for logical operations and conditions.
Example:
is_active = True
Binary Types
- Bytes (bytes)
An immutable sequence of bytes. It is typically used for binary date. Each byte is a number between 0 and 255.
Example:
byte_data = b”hello” - Byte Array (bytearray)
An mutable sequence of bytes. It allows modification of the byte data.
Example:
mutable_byte_data = bytearray ([65, 66, 67])
- Memory View (memoryview)
A view object that provides a view of an array’s data without copying it. Useful for handing large data efficiently.
Example:
data = bytearray (“hello”,”utf-8″)
view = memoryview (data)