Variables serve as containers for storing data values in memory. When you create a variable, Python allocates memory space to hold the assigned data. The interpreter determines the appropriate memory allocation based on the data type, enabling efficient storage and retrieval of information.
Variable Declaration
Unlike statically-typed languages, Python does not require explicit type declarations when defining variables. Each variable comprises three components in memory: an identifier (memory address), a name, and the stored data value. Variables must be assigned a value before they can be referenced in code.
The assignment operator (=) assigns values to variables, with the variable name on the left side and the value on the right side:
# -*- coding: UTF-8 -*-
quantity = 150
distance = 2500.75
product_name = "TensorFlow"
print(quantity)
print(distance)
print(product_name)
Output:
150
2500.75
TensorFlow
Multiple Assignment
Python supports assigning a single value to multiple variables simultaneously:
a = b = c = 42
This creates an integer object with value 42, and all three variables reference the same memory location.
You can also assign different values to multiple variables in one stateemnt:
x, y, message = 3, 7, "hello_world"
This assigns 3 to x, 7 to y, and the string "hello_world" to message.
Standard Data Types
Python provides several built-in data types for storing different kinds of data:
- Numbers - Integer, floating-point, and complex numbers
- String - Textual data
- List - Ordered, mutable sequences
- Tuple - Ordered, immutable sequences
- Dictionary - Key-value pairs
Numeric Types
Numeric types store numerical values. These are immutable types, meaning changing a numeric value creates a new object rather than modifying the existing one.
example_var = 5
another_var = 99
The del statement removes variable references:
del example_var
del first_var, second_var
Python supports four numeric types:
| Type | Description |
|---|---|
| int | Signed integer |
| long | Long integer (Python 2.x only) |
| float | Floating-point number |
| complex | Complex number (a + bj) |
Complex numbers consist of real and imaginary parts, represented as a + bj or using complex(a, b).
Strings
Strings are sequences of characters enclosed in quotes. They support both forward and reverse indexing:
sample = 'machine_learning'
print(sample[1:5]) # Outputs: "achi"
String slicing uses [start:end] notation, where the start index is inclusive and the end index is exclusive. The + operator concatenates strings, while * repeats strings:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
text = 'DeepLearning'
print(text) # Full string
print(text[0]) # First character
print(text[2:6]) # Characters at positions 2-5
print(text[4:]) # From position 4 to end
print(text * 2) # Repeated twice
print(text + "_Model") # Concatenation
Output:
DeepLearning
D
epL
Learning
DeepLearningDeepLearning
DeepLearning_Model
String slicing accepts an optional third parameter for step size.
Lists
Lists are versatile, ordered collections that can hold items of different types, including nested lists. They are defined using square brackets:
# -*- coding: UTF-8 -*-
data_list = ['pytorch', 512, 3.14, 'neural_net', 128.0]
sub_list = [256, 'optimizer']
print(data_list) # Full list
print(data_list[0]) # First element
print(data_list[1:3]) # Second and third elements
print(data_list[2:]) # Third element onwards
print(sub_list * 2) # Repeated list
print(data_list + sub_list) # Combined list
Output:
['pytorch', 512, 3.14, 'neural_net', 128.0]
pytorch
[512, 3.14]
[3.14, 'neural_net', 128.0]
[256, 'optimizer', 256, 'optimizer']
['pytorch', 512, 3.14, 'neural_net', 128.0, 256, 'optimizer']
Tuples
Tuples resemble lists but are immutabel—once created, their contents cannot be modified. They use parentheses instead of square brackets:
# -*- coding: UTF-8 -*-
data_tuple = ('tensorflow', 1024, 2.718, 'gradient', 64.0)
sub_tuple = (512, 'optimizer')
print(data_tuple) # Full tuple
print(data_tuple[0]) # First element
print(data_tuple[1:3]) # Second and third elements
print(data_tuple[2:]) # Third element onwards
print(sub_tuple * 2) # Repeated tuple
print(data_tuple + sub_tuple) # Combined tuple
Output:
('tensorflow', 1024, 2.718, 'gradient', 64.0)
tensorflow
(1024, 2.718)
(2.718, 'gradient', 64.0)
(512, 'optimizer', 512, 'optimizer')
('tensorflow', 1024, 2.718, 'gradient', 64.0, 512, 'optimizer')
Attempting to modify tuple elements raises an error:
# -*- coding: UTF-8 -*-
sample_tuple = ('value', 200, 1.5)
sample_list = ['item', 200, 1.5]
sample_tuple[1] = 999 # Raises TypeError
sample_list[1] = 999 # Valid operation
Dictionaries
Dictionaries store data as key-value pairs, offering fast lookup by key rather than by position. They are unordered collections defined with curly braces:
# -*- coding: UTF-8 -*-
empty_dict = {}
empty_dict['alpha'] = "Neural Networks"
empty_dict[42] = "Deep Learning"
metadata = {'framework': 'PyTorch', 'version': 2.1, 'license': 'BSD'}
print(empty_dict['alpha']) # Value for key 'alpha'
print(empty_dict[42]) # Value for key 42
print(metadata) # Complete dictionary
print(metadata.keys()) # All keys
print(metadata.values()) # All values
Output:
Neural Networks
Deep Learning
{'framework': 'PyTorch', 'version': 2.1, 'license': 'BSD'}
dict_keys(['framework', 'version', 'license'])
dict_values(['PyTorch', 2.1, 'BSD'])
Type Conversion
Python provides built-in functions to convert between data types:
| Function | Purpose |
|---|---|
| int(x) | Convert to integer |
| float(x) | Convert to float |
| complex(a, b) | Create complex number |
| str(x) | Convert to string |
| repr(x) | Convert to expression string |
| eval(str) | Evaluate string as Python code |
| tuple(s) | Convert to tuple |
| list(s) | Convert to list |
| set(s) | Convert to set |
| dict(d) | Create dictionary from key-value pairs |
| frozenset(s) | Convert to immutable set |
| chr(x) | Convert integer to character |
| ord(x) | Convert character to integer |
| hex(x) | Convert to hexadecimal string |
| oct(x) | Convert to octal string |