TechLead
Lección 2 de 25
5 min de lectura
Python

Variables y tipos de datos

Domina los tipos de datos integrados de Python, asignacion de variables, conversion de tipos y modelo de memoria

Variables en Python

En Python, las variables son nombres que se refieren a objetos en memoria. A diferencia de los lenguajes con tipado estatico, no declaras el tipo de una variable — Python lo infiere en tiempo de ejecucion. Una variable se crea en el momento en que le asignas un valor. Las variables en Python son esencialmente etiquetas o punteros a objetos, no contenedores que almacenan valores directamente.

# Variable assignment - no type declaration needed
name = "Alice"
age = 30
pi = 3.14159
is_active = True

# Multiple assignment
x, y, z = 1, 2, 3

# Same value to multiple variables
a = b = c = 0

# Swap variables (Pythonic way)
x, y = y, x
print(x, y)  # 2, 1

# Variable naming conventions (PEP 8)
user_name = "bob"        # snake_case for variables and functions
MAX_RETRIES = 3          # UPPER_CASE for constants
_private_var = "hidden"  # leading underscore for private

Tipos numericos

Python tiene tres tipos numericos integrados: int (enteros con precision arbitraria), float (punto flotante de doble precision de 64 bits) y complex (numeros complejos con partes real e imaginaria). Los enteros de Python no tienen limite de tamano — pueden ser tan grandes como tu memoria lo permita.

# Integers - arbitrary precision
small = 42
big = 10 ** 100  # A googol - no overflow!
binary = 0b1010  # 10 in binary
octal = 0o17     # 15 in octal
hexadecimal = 0xFF  # 255 in hex
readable = 1_000_000  # Underscores for readability

# Floats - double precision
pi = 3.14159
scientific = 2.5e-3   # 0.0025
infinity = float('inf')
not_a_number = float('nan')

# Integer division vs float division
print(7 / 2)    # 3.5 (true division)
print(7 // 2)   # 3 (floor division)
print(7 % 2)    # 1 (modulo)
print(2 ** 10)  # 1024 (exponentiation)

# Complex numbers
z = 3 + 4j
print(z.real)    # 3.0
print(z.imag)    # 4.0
print(abs(z))    # 5.0 (magnitude)

Cadenas de texto

Las cadenas en Python son secuencias inmutables de caracteres Unicode. Puedes crearlas con comillas simples, comillas dobles o comillas triples para cadenas multilinea. Las cadenas de Python 3 son Unicode por defecto, soportando caracteres de practicamente cualquier idioma y conjunto de simbolos.

# String creation
single = 'Hello'
double = "World"
triple = """This is a
multi-line string"""

# f-strings (formatted string literals) - Python 3.6+
name = "Alice"
age = 30
greeting = f"Hello, {name}! You are {age} years old."
calc = f"2 + 2 = {2 + 2}"
formatted = f"Pi is approximately {3.14159:.2f}"

# String methods (strings are immutable - methods return new strings)
text = "Hello, World!"
print(text.upper())        # "HELLO, WORLD!"
print(text.lower())        # "hello, world!"
print(text.replace("World", "Python"))  # "Hello, Python!"
print(text.split(", "))    # ["Hello", "World!"]
print("  spaces  ".strip())  # "spaces"
print(text.startswith("Hello"))  # True
print(text.find("World"))  # 7
print(text.count("l"))     # 3

# String slicing
s = "Python"
print(s[0])      # 'P'
print(s[-1])     # 'n'
print(s[0:3])    # 'Pyt'
print(s[::-1])   # 'nohtyP' (reverse)

# Raw strings (no escape processing)
path = r"C:\Users\new_folder\test"

Booleanos y None

bool es una subclase de int en Python. True es igual a 1 y False es igual a 0. None es el valor nulo de Python, representando la ausencia de un valor. Es un singleton — solo hay un objeto None en memoria.

# Booleans
is_valid = True
is_empty = False

# Truthy and falsy values
# Falsy: False, 0, 0.0, "", [], {}, set(), None, 0j
# Everything else is truthy

print(bool(0))       # False
print(bool(42))      # True
print(bool(""))      # False
print(bool("hello")) # True
print(bool([]))      # False
print(bool([1, 2]))  # True

# None
result = None
if result is None:
    print("No result yet")

# Always use 'is' for None comparison, not '=='
# This is because 'is' checks identity, '==' checks equality
x = None
print(x is None)      # True (correct)
print(x == None)       # True (works but not Pythonic)

Conversion de tipos

Python proporciona funciones integradas para convertir entre tipos. Estas se llaman constructores de tipo e incluyen int(), float(), str(), bool(), list(), tuple(), set() y dict().

# Explicit type conversion
num_str = "42"
num_int = int(num_str)       # 42
num_float = float(num_str)   # 42.0

pi = 3.14159
pi_int = int(pi)             # 3 (truncates, does not round)
pi_str = str(pi)             # "3.14159"

# Converting between collections
my_list = [1, 2, 3, 2, 1]
my_set = set(my_list)        # {1, 2, 3}
my_tuple = tuple(my_list)    # (1, 2, 3, 2, 1)
back_to_list = list(my_set)  # [1, 2, 3]

# Be careful with conversions
int("hello")   # ValueError!
int("3.14")    # ValueError! (use float() first)
int(float("3.14"))  # 3 (this works)

La funcion id() y el modelo de memoria

Cada objeto en Python tiene una identidad unica (direccion de memoria), un tipo y un valor. La funcion id() devuelve la identidad, type() devuelve el tipo y la variable te da el valor. Python almacena en cache enteros pequenos (-5 a 256) y cadenas cortas para mejorar el rendimiento.

# Identity vs equality
a = [1, 2, 3]
b = [1, 2, 3]
c = a

print(a == b)   # True (same value)
print(a is b)   # False (different objects)
print(a is c)   # True (same object)
print(id(a) == id(c))  # True

# Integer caching
x = 256
y = 256
print(x is y)  # True (cached)

x = 257
y = 257
print(x is y)  # May be False (not cached)

# type() and isinstance()
print(type(42))          # 
print(type("hello"))     # 
print(isinstance(42, int))         # True
print(isinstance(42, (int, float)))  # True (check multiple types)

Puntos clave

  • Tipado dinamico: Las variables son etiquetas que apuntan a objetos, no contenedores con tipo
  • Los enteros no tienen limite: Los int de Python tienen precision arbitraria
  • Las cadenas son inmutables: Los metodos devuelven nuevas cadenas, no modifican la original
  • Usa f-strings: Son la forma mas legible de formatear cadenas
  • Usa 'is' para None: Siempre compara con None usando 'is', no '=='

Continuar Aprendiendo