Explore the core data types in Python along with variable management, scope rules, and practical examples.
Python provides a rich set of built-in data types to store various kinds of information efficiently.
Whole numbers (no decimals).
age = 25
print(type(age)) # <class 'int'>
print(age) # 25
Decimal/fractional numbers.
pi = 3.14159
print(type(pi)) # <class 'float'>
print(pi) # 3.14159
Text / sequence of characters.
name = "Python"
print(type(name))# <class 'str'>
print(name) # Python
Truth values (True or False).
is_active = True
print(type(is_active)) # <class 'bool'>
print(is_active) # True
Ordered, mutable collection.
fruits = ["Apple", "Banana"]
print(type(fruits)) # <class 'list'>
print(fruits) # ['Apple', 'Banana']
Ordered, immutable collection.
coords = (10, 20, 30)
print(type(coords)) # <class 'tuple'>
print(coords) # (10, 20, 30)
Unordered collection of unique items.
colors = {"red", "green"}
print(type(colors)) # <class 'set'>
print(colors) # {'red', 'green'}
Key-value pair mappings.
student = {"name": "Alice", "age": 20}
print(type(student)) # <class 'dict'>
print(student) # {'name': 'Alice'...}
Numbers with real & imaginary parts.
c = 2 + 3j
print(type(c)) # <class 'complex'>
print(c) # (2+3j)
Immutable binary data sequence.
data = b"Python"
print(type(data)) # <class 'bytes'>
print(data) # b'Python'
Mutable binary data sequence.
data = bytearray(5)
print(type(data)) # <class 'bytearray'>
Represents absence of a value.
x = None
print(type(x)) # <class 'NoneType'>
print(x) # None
# Same value
a = b = c = 100
# Different values
x, y, z = 10, 20, 30
# Variable swapping
m, n = 5, 10
m, n = n, m # m becomes 10, n becomes 5
x = "Global" # Global variable
def func():
y = "Local" # Local variable
print("Inside function, y =", y)
func()
print("Outside function, x =", x)
x = "100"
print(int(x) + 50) # Output: 150
y = 3.99
print(int(y)) # Output: 3 (truncates decimal)
flag = "True"
print(bool(flag)) # Output: True
int(), float(), str(), bool(), list(), tuple(), dict()PI = 3.14159 # Constant by convention (UPPERCASE)
a = 10
del a # Deletes variable from memory
# Checking if variable exists
if 'x' in globals():
print("x exists")
Note: Python does not enforce rigid hardware constants, but using uppercase names signals to other developers that a variable value should remain constant.