Tutorial de Python
Learn Python from your first print() to classes, files and async code. Real Python running in your browser, quizzes and projects. No installation needed.
Getting Started
- Primeros pasos con Python Meet Python, one of the most popular programming languages. Print your first messages, store values in variables, read input and do quick calculations, all in your browser.
- Cómo ejecutar código Python Learn the ways to run Python - the interactive REPL, script files, editors and IDEs - how to install it, and what the in-browser runner on this site can do.
- Sintaxis y sangría Learn how Python reads your code - statements, indentation blocks, long lines, case sensitivity and comments - and how to fix IndentationError and SyntaxError.
- Variables y nombres Learn how Python variables work - assignment, naming rules and conventions, multiple assignment, swapping values and dynamic typing - with examples to run.
- Entrada y salida Control Python output with print() options like sep and end, read user input with input(), convert it to numbers safely, and format results neatly.
Data Types
- Tipos de datos Tour Python's built-in data types - numbers, strings, lists, tuples, dicts, sets and None - check them with type() and isinstance(), and learn about mutability.
- Números Work with Python numbers - int, float and complex, arithmetic, rounding rules, why 0.1 + 0.2 isn't 0.3, and exact math with the decimal and fractions modules.
- Cadenas de texto Learn Python strings - single, double and triple quotes, escape sequences, raw strings, indexing characters, immutability, and joining and repeating text.
- Métodos de cadenas Master Python's most useful string methods - changing case, strip, split and join, find and replace, startswith, count and the is-checks - with live examples.
- Formato de cadenas Format text with Python f-strings - expressions, the = specifier, alignment, padding, decimals, thousands separators, percentages, dates and str.format().
- Booleanos y valores verdaderos o falsos Learn how Python's bool type works, which values count as truthy or falsy, how bool() converts values, and why True behaves like the number 1.
- None Learn what None means in Python, why you check it with "is None", where it appears as a default return value, and how to use it safely for optional values.
- Conversión de tipos Convert between Python types with int(), float(), str() and bool(). Learn implicit vs explicit conversion, rounding traps, and how to handle ValueError safely.
- bytes y bytearray Learn Python's binary types. Encode and decode text, slice and search bytes, change data with bytearray, read hex and use struct to pack numbers.
- Copias superficiales y profundas Understand aliasing in Python. Learn why assignment does not copy, how shallow copies share nested data, and when to use copy.deepcopy.
Operators
- Operadores aritméticos Master Python's arithmetic operators: + - * / // % and **. Learn floor division with negatives, modulo tricks, divmod(), and the operator precedence rules.
- Operadores de comparación y lógicos Compare values with ==, !=, < and >, chain comparisons like 0 < x < 10, and combine conditions with and, or and not, including short-circuit evaluation.
- Operadores de asignación y el operador morsa Update variables with Python's augmented assignment operators like += and *=, see how they behave with lists and strings, and learn when the walrus operator := helps.
- Operadores de pertenencia e identidad Use in and not in to search strings, lists, sets and dicts, and is and is not to check object identity. Learn the real difference between == and is in Python.
- Operadores a nivel de bits y precedencia Learn Python's bitwise operators &, |, ^, ~, << and >> with binary examples, flags and bitmasks, plus the full operator precedence table and its common traps.
Control Flow
- if, elif y else Make decisions in Python with if, elif and else. Learn how conditions and indentation work, how to avoid deep nesting, and when to use a conditional expression.
- Coincidencia de patrones con match Learn Python's match statement with literal, capture, wildcard, sequence, mapping and class patterns, plus guards, OR patterns and when to choose if/elif.
- Bucles for Learn Python for loops step by step. Iterate over strings, lists and dictionaries, number items with enumerate(), pair them with zip() and nest loops safely.
- Bucles while Learn how Python while loops repeat code while a condition is true. Validate input, use sentinel values, write while True loops and avoid accidental infinite loops.
- break, continue y else en bucles Control Python loops precisely. Exit early with break, skip iterations with continue, use the for/while else clause for searches, and fill empty blocks with pass.
- range() Master Python's range(). Count with start, stop and step, loop backward, understand why the stop value is excluded, and see why range objects use almost no memory.
Data Structures
- Listas Learn Python lists from scratch. Create lists, read items with positive and negative indexes, change them in place, understand shared references and work with nested lists.
- Métodos de listas A practical tour of Python list methods. Add items with append, extend and insert, remove them with remove, pop and clear, then sort, reverse, search, count and copy.
- Rebanadas (slicing) Learn Python slicing with start:stop:step. Take parts of lists and strings, use negative indexes and steps, reverse with [::-1] and replace sections with slice assignment.
- Comprensiones de listas Write Python list comprehensions with confidence. Transform and filter data in one line, use if/else inside them, flatten nested lists and know when a plain loop reads better.
- Tuplas Learn Python tuples, the fixed-size sequences you can't change. Create them, index them, pack and unpack values, and meet named tuples for readable records.
- Conjuntos Learn Python sets for storing unique values. Remove duplicates, test membership fast, and combine collections with union, intersection, difference and frozenset.
- Diccionarios Learn Python dictionaries, the key-value store behind most Python code. Create them, read and change values, delete keys, loop over items and rely on their order.
- Métodos de diccionarios Master Python dictionary methods. Use get and setdefault for missing keys, update and the | operator to merge, pop and popitem to remove, and views to inspect data.
- Comprensiones de diccionarios y conjuntos Build dictionaries and sets in one readable line with Python comprehensions, filter and transform data, and save memory with lazy generator expressions.
- Desempaquetado y expresiones con asterisco Learn Python unpacking. Split sequences into variables, grab the rest with a star, ignore values with _, and spread lists and dicts with * and ** in calls and literals.
- Arrays con el módulo array Learn when Python's array module beats lists. Store typed numbers compactly with array.array, and use bytes, bytearray and memoryview.
Functions
- Funciones Learn to write your own Python functions with def. Pass in parameters, return results, document them with docstrings, and organize programs into small reusable pieces.
- Argumentos: valores por defecto, *args y **kwargs Master Python function arguments. Use positional and keyword arguments, default values, *args and **kwargs, keyword-only and positional-only parameters safely.
- Valores de retorno Learn how Python functions send results back with return, how to return several values as a tuple, why early returns simplify code, and when you get None.
- Ámbito: local, global y nonlocal Understand where Python looks up names with the LEGB rule, how local and global variables differ, when to use global and nonlocal, and how closures work.
- Funciones lambda Write small anonymous functions with Python's lambda, use them as sort keys and callbacks, learn their limits, and know when a regular def is the better choice.
- Recursión Learn recursion in Python step by step - base cases, recursive cases, the call stack, RecursionError, and speeding up recursive functions with functools.cache.
- Funciones de orden superior Treat functions as values in Python - pass them as arguments, return them from other functions, and use map, filter, sorted, min, max and reduce effectively.
- Decoradores Learn how Python decorators wrap functions to add timing, logging, caching or validation, why functools.wraps matters, and how to write decorators that take arguments.
- Generadores Write Python generator functions with yield, build lazy and infinite sequences, use generator expressions to save memory, chain pipelines and delegate with yield from.
- Iteradores y el protocolo de iteración See how Python for loops really work - iterables vs iterators, iter() and next(), writing classes with __iter__ and __next__, and a first look at itertools.
Modules and the Standard Library
- Módulos e importaciones Learn how Python modules work. Use import, from ... import and aliases, write your own module, and understand the if __name__ == "__main__" idiom.
- Paquetes y pip Learn how Python packages group modules into folders, how relative imports work, and how to install third-party code from PyPI with pip and requirements files.
- math y random Use Python's math module for roots, rounding, logs and trigonometry, generate random numbers and choices with random, and summarize data with statistics.
- uuid, ID aleatorios y claves únicas Generate unique identifiers in Python with uuid1, uuid4, uuid5 and uuid7, create secure tokens with secrets, and learn when collisions matter and which ID to use.
- Fechas y horas Work with dates and times in Python using datetime, date and timedelta. Do date math, format and parse strings with strftime and strptime, and handle time zones.
- collections Learn Python's collections module. Count things with Counter, group with defaultdict, build fast queues with deque, and use namedtuple and ChainMap well.
- itertools y functools Master Python's itertools and functools. Chain, group, slice and combine iterables lazily, then use partial, reduce and cache to build smarter functions.
- Trabajar con JSON Learn to read and write JSON in Python. Convert data with json.dumps and json.loads, save JSON files, pretty-print, handle errors and encode dates and classes.
- Guardar objetos con pickle y shelve Save almost any Python object to bytes or a file with pickle, store objects by key with shelve, avoid the security trap, and copy with deepcopy.
- XML con ElementTree Read and write XML in Python with ElementTree. Parse documents, find elements with XPath, handle namespaces, build and save XML, and use defusedxml.
- Expresiones regulares Learn regular expressions in Python with the re module. Write patterns, match and search text, capture groups, find all matches, replace text and compile patterns.
- Rutas con pathlib Handle files and folders the modern way with pathlib. Build paths with /, inspect names and suffixes, read and write files, create folders and find files with glob.
- Archivos y carpetas con os y shutil Work with folders in Python. List and walk directories with os, read environment variables, copy, move and delete trees with shutil, use tempfile.
- decimal y fractions Avoid floating-point surprises in Python. Use Decimal for money, control precision and rounding with contexts, and Fraction for exact rational numbers.
- El módulo statistics Summarize small data sets with Python's statistics module. Compute mean, median, mode, standard deviation, quantiles, correlation and linear regression.
Files and Errors
- Leer y escribir archivos Learn to read and write text files in Python with open() and the with statement. Covers file modes, reading line by line, appending, and encodings.
- Archivos CSV Read and write CSV files in Python with csv.reader, csv.writer, DictReader and DictWriter. Learn about quoting, delimiters, headers and number conversion.
- Archivos de Excel con openpyxl Read and write Excel .xlsx files with openpyxl. Create workbooks, fill cells, add formulas, style headers, set number formats, add charts and use pandas.
- Excepciones y try/except Learn how Python exceptions work and how to handle them with try, except, else and finally. Catch specific errors, inspect them, and avoid common mistakes.
- Archivos PDF con pypdf Work with PDF files in Python using pypdf. Extract text, merge, split, rotate and reorder pages, edit metadata, add a watermark and encrypt a PDF. Runs live.
- Lanzar excepciones Learn to raise exceptions in Python with raise, choose the right exception type, re-raise errors you can't handle, and chain exceptions with raise ... from.
- Excepciones personalizadas Create your own exception classes in Python by subclassing Exception, add extra data, design an exception hierarchy, and handle exception groups with except*.
- Administradores de contexto Understand how Python's with statement works, write context managers with __enter__ and __exit__ or contextlib.contextmanager, and use suppress and ExitStack.
- Depuración y assert Learn to debug Python code. Read tracebacks from the bottom up, use print debugging well, check assumptions with assert, log with the logging module, and meet pdb.
- Registro y advertencias Set up real logging in Python with loggers, handlers, formatters and dictConfig, log to files, and use the warnings module for deprecations and soft problems.
- Zip, tar y compresión Create and read archives in Python. Use zipfile, tarfile, gzip and shutil.make_archive, extract files safely and compress data in memory.
Object-Oriented Programming
- Clases y objetos Start object-oriented programming in Python. Define classes, create objects, set attributes in __init__, write methods with self, and use class attributes.
- Métodos de instancia, de clase y estáticos Learn the three kinds of methods in Python classes, when to use @classmethod and @staticmethod, and how to build clean alternative constructors.
- Herencia Learn Python inheritance step by step - create subclasses, override methods, extend them with super(), check types with isinstance, and understand the MRO.
- Métodos especiales (dunder) Make your Python classes feel built in. Learn __str__ and __repr__, comparisons, __len__, __getitem__, iteration and operator overloading with clear examples.
- Propiedades Use Python's @property to create computed attributes, validate values with setters, make read-only attributes and keep a clean public interface for your classes.
- Clases de datos Learn Python data classes - let @dataclass write __init__, __repr__ and __eq__, set defaults safely with field(), and make frozen, ordered and slotted classes.
- Clases abstractas y protocolos Define interfaces in Python with abstract base classes (abc), understand duck typing, and describe expected methods structurally with typing.Protocol.
- Enumeraciones Replace magic strings and numbers with Python enums. Learn Enum, auto(), StrEnum, IntEnum, Flag, looking up members, adding methods and using enums in match.
- Principios de POO: encapsulación, polimorfismo y abstracción Apply core OOP principles in Python. Learn encapsulation with _ and __ name mangling, polymorphism and duck typing, abstraction, composition vs inheritance.
- Metaclases, descriptores y entresijos de los objetos Look inside Python objects. Learn how __dict__ and attribute lookup work, save memory with __slots__, write descriptors, and meet metaclasses.
Beyond the Basics
- Anotaciones de tipo Learn Python type hints - annotate variables and functions, use list[int], unions with |, Optional, TypedDict, Literal and generics, and check code with mypy.
- Programación asíncrona con asyncio Learn async programming in Python with asyncio. Write coroutines with async and await, run work concurrently with tasks, gather and TaskGroup, and add timeouts.
- Hilos, procesos y concurrent.futures Learn when to use threads, processes or asyncio in Python. Understand the GIL, avoid race conditions with locks, and run jobs with ThreadPoolExecutor.
- Pruebas con unittest y doctest Learn to test Python code with unittest and doctest. Write test cases, use assertions, check exceptions, share setup, and read test failures with confidence.
- Entornos virtuales y configuración de proyectos Set up real Python projects. Create virtual environments with venv, install packages with pip, pin requirements, lay out folders and describe it all in pyproject.toml.
- Programas de línea de comandos con argparse Build real command-line tools in Python. Read sys.argv, define arguments and options with argparse, add subcommands and help text, and return proper exit codes.
- Interfaces de escritorio con tkinter Build desktop apps with tkinter. Create windows and widgets, lay them out with pack and grid, handle events, use variables and timers, and build a to-do app.
- Gráficos con turtle Learn Python's turtle module. Move, turn and draw shapes with loops, use colors and fills, handle key presses, and try the ideas live with a plotting stand-in.
- Frameworks de interfaz gráfica en Python: Kivy, PyQt y Streamlit Compare Python GUI frameworks. See Kivy, PySide6/PyQt, wxPython and Streamlit code side by side, learn signals and the rerun model, and pick the right toolkit.
- Escribir código pythónico Write Python the way experienced developers do. Learn PEP 8 style, the Zen of Python, everyday idioms like enumerate and unpacking, and the anti-patterns to avoid.
- Medir y mejorar el rendimiento Make Python code faster the right way. Time code with timeit, find hotspots with cProfile, pick the right data structures, save memory with generators, and cache results.
- Gestión de memoria See how Python manages memory. Learn how names reference objects, how reference counting and the garbage collector free them, and use weakref and getsizeof.
- Pruebas con pytest Learn pytest from the ground up. Write plain assert tests, share setup with fixtures, run many cases with parametrize, mock dependencies, and measure coverage.
- Comprobación estática de tipos con mypy Learn to check Python types with mypy. Run the checker, read its errors, narrow Optional values, write generics and Protocols, and configure strict mode in pyproject.toml.
- Empaquetar y publicar una biblioteca Learn to package a Python library. Use the src layout, write pyproject.toml, build a wheel and sdist with build, test the install, and publish to PyPI with twine.
- Python seguro: secretos, hashing e inyección Write safer Python. Generate tokens with secrets, hash and verify passwords, sign data with hmac, avoid pickle risks, and stop SQL and command injection.
- Novedades de Python 3.13 A practical tour of Python 3.13 - the new interactive shell, experimental free-threaded mode and JIT, copy.replace, warnings.deprecated, TypeVar defaults, removed modules and what changed afterwards.
Data and the Web
- Redes: URLs, HTTP y sockets Learn how Python programs talk over the network. Parse and build URLs with urllib.parse, understand HTTP, call APIs with urllib and requests, and meet sockets.
- Bases de datos con sqlite3 Store and query data with Python's built-in sqlite3 module. Create tables, insert and select rows, use safe parameters, handle transactions and read rows by name.
- MySQL y PostgreSQL desde Python Connect Python to MySQL and PostgreSQL. Learn the DB-API, choose a driver, use the right placeholders, manage transactions and pool connections.
- ORM con SQLAlchemy Learn SQLAlchemy 2.0. Run Core queries, define ORM models with Mapped[], use sessions and relationships, avoid N+1 queries and migrate with Alembic.
- Bases de datos de documentos con MongoDB Use MongoDB from Python with PyMongo. Learn documents and collections, CRUD, query and update operators, indexes and the aggregation pipeline.
- Desarrollo web con Flask y Django Discover how Python builds websites and APIs. Learn what web frameworks do, how WSGI, routing and templates work, and compare Flask, Django and FastAPI.
- Plantillas con Jinja2 Learn Jinja2 in plain Python. Render variables, filters, loops, macros and template inheritance, escape user input safely, add custom filters and see how Flask uses it.
- Recursos con Flask-RESTful Build REST APIs with Flask-RESTful. Write Resource classes, route them with Api.add_resource, parse arguments with reqparse, shape output with marshal_with and test everything.
- Fundamentos de NumPy Learn NumPy from scratch. Create arrays, read shapes and dtypes, do vectorized math, slice and filter with masks, use broadcasting and compute aggregates.
- Fundamentos de pandas Learn pandas step by step. Build Series and DataFrames, read CSV data, select and filter rows, add columns, sort, group with groupby and handle missing values.
- Gráficos con Matplotlib Learn Matplotlib step by step. Draw line, bar, scatter, histogram and pie charts, add labels and legends, build subplots, apply styles and save figures.
- Gráficos estadísticos con Seaborn Learn Seaborn step by step. Draw histograms, box plots, scatter plots with hue, bar charts with error bars, heatmaps and pair plots from pandas DataFrames, then style them with themes.
- Aprendizaje automático con scikit-learn Learn machine learning in Python with scikit-learn. Split data, train classifiers and regressors, measure accuracy, build pipelines, cross-validate and spot overfitting.
- Gradient boosting con XGBoost y LightGBM Train, tune and compare XGBoost and LightGBM on a tabular dataset in Python. Learn n_estimators, learning_rate, early stopping, feature importance and a fair comparison with scikit-learn.
- Redes neuronales: TensorFlow y PyTorch de un vistazo Understand neural networks in Python. Build and train a tiny network with NumPy, see how PyTorch and Keras code looks, and learn when deep learning is the right tool.
- Correo electrónico con smtplib y email Send email from Python. Build messages with EmailMessage, add HTML and attachments, connect securely with smtplib and test with a local debug server.
- Web scraping con requests y BeautifulSoup Learn web scraping in Python. Fetch pages with requests, parse HTML with BeautifulSoup, select elements with CSS selectors, and scrape politely with robots.txt.
- Rastreo web con Scrapy Learn web crawling with Scrapy. Write spiders, extract data with CSS and XPath selectors, follow links and pagination, clean items in pipelines, and crawl politely.
- Procesamiento de imágenes con Pillow Learn image processing in Python with Pillow. Create and open images, resize and crop, convert to grayscale, apply filters, draw shapes and text, and save in other formats.
- Visión por computadora con OpenCV Learn OpenCV with Python. Create and inspect images as NumPy arrays, convert colors, resize, blur, threshold, detect edges and count shapes with contours, with runnable examples.
- Juegos con pygame Learn pygame basics in Python. Build the game loop, handle keyboard and quit events, draw shapes, use Rect and Sprite classes, detect collisions and keep logic testable.
- APIs REST con FastAPI Learn FastAPI step by step. Build typed routes, path and query parameters, Pydantic request bodies, validation errors, dependencies and async endpoints in Python.
- Autenticación en FastAPI: hash de contraseñas, JWT y OAuth2 Secure a FastAPI app. Hash passwords with bcrypt, issue and verify JWT access tokens, build the OAuth2 password flow, add role checks, and learn when CSRF matters.
- Tareas en segundo plano con Celery y RQ Learn task queues in Python. Understand brokers, workers and result backends, write Celery tasks with retries, chains and groups, schedule jobs with beat, and compare Celery with RQ.
- Automatización del navegador con Selenium y Playwright Control a real browser from Python with Selenium and Playwright. Learn locators, waits, forms and the page object pattern, and practice selectors and waiting live.
- Desplegar aplicaciones web de Python Learn how to take a Python web app live. Understand WSGI and ASGI, run Gunicorn or Uvicorn behind a proxy, read settings from the environment, package with Docker and pick a host.
- Procesamiento del lenguaje natural con NLTK y spaCy Learn natural language processing in Python. Tokenize and clean text, stem words, count n-grams, compare documents with TF-IDF, and meet spaCy pipelines and entities.
- Python para el Internet de las cosas (IoT) Use Python for Internet of Things projects - Raspberry Pi with GPIO Zero, Arduino with pyFirmata, ESP32 with MicroPython, and MQTT messaging, with runnable simulations.
- Python en la nube: AWS, Azure y sin servidor Use Python with cloud platforms - AWS boto3, the Azure SDK, serverless functions, retries, pagination and testing cloud code without credentials using runnable fakes.
- Python para ciberseguridad Learn how security professionals use Python - port scanning with sockets, packet crafting with Scapy, SSH automation with Paramiko, packet parsing and log analysis - with runnable examples.
Projects
- Proyecto: piedra, papel o tijera Build rock, paper, scissors in Python step by step. Practice input, random choices, a rules dictionary, input validation, score keeping and best-of-N matches.
- Proyecto: juego de adivinar el número Build a complete number guessing game in Python, step by step. Practice random numbers, loops, input validation, functions, difficulty levels and replay stats.
- Proyecto: tres en raya Build tic-tac-toe in Python step by step, from a list-based board and validated moves to win detection, a rule-based computer player and an unbeatable minimax AI.
- Proyecto: analizador de texto Build a text analyzer in Python step by step. Count words and sentences, find the most common words with Counter, estimate readability and print a clean report.
- Proyecto: sistema bancario Build a banking system in Python step by step. Use classes, inheritance, Decimal money, custom exceptions, transaction history and safe transfers, then test it with unittest.
- Proyecto: gestor de inventario Build an inventory manager in Python with data classes, custom exceptions, reports, JSON saving and a command-line interface driven by pattern matching.
- Proyecto: informe de datos Build a data report in Python from a CSV file. Clean messy rows, group and total the data, compute statistics, chart trends in text and save the finished report.
- Proyecto: análisis de sentimiento Build a sentiment classifier in Python. Clean text, count words, vectorize reviews with TF-IDF, train logistic regression with scikit-learn, evaluate it, find its mistakes and wrap it in a function.
- Proyecto: API JSON con Flask Build a JSON REST API with Flask step by step. Add CRUD routes, input validation, JSON error handlers, filtering and pagination, then test it with the Flask test client.
- Proyecto: aplicación web de tareas Build a to-do web app with Flask and SQLite. Render HTML templates, handle forms with POST and redirect, edit and delete tasks, escape user input, add CSRF protection and test it all.
- Automatización del escritorio: captura de pantalla, pyautogui y síntesis de voz Automate your desktop with Python. Take screenshots, record the screen to a GIF, control mouse and keyboard with pyautogui and speak text. Includes runnable stand-ins.
- Final project: Build a Command-Line Study Tracker Build a small command-line study tracker step by step in Python, with input checks, totals, JSON saving, simple tests and a Git history of your work.
Data Structures and Algorithms
- Pilas, colas, montículos y listas enlazadas Build classic data structures in Python. Use lists as stacks, deque as a queue, heapq for priority queues, and build a linked list and a binary search tree.
- Algoritmos de búsqueda y ordenación Learn classic Python algorithms, including linear and binary search, bisect, bubble, insertion, merge and quick sort, and measuring Big-O by timing your code.
- Bibliotecas extra de estructuras de datos: sortedcontainers, treelib, intervaltree, pygtrie Go beyond lists and dicts. Use sortedcontainers for always-sorted data, treelib for trees, intervaltree for ranges and pygtrie for prefix lookups, with runnable examples.
- Complejidad de las operaciones incorporadas Learn the Big O cost of Python's built-in operations on list, dict, set, deque, str and heapq, see why some are O(1) and others O(n), and pick the right type.
Practice and Review
- Hoja de referencia de Python A one-page Python cheat sheet with syntax, strings, lists, dicts, sets, loops, functions, classes, errors, files, f-string formats and the most-used built-ins.
- Ejercicios de práctica de Python 27 graded Python exercises with solutions on strings, loops, dictionaries, functions, files, classes, generators and algorithms. Run them in your browser.
- Programas clásicos de Python Work through the short Python programs every learner meets - maximum, interest, Armstrong numbers, primes and sieve, Fibonacci, list rotation and swapping, and date arithmetic.
- Preguntas de entrevista de Python 38 common Python interview questions with concise answers, from lists vs tuples and scope to generators, decorators, the GIL, memory and metaclasses.