CodeNebula
Python🔧Core Languagebeginner

Variables and Types

Python · Core Language · Run with python3

Explanation

Python is dynamically typed — a variable is just a name bound to an object; the type lives on the object, not the variable. Everything is an object: integers, strings, functions, classes. Python's built-in types include `int`, `float`, `complex`, `bool`, `str`, `bytes`, `list`, `tuple`, `dict`, `set`, `frozenset`, and `NoneType`. `type()` returns an object's type; `isinstance()` checks inheritance.

Real-World Scenario

When reading config files you get strings like `"42"` and `"true"`. `int("42")` and `"true".lower() == "true"` convert them safely. Python's dynamic typing lets you write polymorphic functions that work on any type with the right interface — duck typing in action. ```python x = 42 # int y = 3.14 # float z = 1 + 2j # complex s = "hello" # str b = b"bytes" # bytes t = (1, 2, 3) # tuple (immutable) lst = [1, 2, 3] # list (mutable) d = {"a": 1} # dict nothing = None # NoneType print(type(x), isinstance(x, int)) # <class 'int'> True print(type(s), len(s)) # <class 'str'> 5 ```

Quick Snippet

snippet.py
x = 42            # int
y = 3.14          # float
z = 1 + 2j        # complex
s = "hello"       # str
b = b"bytes"      # bytes
t = (1, 2, 3)     # tuple (immutable)
lst = [1, 2, 3]   # list (mutable)
d = {"a": 1}      # dict
nothing = None    # NoneType

print(type(x), isinstance(x, int))   # <class 'int'> True
print(type(s), len(s))               # <class 'str'> 5

Full Example

variables_and_types.py
# Compile: python3 variables_and_types.py
# Output:
# <class 'int'> True
# <class 'str'> 5

x = 42
y = 3.14
z = 1 + 2j
s = "hello"
b = b"bytes"
t = (1, 2, 3)
lst = [1, 2, 3]
d = {"a": 1}
nothing = None

print(type(x), isinstance(x, int))
print(type(s), len(s))
print(f"int: {x}, float: {y}, complex: {z}")
print(f"tuple: {t}, list: {lst}")
print(f"None type: {type(nothing).__name__}")

# Type conversion
print(int("42"), float("3.14"), str(99))
print(list(t), tuple(lst))
Run command
python3 variables_and_types.py