Quiz de Python: Cierres y Bucles

Aprende sobre closures y enlace tardío en Python con el ejemplo make_counters: por qué a(), b(), c() devuelven 2 y cómo fijar 0, 1 y 2 usando argumentos por defecto o funciones auxiliares.

31 ago 2025 • 2 min read • Q2BSTUDIO Team

Inteligencia-Artificial-

Python Quiz — Closures y variables de bucle

Pregunta clave cual es la salida de este código y por qué

def make_counters(): counters = [] for i in range(3): def counter(): return i counters.append(counter) return counters a, b, c = make_counters() print(a(), b(), c())

Respuesta correcta 2 2 2

Por qué sucede Esto ocurre por el enlace tardío de Python en cierres o closures. La función interna counter no captura el valor de i, captura la referencia al nombre i del alcance exterior. El valor de i se resuelve cuando se llama a cada función, no cuando se define. Al terminar el bucle for, i vale 2, por lo que a(), b() y c() devuelven 2.

Cómo obtener 0 1 2 si lo necesitas Usa enlace temprano pasando el valor como argumento por defecto en el momento de la definición o usando una función auxiliar. Por ejemplo def counter(i=i): return i dentro del bucle, o bien una fábrica def make_counter(j): def counter(): return j return counter, y añadir make_counter(i) a la lista. En ambos casos cada closure fija su propio valor.

Por qué este ejercicio importa Comprender cierres, enlace tardío y variables de bucle evita errores sutiles al crear fábricas de funciones, decoradores, callbacks y generadores de comandos. Con esta base, patrones avanzados de diseño funcional se convierten en herramientas fiables en proyectos de software a medida y aplicaciones a medida.

Guía rápida para razonar el código 1 identifica dónde se define cada función y qué nombres externos utiliza 2 pregúntate cuándo se evalúa i si es al definir o al llamar 3 simula mentalmente el bucle y las llamadas posteriores 4 si dudas, imprime i dentro del bucle y al llamar para observar el momento de la resolución de nombres

Q2BSTUDIO es tu aliado tecnológico para llevar estas buenas prácticas de ingeniería a producción. Somos una empresa de desarrollo de software y aplicaciones a medida, especialistas en inteligencia artificial, ciberseguridad, servicios cloud aws y azure, servicios inteligencia de negocio y power bi, automatización de procesos, ia para empresas y agentes IA. Si buscas un equipo que convierta conceptos como closures, diseño de APIs, pruebas automatizadas y despliegues en valor real para tu negocio, descubre nuestro desarrollo de aplicaciones y software a medida y cómo aplicamos patrones fiables desde el código hasta la nube.

Además, si tu objetivo es acelerar la entrega con pipelines robustos y tareas repetitivas sin errores humanos, podemos ayudarte con automatización de procesos, integrando tus sistemas con buenas prácticas de ingeniería, observabilidad y seguridad. Potenciamos tus soluciones con analítica avanzada, power bi y estrategias de ciberseguridad alineadas a normativas, sobre infraestructuras cloud escalables en aws y azure.

Conclusión Recuerda que en Python las closures capturan nombres y se evalúan al llamar. Si necesitas capturar el valor en cada iteración, fija el valor con argumentos por defecto o funciones auxiliares. Dominar estos detalles técnicos es clave para construir software a medida robusto, ampliar capacidades con inteligencia artificial e industrializar tus soluciones con seguridad y escalabilidad.

A BREAK?

Play for a moment before you go

OUR SERVICES

How we can help you

Artificial intelligence

AI agents, chatbots, and intelligent assistants that automate tasks and serve your customers 24/7 to improve the efficiency of your business.

More info

Software Development

Web, mobile, and desktop applications, intranets, e-commerce, SaaS, and management platforms designed for your company's specific needs.

More info

Cloud services

Migration, infrastructure, managed hosting, high availability, and security on Microsoft Azure and Amazon Web Services to help your business scale without limits.

More info

Cybersecurity and pentesting

Security audits, penetration testing and protection of applications, data and infrastructure on-premise and cloud, with ethical hacking and regulatory compliance.

More info

Business Intelligence

Dashboards and data analysis with Power BI: we integrate your sources, design dashboards and KPIs and turn your data into decisions.

More info

Process automation

We automate repetitive tasks and connect your applications with n8n, Power Automate, Make, and RPA, eliminating manual work and increasing productivity.

More info

Training for Companies

We train your teams in technology with criteria: web development, databases, Git, best practices and security, automation with n8n, artificial intelligence for companies and creation of AI solutions with Azure AI Foundry.

More info

Code Auditing

We audit the code that you, your team or an AI create: we tell you what is good and what to improve, we secure it and make it ready for production, web or app.

More info

AI Image Generation

We create for you the images that your business needs with artificial intelligence: product, networks, advertising, illustration and avatars. You tell us what you want and we deliver it ready to use.

More info

AI Video Generation

We create videos with artificial intelligence for you: promotional, networking, virtual presenters, dubbing and animations. You tell us the idea and we will deliver it assembled and ready to publish.

More info

AI Conversational Avatars

We create conversational avatars with AI – digital humans with a face and voice – that serve your customers and teams with the knowledge of your company, on your website, interactive monitors, WhatsApp or Teams.

More info

Online Marketing and AI

Google Ads, Meta Ads, LinkedIn Ads and AI Engine Positioning (GEO/AEO): we attract customers and make your brand appear where they search for you, also on ChatGPT, Gemini and Perplexity.

More info

Do you have a project in mind?

Tell us your vision and we'll turn it into a software solution. Whatever the scope, we make your idea real.

Live Chat