<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Balbir Yadav on Medium]]></title>
        <description><![CDATA[Stories by Balbir Yadav on Medium]]></description>
        <link>https://medium.com/@balbirms?source=rss-3e44dfe8d9a6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*W4mehJ9AF35VanMIvMTSeg.jpeg</url>
            <title>Stories by Balbir Yadav on Medium</title>
            <link>https://medium.com/@balbirms?source=rss-3e44dfe8d9a6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 20:37:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@balbirms/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to Crack System Design (HLD) Interviews — A Complete Guide for Software Engineers]]></title>
            <link>https://medium.com/@balbirms/how-to-crack-system-design-hld-interviews-a-complete-guide-for-software-engineers-db20c837f32e?source=rss-3e44dfe8d9a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/db20c837f32e</guid>
            <category><![CDATA[high-level-design]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <dc:creator><![CDATA[Balbir Yadav]]></dc:creator>
            <pubDate>Sun, 29 Mar 2026 16:08:20 GMT</pubDate>
            <atom:updated>2026-03-29T16:09:01.634Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A practical, no-fluff guide to walking into your next system design interview with confidence.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ULMD2uIjAZMdv49OmzX33Q.png" /></figure><h3>Why Most Engineers Fail HLD Interviews</h3><p>Here’s the uncomfortable truth: most engineers who fail system design interviews don’t fail because they don’t know enough. They fail because they don’t know <strong>how to think out loud</strong> about systems.</p><p>HLD (High-Level Design) interviews are not knowledge tests. They’re <strong>thinking tests</strong>. The interviewer isn’t checking if you’ve memorized every component of a Kafka cluster. They’re watching how you approach an ambiguous problem, how you communicate trade-offs, and whether you can make reasonable decisions under uncertainty.</p><p>This guide will give you a repeatable framework, the core building blocks you need to know, and walkthroughs of the most commonly asked systems — so you walk in structured, confident, and ready.</p><h3>Part 1: The 5-Step Framework (Use This on Every Question)</h3><p>The biggest mistake engineers make in HLD interviews is jumping straight to drawing boxes. The interviewer asks “design Twitter” and you immediately start talking about databases. Stop. Breathe. Follow this structure every single time.</p><h3>Step 1 — Clarify Requirements (3–5 minutes)</h3><p>Before drawing a single box, ask questions. This signals maturity. Interviewers love it.</p><p><strong>Ask about functional requirements:</strong></p><ul><li>What are the core features we need to support?</li><li>What are we explicitly NOT building? (scope matters)</li><li>Who are the users — consumers, businesses, internal teams?</li></ul><p><strong>Ask about non-functional requirements:</strong></p><ul><li>How available does the system need to be? (99.9% vs 99.999%)</li><li>How consistent? Can we tolerate eventual consistency?</li><li>What’s the expected latency for reads? Writes?</li></ul><p><strong>A real example:</strong> If asked to design a URL shortener, clarify:</p><ul><li>Do we need custom aliases?</li><li>Do URLs expire?</li><li>Do we need analytics (click counts, geo data)?</li></ul><p>This takes 3–5 minutes and sets the entire direction of your design. Never skip it.</p><h3>Step 2 — Estimate Scale (3–5 minutes)</h3><p>Back-of-envelope math tells you what kind of system you’re building. A system handling 100 QPS is architecturally very different from one handling 100,000 QPS.</p><p><strong>The four numbers to estimate:</strong></p><ol><li><strong>DAU (Daily Active Users)</strong> — how many users are using the system daily?</li><li><strong>QPS (Queries Per Second)</strong> — DAU × actions per day ÷ 86,400 seconds</li><li><strong>Storage</strong> — how much data is written per day, per year?</li><li><strong>Bandwidth</strong> — how much data flows in and out per second?</li></ol><p><strong>Example for a URL shortener:</strong></p><ul><li>100M URLs created per day</li><li>10:1 read-write ratio → 1B redirects/day</li><li>1B ÷ 86,400 ≈ <strong>11,500 QPS reads</strong></li><li>100M × 500 bytes ≈ <strong>50 GB storage per day</strong></li></ul><p>This tells you immediately: reads dominate, so you’ll need aggressive caching. You’ve already made your first architectural decision — from math, not intuition.</p><h3>Step 3 — Define API &amp; Data Model (5–7 minutes)</h3><p>Before drawing the architecture, define what data flows through the system and how users interact with it.</p><p><strong>API design:</strong></p><ul><li>Keep it simple — 2 to 4 core endpoints</li><li>Use REST conventions (GET for reads, POST for creates)</li><li>Mention what each endpoint returns</li></ul><p><strong>Data model:</strong></p><ul><li>What are the core entities?</li><li>What database type — SQL or NoSQL, and why?</li><li>What are the access patterns? (This drives your schema)</li></ul><p><strong>SQL vs NoSQL — the decision framework:</strong></p><p>Use <strong>SQL</strong> when: you need ACID transactions, data is relational, schema is stable (e.g., banking, orders)</p><p>Use <strong>NoSQL</strong> when: you need massive scale, flexible schema, high write throughput, or your access pattern is key-value or document-based (e.g., user profiles, messages, URL mappings)</p><h3>Step 4 — Draw the High-Level Design (10–15 minutes)</h3><p>Now you draw. Start simple — a client, a server, a database. Then layer in complexity as needed.</p><p><strong>The core components to know:</strong></p><ul><li><strong>Load balancer</strong> — distributes traffic across servers, prevents any single server from being overwhelmed</li><li><strong>API gateway</strong> — handles authentication, rate limiting, and routing at the edge</li><li><strong>Application servers</strong> — your stateless business logic layer (stateless = easy to scale horizontally)</li><li><strong>Cache (Redis)</strong> — fast in-memory reads, dramatically reduces database load</li><li><strong>Database</strong> — persistent storage, SQL or NoSQL depending on your data model</li><li><strong>Message queue (Kafka/SQS)</strong> — async processing, decouples services, handles traffic spikes</li><li><strong>Object storage (S3)</strong> — store blobs — images, videos, files</li><li><strong>CDN</strong> — serve static content from servers close to the user</li></ul><p><strong>The golden rule when drawing:</strong> Data flow must be clear. A good diagram shows not just what components exist, but how data moves between them.</p><h3>Step 5 — Deep Dive &amp; Trade-offs (10–15 minutes)</h3><p>This is where SDE-2 and SDE-3 candidates separate themselves. The interviewer will pick one component and go deep. Be ready.</p><p>Common deep-dives:</p><ul><li>How does your cache handle failures?</li><li>What happens when your database can’t keep up with write load?</li><li>How do you handle duplicate messages in your queue?</li><li>What’s your strategy for database sharding?</li></ul><p>For every decision you make, state the trade-off. Not just “I’ll use Redis” but “I’ll use Redis because reads heavily outnumber writes and this data fits in memory — the trade-off is that Redis is not durable by default, so for critical data I’d configure AOF persistence or back it with a database.”</p><p>Trade-off language = senior engineer language.</p><h3>Part 2: Core Building Blocks (Know These Cold)</h3><p>These are the components that appear in almost every system design problem. Understand not just what they are, but <strong>when and why</strong> to use them.</p><h3>Load Balancer</h3><p>Distributes incoming traffic across multiple servers. Prevents single points of failure. Algorithms: round-robin (simple, works well for stateless servers), least connections (better for variable request durations), consistent hashing (use when you need sticky sessions or for cache routing).</p><h3>CDN (Content Delivery Network)</h3><p>Serves static assets — images, JS, CSS, videos — from servers geographically close to the user. Reduces latency dramatically for global users. Reduces load on your origin servers. Always use a CDN when your system serves media or has global users.</p><h3>Cache (Redis / Memcached)</h3><p>Stores frequently accessed data in memory. Reads from cache are 10–100x faster than database reads. Key concepts: <strong>cache-aside</strong> (app checks cache first, falls back to DB on miss), <strong>write-through</strong> (write to cache and DB together), <strong>write-back</strong> (write to cache, async flush to DB). Eviction policy: LRU (Least Recently Used) is the most common.</p><h3>Message Queue (Kafka / SQS / RabbitMQ)</h3><p>Enables asynchronous communication between services. Use when: a task is slow and doesn’t need an immediate response (e.g., sending an email, processing an image), you want to decouple producers from consumers, or you need to absorb traffic spikes without dropping requests. Key concept: at-least-once delivery means you must handle duplicates with idempotency keys.</p><h3>Database Scaling Patterns</h3><p><strong>Read replicas</strong> — one primary handles writes, multiple replicas handle reads. Good when reads vastly outnumber writes.</p><p><strong>Sharding</strong> — split data across multiple database nodes by a shard key (e.g., user_id). Enables massive horizontal scale but adds complexity — cross-shard queries are expensive and resharding is painful. Choose your shard key carefully.</p><p><strong>Denormalization</strong> — store redundant data to avoid expensive joins. Common in NoSQL systems and high-scale reads.</p><h3>Part 3: Three Systems You Must Know</h3><h3>System 1 — URL Shortener</h3><p><strong>The problem:</strong> Given a long URL, return a short URL. Redirect short URLs to the original.</p><p><strong>Scale:</strong> ~100M URLs created/day, ~1B redirects/day (11,500 QPS reads)</p><p><strong>Key design decisions:</strong></p><p><em>Short code generation:</em> Use Base62 encoding on an auto-incremented ID. 6 characters of Base62 gives you 6²⁶ ≈ 56 billion unique URLs. Simple, fast, no collision risk.</p><p><em>Architecture:</em> Client → Load Balancer → App Servers → Cache (Redis) → Database (NoSQL). On write: generate short code, store mapping in DB. On read: check cache first, fall back to DB on miss, redirect.</p><p><em>301 vs 302 redirect:</em> 301 is permanent — browsers cache it, so subsequent requests never hit your server. Great for reducing load. 302 is temporary — every request hits your server. Use 302 if you need analytics.</p><p><em>Cache strategy:</em> Cache-aside. 80% of redirects go to 20% of URLs (power law distribution), so your cache hit rate will be very high. LRU eviction.</p><h3>System 2 — Instagram / Social Media Feed</h3><p><strong>The problem:</strong> Users post photos. Users see a feed of posts from accounts they follow.</p><p><strong>Scale:</strong> 500M DAU, ~50M posts/day, feed reads are much more frequent than writes</p><p><strong>Key design decisions:</strong></p><p><em>The fan-out problem:</em> When a user posts, how do their followers see it?</p><p><strong>Fan-out on write (push model):</strong> When Alice posts, immediately write to all her followers’ feed caches. Reads are instant — the feed is pre-built. Problem: if Alice has 10M followers, one post triggers 10M writes. This is the celebrity problem.</p><p><strong>Fan-out on read (pull model):</strong> Don’t pre-build feeds. When Bob opens the app, pull posts from all accounts he follows and merge them. No write amplification, but every read is expensive.</p><p><strong>Hybrid approach (what Instagram actually does):</strong> Fan-out on write for regular users. Fan-out on read for celebrities (users with millions of followers). This is the right answer — mention it and you’ll impress.</p><p><em>Image storage:</em> Store images in object storage (S3). Never in a database. Serve via CDN.</p><p><em>Feed cache:</em> Redis sorted set, where score is the post timestamp. Pre-built per user for non-celebrity accounts.</p><h3>System 3 — WhatsApp / Chat System</h3><p><strong>The problem:</strong> Users send messages to each other in real time. Messages must be delivered even if the recipient is offline.</p><p><strong>Scale:</strong> 100B messages/day, billions of users</p><p><strong>Key design decisions:</strong></p><p><em>Why WebSockets, not HTTP:</em> HTTP is request-response — the server can’t push messages to the client without the client asking first. WebSockets maintain a persistent bidirectional connection. The server can push messages to the client the moment they arrive. Essential for real-time chat.</p><p><em>Multi-server routing:</em> Alice and Bob are likely connected to different chat servers. When Alice sends a message, her server publishes it to a message queue (Kafka). Bob’s server subscribes to Bob’s topic and pushes it to Bob over his WebSocket connection.</p><p><em>Offline delivery:</em> If Bob is offline, store the message in the database. When Bob reconnects, his server fetches all undelivered messages. Additionally, send a push notification (APNs for iOS, FCM for Android) to wake up Bob’s app.</p><p><em>Database choice:</em> Cassandra. Messages are append-only writes. You query by (chat_id, timestamp) — perfect for Cassandra’s partition key + clustering key model. Scales horizontally with ease.</p><p><em>Message delivery states:</em> Sent (stored on server) → Delivered (received by Bob’s device) → Read (Bob opened it). Each state change requires an acknowledgement (ACK) back to the server.</p><h3>Part 4: Trade-offs That Impress Interviewers</h3><p>Knowing components is table stakes. Knowing when NOT to use them is what separates good candidates.</p><h3>CAP Theorem — Know It, Use It</h3><p>In a distributed system, you can only guarantee two of three: <strong>Consistency</strong> (every read gets the latest write), <strong>Availability</strong>(every request gets a response), <strong>Partition tolerance</strong> (system works despite network failures).</p><p>Since network partitions are unavoidable in real distributed systems, you’re always choosing between consistency and availability. Mention this explicitly: “Given that we need high availability and can tolerate eventual consistency, I’d choose an AP system like Cassandra over a CP system like HBase.”</p><h3>SQL vs NoSQL — Don’t Just Pick NoSQL</h3><p>A very common mistake is defaulting to NoSQL because it “scales better.” SQL databases scale very well with read replicas and proper indexing. Choose based on access patterns, not hype.</p><p>Use SQL for: financial transactions, relational data, complex queries, strong consistency requirements.</p><p>Use NoSQL for: massive write throughput, flexible schema, simple key-value or document access patterns, horizontal scale requirements.</p><h3>Synchronous vs Asynchronous</h3><p>Not every operation needs an immediate response. Email sending, image processing, notification delivery, analytics event logging — all of these can be async. Moving them to a queue improves your system’s responsiveness and resilience. When a third-party API is down, your queue buffers the work instead of failing the user’s request.</p><h3>Caching trade-offs</h3><p>Cache improves read performance dramatically but introduces consistency challenges. When the database is updated, the cache can serve stale data. Solutions: TTL (cache expires after N seconds), cache invalidation (delete the cache entry on DB write), write-through (update cache and DB together). Know these by name and explain the trade-off for each.</p><h3>Part 5: What Interviewers Actually Look For</h3><p>After all the technical content, here’s what’s actually being evaluated:</p><p><strong>Structured thinking.</strong> Do you have a systematic approach or do you jump around randomly? Following the 5-step framework signals that you can handle ambiguity in a structured way.</p><p><strong>Communication.</strong> Can you explain complex ideas clearly? Use analogies. Avoid jargon when a plain word works. Think out loud — interviewers can’t evaluate silent thinking.</p><p><strong>Trade-off awareness.</strong> Every decision has a cost. Senior engineers don’t just pick the “best” tool — they pick the right tool for the constraint and explain what they’re giving up.</p><p><strong>Driving the conversation.</strong> Don’t wait to be led. Propose, explain, and ask for feedback. “I’m thinking of using Redis here for caching — does that make sense to explore further, or would you like me to move on to the database layer?”</p><p><strong>Knowing what you don’t know.</strong> It’s fine to say “I’m not deeply familiar with Cassandra’s internals but I know it’s optimized for time-series append-heavy workloads which fits our use case.” Intellectual honesty beats fake confidence.</p><h3>Part 6: Your Interview Day Checklist</h3><p>Print this, stick it in your head.</p><p><strong>Before you start:</strong></p><ul><li>[ ] Ask clarifying questions before drawing anything</li><li>[ ] State your assumptions out loud</li><li>[ ] Confirm scope — what’s in and what’s out</li></ul><p><strong>While designing:</strong></p><ul><li>[ ] Start simple, then add complexity</li><li>[ ] Label every component and every arrow</li><li>[ ] Explain each component as you add it</li><li>[ ] Justify every technology choice</li><li>[ ] State trade-offs unprompted</li></ul><p><strong>On deep dives:</strong></p><ul><li>[ ] Know your failure scenarios (what breaks if X goes down?)</li><li>[ ] Know your bottlenecks (where does the system struggle under load?)</li><li>[ ] Know your scaling strategy (how do you 10x this system?)</li></ul><p><strong>Things to avoid:</strong></p><ul><li>[ ] Don’t over-engineer — YAGNI (You Aren’t Gonna Need It)</li><li>[ ] Don’t under-engineer — a single server with no replication won’t cut it</li><li>[ ] Don’t use a technology just because it’s trendy</li><li>[ ] Don’t go silent for more than 30 seconds</li></ul><h3>Final Thoughts</h3><p>System design interviews feel overwhelming because the problem space is infinite. But every system — no matter how complex — is built from the same ~10 components, following the same trade-off principles, using the same 5-step thinking process.</p><p>You don’t need to have designed Google’s infrastructure to pass these interviews. You need to show that you can think through problems systematically, communicate your reasoning clearly, and make reasonable decisions given real-world constraints.</p><p>Practice the framework on one new system every day. After a week, you’ll start seeing the same patterns everywhere. After two weeks, the interview will feel like a conversation, not an exam.</p><p>Good luck. You’ve got this.</p><p><em>If this helped you, share it with someone who has a system design interview coming up. And if you have questions or want to discuss any of the concepts above, drop a comment — happy to help.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db20c837f32e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is MCP? why everyone is talking about it.]]></title>
            <link>https://medium.com/@balbirms/what-is-mcp-why-everyone-is-talking-about-it-b022b22a9e13?source=rss-3e44dfe8d9a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/b022b22a9e13</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[mcp-protocol]]></category>
            <category><![CDATA[model-context-protocol]]></category>
            <category><![CDATA[mcp-server]]></category>
            <dc:creator><![CDATA[Balbir Yadav]]></dc:creator>
            <pubDate>Mon, 26 Jan 2026 19:42:08 GMT</pubDate>
            <atom:updated>2026-01-26T19:42:08.092Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hE9Xx7mNCa-ximJcDeDxOg.png" /></figure><p>MCP is becoming a necessity for AI experiences — and that’s why everyone is talking about it.</p><p>AI agents look smart on the surface.<br>But if you’ve built or deployed one, you already know the cracks underneath.</p><p>Let’s talk about why AI agents struggle today and why Model Context Protocol (MCP) exists in the first place 👇</p><p>The hidden limitations of AI agents without MCP</p><p>Even powerful LLMs face serious structural issues:</p><p>🔹 Inconsistent tool usage<br>Every tool integration is custom. No standards. Results? Fragile, unpredictable behavior — like using random chargers for the same device.</p><p>🔹 Limited control &amp; observability<br>Once a task is handed to the agent, it’s hard to understand how or why it made decisions. Steering mid-execution is painful.</p><p>🔹 No composability<br>You can’t easily build complex workflows from smaller, reusable parts. Everything becomes tightly coupled and hard to evolve.</p><p>🔹 Limited context awareness<br>Most agents don’t truly understand:</p><ul><li>real-time system state</li><li>user history</li><li>business context<br>So answers are often technically right but practically wrong.</li></ul><p>🔹 Brittle integrations<br>A small API or schema change can break the entire agent flow.</p><p>🔹 Security risks<br>Without standardized guardrails, giving agents access to sensitive systems is risky.</p><p>🔹 Poor reusability<br>Each new agent feels like starting from scratch.</p><p>🔹 Static knowledge<br>Agents don’t naturally stay in sync with changing tools or data.</p><p><strong>This is exactly why Model Context Protocol (MCP) came into the picture</strong></p><p><strong>MCP</strong> is not another AI model.<br>It’s a protocol — a structured way to give AI agents reliable, real-time context.</p><p>Think of MCP as a rulebook that tells an AI agent:</p><ul><li>What problem it is solving</li><li>What tools and data are available</li><li>Who it’s interacting with</li><li>What the current system state is</li></ul><p>Until now, LLMs like GPT, Claude, or Gemini mostly operated in isolation. Great at language — poor at understanding their environment.</p><p>MCP bridges that gap.</p><p><strong>How MCP actually helps</strong></p><p>A simple mental model 👇</p><p><strong>MCP is the USB-C port between LLMs and tools.</strong></p><p><strong>On one side:</strong></p><ul><li>LLMs (GPT, Claude, Gemini)</li></ul><p><strong>On the other side:</strong></p><ul><li>Databases</li><li>APIs</li><li>Code editors</li><li>Internal systems</li></ul><p>Instead of building a custom connector for every tool, MCP provides a standard, reusable, and secure interface.</p><p>This means:<br>✅ More reliable tool usage<br>✅ Better control and transparency<br>✅ Composable agent workflows<br>✅ Safer integrations<br>✅ Less hallucination, more grounded actions</p><p><strong>Why MCP matters now</strong></p><p>As AI moves from chatbots → agents → autonomous systems, context becomes non-negotiable.</p><p>Without MCP: Agents are clever but fragile<br>With MCP: Agents become reliable, extensible, and production-ready</p><p>That’s why MCP isn’t a “nice to have” anymore.<br><strong><em>It’s becoming infrastructure.</em></strong></p><p>If you’re building AI agents today — or planning to — <strong>understanding MCP is no longer optional.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b022b22a9e13" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Visualization using Python Matplotlib Part-1 (Hands-On Tutorial)]]></title>
            <link>https://medium.com/@balbirms/data-visualization-using-python-matplotlib-part-1-hands-on-tutorial-ae2e0deda929?source=rss-3e44dfe8d9a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae2e0deda929</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[matplotlib-tutorial]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[matplotlib]]></category>
            <dc:creator><![CDATA[Balbir Yadav]]></dc:creator>
            <pubDate>Sun, 16 Mar 2025 11:15:27 GMT</pubDate>
            <atom:updated>2025-03-16T11:15:27.783Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l5--ZFfu0RYWeF57ROoKcA.png" /><figcaption>Figure 1</figcaption></figure><p>Imagine you’ve just launched a <strong>food delivery startup</strong>. In the first few months, you’re collecting data on things like:</p><ul><li><strong>Daily Orders</strong></li><li><strong>Top-Selling Dishes</strong></li><li><strong>Customer Ratings</strong></li><li><strong>Delivery Times</strong></li></ul><p>But looking at just numbers every day isn’t helping you spot trends. Are orders increasing over time? Which dish is the crowd favorite? How fast are deliveries on average?</p><p>This is where <strong>Matplotlib</strong> comes in. It lets you turn all that raw data into <strong>clear, insightful charts</strong> — like a <strong>line plot</strong> to track daily orders, a <strong>bar chart</strong> for top-selling dishes, or even a <strong>pie chart</strong> to show customer feedback percentages.</p><p>In this blog, I’ll show you how to use Matplotlib step-by-step — no prior experience needed. By the end, you’ll be able to create data visualizations in just <strong>1.5 hours</strong>! Let’s dive in.</p><h3>What is Matplotlib?</h3><p>Matplotlib is a popular <strong>Python library</strong> used for creating static, interactive, and animated visualizations.</p><h4>Key Features of Matplotlib</h4><ul><li>Easy to create line plots, bar charts, scatter plots, histograms, and more.</li><li>Supports customization of plots (labels, titles, legends, styles, etc.).</li><li>Works seamlessly with NumPy, Pandas, and other libraries.</li><li>Offers a variety of backends for rendering plots in different environments.</li></ul><h4>Applications of Matplotlib</h4><p>Let’s look at the common application of Matplotlib</p><ol><li><strong>Data Visualization: </strong>Representing data trends and patterns in an easy-to-understand format. It is also used in creating line graphs, bar charts, and scatter plots for data analysis.</li><li><strong>Scientific and Research Graphs: </strong>Plotting complex mathematical functions &amp; Analyzing experimental data in scientific research.</li><li><strong>Machine Learning: </strong>Visualizing training and testing results (e.g., loss, accuracy graphs) and Plotting decision boundaries and feature distributions.</li><li><strong>Finance and Economics: </strong>Generating stock market trends and financial reports. Visualizing economic indicators and forecasts.</li><li><strong>Education and Tutorials: </strong>Creating teaching aids and materials with graphical illustrations.</li></ol><h3>Matplotlib Hands-On</h3><p>Here’s the Google Colab notebook — open it to follow along!</p><p><a href="https://colab.research.google.com/drive/1fGzqhM3FH1xsqCwfYQ-vhAw3O2TC4Idb?usp=sharing">Google Colab</a></p><pre># Installing matplotlib<br>!pip install matplotlib<br><br># To use Matplotlib in python, We need to Import it.<br>import matplotlib.pyplot as plt</pre><p>Now we will make will make a sample plot. Here we have three points and we will be connecting them together by line</p><pre># Simple example plot<br><br>x = [1, 2, 3]<br>y = [3, 4, 2]<br><br># three point (x, y)==&gt; (1, 3), (2, 4), (3,2)<br><br>plt.plot(x, y)<br># plt.plot(x, y)<br><br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*r9KN3hRDB1XIFSRzSLTklQ.png" /><figcaption>Figure 2</figcaption></figure><p>Here x is horizontal axis and y is vertical axis</p><h4>Understanding the plot() Function in Matplotlib</h4><ol><li><strong>Purpose of </strong><strong>plot():</strong>The plot() function is used to draw points (markers) in a diagram.</li><li><strong>Default Behavior: </strong>By default, the plot() function connects the points with a line.</li><li><strong>Parameters: </strong>The function takes two main parameters: <strong>Parameter 1</strong>: An array containing the points on the X-axis and <strong>Parameter 2</strong>: An array containing the points on the Y-axis.</li></ol><pre># Example: Line passing through multiple points<br><br>xpoints = [1, 4, 6, 8]<br>ypoints = [3, 5, 1, 10]<br><br>plt.plot(xpoints, ypoints)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*RzUQnFtG4jYheHEsp6KpHQ.png" /><figcaption>Figure 3</figcaption></figure><p>If the x points are not passed to the plot() function, it uses default values. The default x values are [0, 1, 2, ..., n-1], where <strong>n</strong> is the number of y values.</p><pre># Example: Default values of x 0, 1, 2, 3<br><br>ypoints = [3, 5, 1, 10, 4, 15, 4,10]<br><br>plt.plot(ypoints)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*UAhpX0RdTPnapMrPjvW-ig.png" /><figcaption>Figure 4</figcaption></figure><h4>Markers</h4><p>You can use the marker keyword argument in Matplotlib&#39;s plot() function to highlight each point with a specified marker.</p><pre># Example plot with &#39;x&#39; marker<br><br>xpoints = [1, 4, 6, 8]<br>ypoints = [3, 5, 1, 10]<br><br>plt.plot(xpoints, ypoints, marker=&#39;x&#39;)<br>plt.show()<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*9NrHxkA0z6G6n5CMrhBTPg.png" /><figcaption>Figure 5</figcaption></figure><pre># Example plot with &#39;o&#39; marker<br><br>xpoints = [1, 4, 6, 8]<br>ypoints = [3, 5, 1, 10]<br><br>plt.plot(xpoints, ypoints, marker=&#39;o&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/1*2YaB1wRhKIHCpAIXsINotA.png" /><figcaption>Figure 6</figcaption></figure><p>Similarly, Matplotlib offers many other markers. Here’s a list of all the available markers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/278/1*HMZVl0K8Suv0ssgvaeHjPg.png" /><figcaption>Figure 7</figcaption></figure><h4>Marker Size</h4><p>You can use the keyword argument “<strong>markersize”</strong> or the shorter version, “<strong>ms”</strong> to set the size of the markers</p><p>Let’s look at an example where we set ms=10 and then ms=20 to understand the significance of <strong>ms </strong>or <strong>markersize</strong>.</p><pre># Example plot with &#39;X&#39; marker<br><br>xpoints = [1, 4, 6, 8]<br>ypoints = [3, 5, 1, 10]<br><br>plt.plot(xpoints, ypoints, marker=&#39;X&#39;, ms=&#39;10&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*xafy_TXJYU0MeGBXwq570Q.png" /><figcaption>Figure 8</figcaption></figure><pre># Example plot with &#39;X&#39; marker<br><br>xpoints = [1, 4, 6, 8]<br>ypoints = [3, 5, 1, 10]<br><br>plt.plot(xpoints, ypoints, marker=&#39;X&#39;, ms=&#39;20&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*sx5hCI6ISNoTpCoP94NB7w.png" /><figcaption>Figure 9</figcaption></figure><h4>Linestyle</h4><p><strong>linestyle</strong>, or shorter <strong>ls</strong>, to change the style of the plotted line</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*diVHbNOxJbRWLmKv_G9xkg.png" /><figcaption>Figure 10</figcaption></figure><p>Now, let’s look at an example of a dashed line with the marker ‘X’.</p><pre># Example plot with &#39;X&#39; marker and &#39;dashed&#39; linestyle<br><br>xpoints = [1, 4, 6, 8]<br>ypoints = [3, 5, 1, 10]<br><br>plt.plot(xpoints, ypoints, marker=&#39;X&#39;, ms=&#39;10&#39;, ls=&#39;--&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*J742AGOFmEtzOpX-8UflqQ.png" /><figcaption>Figure 11</figcaption></figure><h4>Line Color</h4><p>You can use the keyword argument <strong>color</strong> or the shorter <strong>c</strong> to set the color of the line.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/487/1*zzpkOosokjLIs4oT9zgntw.png" /><figcaption>Figure 12</figcaption></figure><p>The colors listed above are just a few examples, and there are many more options available. You can also specify colors using their hex codes in the color argument. Let’s go through an example to see how it works.</p><pre># Example plot with &#39;X&#39; marker, &#39;dotted&#39; linestyle, color pink<br><br>xpoints = [1, 4, 6, 8]<br>ypoints = [3, 5, 1, 10]<br><br>plt.plot(xpoints, ypoints, marker=&#39;X&#39;, ls=&#39;dotted&#39;, c=&#39;pink&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*KKbJ1j6-4PPimk0Zmyx6bA.png" /><figcaption>Figure 13</figcaption></figure><h4>Line Width</h4><p>You can use the keyword argument <strong>linewidth</strong> or the shorter <strong>lw</strong> to change the width of the line.</p><p>The value is a <strong>floating number</strong>, in points. Let’s see an example.</p><pre># Example plot with &#39;X&#39; marker, &#39;solid&#39; linestyle, color red, line width 5<br><br>xpoints = [1, 4, 6, 8]<br>ypoints = [3, 5, 1, 10]<br><br>plt.plot(xpoints, ypoints, marker=&#39;X&#39;, ls=&#39;solid&#39;, color=&#39;r&#39;, linewidth=&quot;5&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/659/1*kAe2AJcExKVJ2LAbRiQwkQ.png" /><figcaption>Figure 14</figcaption></figure><h3>End of Part 1</h3><p>So that’s it about part 1 of this series! 🎉</p><p>So far, we’ve covered the basics of Matplotlib, including the installation process and how to get started by creating simple plots. We’ve also explored how to customize plots using various arguments of the plot function, such as markers, markersize, linestyle, line color, and linewidth.</p><p>In the next part of this series we will be doing more exciting things, where we will see plot labelling, subplots, scatterplots etc.</p><p><strong>Feel free to add your thoughts in the comment section, and follow for more such blogs.</strong> 🚀</p><ul><li>Supports customization of plots (labels, titles, legends, styles, etc.).</li><li>Works seamlessly with NumPy, Pandas, and other libraries.</li><li>Offers a variety of backends for rendering plots in different environments.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae2e0deda929" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Built a Coding Practice Platform Like HackerRank & LeetCode (2025)]]></title>
            <link>https://medium.com/@balbirms/how-i-built-a-coding-practice-platform-like-hackerrank-leetcode-2025-6aba0414be97?source=rss-3e44dfe8d9a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/6aba0414be97</guid>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[online-judge]]></category>
            <category><![CDATA[online-coding-platform]]></category>
            <category><![CDATA[full-stack-developer]]></category>
            <category><![CDATA[coding-projects]]></category>
            <dc:creator><![CDATA[Balbir Yadav]]></dc:creator>
            <pubDate>Sat, 15 Mar 2025 10:21:35 GMT</pubDate>
            <atom:updated>2025-03-15T10:21:35.632Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*21jm7kLb2OCkB2FyJdHquA.png" /><figcaption>Figure 1: UI Screenshot</figcaption></figure><p>Ever wanted to build your own coding practice platform, like <strong>HackerRank</strong> or <strong>LeetCode</strong>? In this blog, I’ll walk you through how I built a platform where users can solve coding problems, run their code, and get real-time feedback. Let’s dive in! 💻</p><h3>Judge0: The Code Execution Engine</h3><p>We are using <a href="https://judge0.com/"><strong>Judge0</strong></a> for code execution. It’s a robust, scalable, and open-source online code execution system that supports multiple programming languages.</p><p>Why Judge0?<br> ✅ Supports 50+ programming languages.<br> ✅ Handles time limits and memory limits for each code submission.<br> ✅ Provides a simple API to send code and get results.</p><p>Checkout the judge0 API documentation here <a href="https://ce.judge0.com/">https://ce.judge0.com/</a></p><h3>Features of the Platform</h3><ol><li><strong>Admin Dashboard:</strong> Add and manage coding problems.</li><li><strong>Problem List Page:</strong> Display all coding problems with a “Solve Now” button.</li><li><strong>Problem Page:</strong> Interactive code editor and problem description.</li><li><strong>Code Execution:</strong> Use <strong>Judge0</strong> to run user code and check results.</li><li><strong>Real-time Feedback:</strong> Show live test case results as the code runs.</li><li><strong>Submission History:</strong> Store past submissions for each user.</li></ol><h3>Architecture Overview</h3><p>Here’s a high-level view of how everything works:</p><ol><li><strong>Admin adds problems</strong> → Problems stored in the database.</li><li><strong>User selects a problem</strong> → Opens a page with a code editor and problem description.</li><li><strong>User submits code</strong> → Backend sends the code to <strong>Judge0</strong>.</li><li><strong>Judge0 executes the code</strong> → Returns results for each test case.</li><li><strong>Show results to the user</strong> → Store the submission for future reference.</li></ol><h3>Step 1: Admin Dashboard — Adding Problems</h3><p>The journey begins with the <strong>Admin Dashboard</strong>:</p><p>✅ Admin enters:</p><ul><li><strong>Problem Title</strong></li><li><strong>Problem Description</strong></li><li><strong>Base Code</strong> (Starter template for users)</li><li><strong>Test Cases</strong> (Input + Expected Output)</li></ul><p>✅ These details are stored in the <strong>database</strong> with a unique problemId for each problem.</p><h3>Step 2: Problem List Page</h3><p>The frontend shows a list of all coding problems fetched from the database. Each problem has a <strong>“Solve Now”</strong> button.</p><p>When the user clicks <strong>Solve Now</strong>:</p><ol><li>The frontend sends a request to get problem details (problemId).</li><li>The problem page opens with:</li></ol><ul><li><strong>Problem Description </strong>having sample testcase</li><li><a href="https://microsoft.github.io/monaco-editor/"><strong>Monaco Editor</strong></a> pre-filled with base code</li><li><strong>Submit Button</strong></li></ul><h3>Step 3: Problem Page — Writing &amp; Submitting Code</h3><p>Here’s where the magic happens! 🌟</p><ol><li>The user writes code in the <a href="https://microsoft.github.io/monaco-editor/">Monaco Editor</a>.</li><li>When the user clicks <strong>Submit</strong>:</li></ol><ul><li>The frontend sends a request to the backend with:<br> 🔹 <strong>problemId</strong><br> 🔹 <strong>languageId</strong><br> 🔹 <strong>sourceCode</strong> (code written by the user)</li></ul><p>Example payload:</p><pre>{<br>  &quot;problemId&quot;: &quot;123&quot;,<br>  &quot;languageId&quot;: 71,<br>  &quot;sourceCode&quot;: &quot;print(&#39;Hello, World!&#39;)&quot;<br>}</pre><h3>Step 4: Backend — Executing Code with Judge0</h3><p>Now the backend steps in. It works like this:</p><ol><li><strong>Fetch Test Cases: </strong>Fetch the test cases for the given problemId from the database.</li><li><strong>Send Code to Judge0: </strong>Loop through each test case to build the request body having all the test cases shown below and send a request to <strong>Judge0</strong></li></ol><pre>{<br>  &quot;submissions&quot;: [<br>    {<br>      &quot;language_id&quot;: 71,<br>      &quot;source_code&quot;: &quot;\ndef twosum(num1, num2):\n    return num1 + num2\n\n# Test the function\nnum1 = int(input())\nnum2 = int(input())\nresult = twosum(num1, num2)\nprint(result)\n&quot;,<br>      &quot;stdin&quot;: &quot;2 3&quot;,<br>      &quot;expected_output&quot;: &quot;5&quot;<br>    },<br>    {<br>      &quot;language_id&quot;: 71,<br>      &quot;source_code&quot;: &quot;\ndef twosum(num1, num2):\n    return num1 + num2\n\n# Test the function\nnum1 = int(input())\nnum2 = int(input())\nresult = twosum(num1, num2)\nprint(result)\n&quot;,<br>      &quot;stdin&quot;: &quot;2 0&quot;,<br>      &quot;expected_output&quot;: &quot;2&quot;<br>    },<br>    {<br>      &quot;language_id&quot;: 71,<br>      &quot;source_code&quot;: &quot;\ndef twosum(num1, num2):\n    return num1 + num2\n\n# Test the function\nnum1 = int(input())\nnum2 = int(input())\nresult = twosum(num1, num2)\nprint(result)\n&quot;,<br>      &quot;stdin&quot;: &quot;2 10&quot;,<br>      &quot;expected_output&quot;: &quot;12&quot;<br>    }<br>  ]<br>}</pre><p>Judge0 returns a unique token for each test case.</p><pre>[<br>  {<br>    &quot;token&quot;: &quot;db54881d-bcf5-4c7b-a2e3-d33fe7e25de7&quot;<br>  },<br>  {<br>    &quot;token&quot;: &quot;ecc52a9b-ea80-4a00-ad50-4ab6cc3bb2a1&quot;<br>  },<br>  {<br>    &quot;token&quot;: &quot;1b35ec3b-5776-48ef-b646-d5522bdeb2cc&quot;<br>  }<br>]</pre><p>3. <strong>Respond to Frontend: </strong>Return the list of tokens to the frontend, so it can track the status of each test case.</p><h3>Step 5: Real-Time Test Case Status</h3><p>Since code execution might take some time, the frontend needs to keep checking the status of each test case.</p><ol><li>The frontend repeatedly sends requests to the Judgo0 directly to check the status of each token.</li><li>The frontend updates the UI:<br> ✅ <strong>3/5 Test Cases Passed</strong></li><li>Once all results are fetched, the final result is displayed. 🎉</li></ol><h3>Step 6: Storing the Submission</h3><p>After showing the results, the frontend sends one final request to save the submission:</p><ul><li><strong>User ID</strong></li><li><strong>Problem ID</strong></li><li><strong>Status</strong> (Passed/Failed)</li><li><strong>Code</strong> (User’s submitted code)</li></ul><p>The backend saves these details in the database, allowing users to review their past submissions.</p><h3>Architecture Diagram</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pK7mX5ld60giE0K18je2Rg.png" /><figcaption>Figure 2: High level architecture flow diagram</figcaption></figure><p>This diagram shows how everything connects:</p><ol><li>Admin creates coding problem → Backend</li><li>User submits code → Backend</li><li>Backend sends code to Judge0 → Judge0 returns the tokens for submitted testcases</li><li>Tokens are sent back to the frontend → frontend makes call to Judge0 to fetch the status of each testcases → Show result to the user</li><li>Frontend makes call to backend to save the submission with results</li></ol><h3>🎯 Final Thoughts</h3><p>Building a coding practice platform might seem overwhelming at first, but breaking it down step-by-step makes it much more manageable:</p><p>✅ <a href="https://microsoft.github.io/monaco-editor/"><strong>Monaco Editor</strong></a> creates a smooth coding experience.<br>✅ <a href="https://ce.judge0.com/"><strong>Judge0 API</strong></a> handles multi-language code execution.</p><p>I hope you found this guide helpful! 🌟 If you have any questions or doubts, feel free to drop them in the <strong>comments section</strong> — I’d be happy to help.</p><p>Also, don’t forget to <strong>follow for more content</strong> like this, where I break down complex projects into simple, actionable steps. 🚀</p><p>Happy coding! 💻</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6aba0414be97" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Developed the Snake Game in Python (2025)]]></title>
            <link>https://medium.com/@balbirms/how-i-developed-the-snake-game-in-python-2025-9853a7d7e26f?source=rss-3e44dfe8d9a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/9853a7d7e26f</guid>
            <category><![CDATA[snake-games]]></category>
            <category><![CDATA[python-beginner]]></category>
            <category><![CDATA[pygame]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[coding-for-kids]]></category>
            <dc:creator><![CDATA[Balbir Yadav]]></dc:creator>
            <pubDate>Fri, 14 Mar 2025 20:51:12 GMT</pubDate>
            <atom:updated>2025-03-14T20:51:12.187Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*EVvbAayz2-CApPiJTqWVBg.gif" /><figcaption>Figure 1: Working Demo</figcaption></figure><p>Do you remember the classic <strong>Snake Game</strong>? 🐍 The one where a snake moves around the screen, eats food, and grows longer? I decided to build it using Python, and it was a super fun experience!</p><p>In this blog, I’ll explain <strong>each part</strong> of the game in the simplest way possible. Even if you’re new to coding, you’ll understand everything. Let’s get started! 🚀</p><h3>Understanding the Game Structure</h3><p>Before jumping into the code, let’s break the game into <strong>four main sections</strong>:</p><p>1️⃣ <strong>Game Window</strong> — A screen where everything happens.<br>2️⃣ <strong>Snake Movement</strong> — The snake should move automatically.<br>3️⃣ <strong>Food Generation</strong> — The snake should eat food and grow.<br>4️⃣ <strong>Collision Handling</strong> — The game should end if the snake hits a wall or itself.</p><p>Now, let’s take each part one by one.</p><h3>1️⃣ Creating the Game Window</h3><p>First, we need to create a <strong>game window</strong> where everything will happen. For this, we use a Python library called <strong><em>pygame</em></strong>. It helps create games easily.</p><p><strong>Steps to Create the Window:</strong></p><p>✅ Install pygame:</p><pre>pip install pygame</pre><p>✅ Create a simple window in Python:</p><pre>import pygame  <br><br>pygame.init()  # Initialize pygame  <br><br># Set up the game window  <br>WIDTH, HEIGHT = 500, 500  <br>screen = pygame.display.set_mode((WIDTH, HEIGHT))  <br>pygame.display.set_caption(&quot;Snake Game&quot;)  <br><br># Keep the window running  <br>running = True  <br>while running:  <br>    for event in pygame.event.get():  <br>        if event.type == pygame.QUIT:  <br>            running = False  <br><br>pygame.quit()</pre><p>👉 This code creates a <strong>500x500 pixel</strong> game window and keeps it open until we close it.</p><h3>2️⃣ Making the Snake Move</h3><p>The snake should <strong>keep moving forward</strong> automatically and change direction when we press arrow keys.</p><p><strong>Steps to Move the Snake:</strong></p><p>✅ Define the snake as a list of blocks.<br>✅ Change its position when a key is pressed.<br>✅ Update the screen to show movement.</p><pre>import time<br><br># Define the snake  <br>snake = [(100, 100), (90, 100), (80, 100)]  # A list of (x, y) positions  <br>direction = &quot;RIGHT&quot;  # Initial direction  <br><br>while running:  <br>    for event in pygame.event.get():  <br>        if event.type == pygame.QUIT:  <br>            running = False  <br>        elif event.type == pygame.KEYDOWN:  <br>            if event.key == pygame.K_UP:  <br>                direction = &quot;UP&quot;  <br>            elif event.key == pygame.K_DOWN:  <br>                direction = &quot;DOWN&quot;  <br>            elif event.key == pygame.K_LEFT:  <br>                direction = &quot;LEFT&quot;  <br>            elif event.key == pygame.K_RIGHT:  <br>                direction = &quot;RIGHT&quot;  <br><br>    # Move the snake  <br>    x, y = snake[0]  <br>    if direction == &quot;UP&quot;:  <br>        y -= 10  <br>    elif direction == &quot;DOWN&quot;:  <br>        y += 10  <br>    elif direction == &quot;LEFT&quot;:  <br>        x -= 10  <br>    elif direction == &quot;RIGHT&quot;:  <br>        x += 10  <br><br>    snake.insert(0, (x, y))  # Add new head  <br>    snake.pop()  # Remove tail  <br><br>    # Draw the snake  <br>    screen.fill((0, 0, 0))  # Clear screen  <br>    for block in snake:  <br>        pygame.draw.rect(screen, (0, 255, 0), (*block, 10, 10))  # Green snake  <br><br>    pygame.display.update()  # Refresh screen  <br>    time.sleep(0.1)  # Slow down movement</pre><p>👉 The snake <strong>moves automatically</strong> in the chosen direction.</p><h3>3️⃣ Adding Food for the Snake</h3><p>The snake needs <strong>food</strong> to grow. Let’s add random food on the screen.</p><p><strong>Steps to Add Food:</strong></p><p>✅ Generate a random position for the food.<br>✅ Draw the food on the screen.<br>✅ When the snake eats it, make it longer.</p><pre>import random  <br><br>food_x = random.randint(0, WIDTH // 10) * 10  <br>food_y = random.randint(0, HEIGHT // 10) * 10  <br><br>while running:  <br>    screen.fill((0, 0, 0))  <br>    pygame.draw.rect(screen, (255, 0, 0), (food_x, food_y, 10, 10))  # Red food  <br><br>    # Check if snake eats food  <br>    if snake[0] == (food_x, food_y):  <br>        food_x = random.randint(0, WIDTH // 10) * 10  <br>        food_y = random.randint(0, HEIGHT // 10) * 10  <br>        snake.append(snake[-1])  # Make snake longer  <br><br>    pygame.display.update()</pre><p>👉 When the snake <strong>touches the food</strong>, a new food appears, and the snake grows!</p><h3>4️⃣ Handling Collisions (Game Over Condition)</h3><p>The game should end if:<br> 1️⃣ The snake hits the wall.<br> 2️⃣ The snake collides with itself.</p><p><strong>Steps to Handle Collisions:</strong></p><p>✅ If the snake’s head goes outside the window, <strong>end the game</strong>.<br>✅ If the snake’s head touches its body, <strong>end the game</strong>.</p><pre>if x &lt; 0 or x &gt;= WIDTH or y &lt; 0 or y &gt;= HEIGHT:  <br>    running = False  # Snake hits the wall  <br><br>if snake[0] in snake[1:]:  <br>    running = False  # Snake hits itself</pre><p>👉 The game <strong>stops</strong> when the snake dies.</p><h3>Final Snake Game Code</h3><p>Here’s the full code for our <strong>Snake Game</strong>:</p><pre>import pygame  <br>import random  <br>import time  <br><br>pygame.init()  <br><br># Game variables  <br>WIDTH, HEIGHT = 500, 500  <br>screen = pygame.display.set_mode((WIDTH, HEIGHT))  <br>pygame.display.set_caption(&quot;Snake Game&quot;)  <br><br># Snake  <br>snake = [(100, 100), (90, 100), (80, 100)]  <br>direction = &quot;RIGHT&quot;  <br><br># Food  <br>food_x = random.randint(0, WIDTH // 10) * 10  <br>food_y = random.randint(0, HEIGHT // 10) * 10  <br><br>running = True  <br>while running:  <br>    for event in pygame.event.get():  <br>        if event.type == pygame.QUIT:  <br>            running = False  <br>        elif event.type == pygame.KEYDOWN:  <br>            if event.key == pygame.K_UP and direction != &quot;DOWN&quot;:  <br>                direction = &quot;UP&quot;  <br>            elif event.key == pygame.K_DOWN and direction != &quot;UP&quot;:  <br>                direction = &quot;DOWN&quot;  <br>            elif event.key == pygame.K_LEFT and direction != &quot;RIGHT&quot;:  <br>                direction = &quot;LEFT&quot;  <br>            elif event.key == pygame.K_RIGHT and direction != &quot;LEFT&quot;:  <br>                direction = &quot;RIGHT&quot;  <br><br>    # Move the snake  <br>    x, y = snake[0]  <br>    if direction == &quot;UP&quot;:  <br>        y -= 10  <br>    elif direction == &quot;DOWN&quot;:  <br>        y += 10  <br>    elif direction == &quot;LEFT&quot;:  <br>        x -= 10  <br>    elif direction == &quot;RIGHT&quot;:  <br>        x += 10  <br><br>    snake.insert(0, (x, y))  <br>    if (x, y) == (food_x, food_y):  <br>        food_x = random.randint(0, WIDTH // 10) * 10  <br>        food_y = random.randint(0, HEIGHT // 10) * 10  <br>    else:  <br>        snake.pop()  <br><br>    # Check collisions  <br>    if x &lt; 0 or x &gt;= WIDTH or y &lt; 0 or y &gt;= HEIGHT or snake[0] in snake[1:]:  <br>        running = False  <br><br>    # Draw everything  <br>    screen.fill((0, 0, 0))  <br>    pygame.draw.rect(screen, (255, 0, 0), (food_x, food_y, 10, 10))  <br>    for block in snake:  <br>        pygame.draw.rect(screen, (0, 255, 0), (*block, 10, 10))  <br><br>    pygame.display.update()  <br>    time.sleep(0.1)  <br><br>pygame.quit()</pre><h3>Conclusion</h3><p>That’s it! 🎉 We built a simple <strong>Snake Game in Python</strong> step by step. You can now <strong>customize it</strong>, add sound, or even a scoreboard. Try it out and have fun coding! 🚀 GitHub repo link <a href="https://github.com/Yadavbalbir/medium-blogs/tree/main/snakegame-python">https://github.com/Yadavbalbir/medium-blogs/tree/main/snakegame-python</a></p><p>I hope you enjoyed this journey as much as I did. If you have any <strong>doubts or questions</strong>, feel free to drop a comment — I’ll be happy to help! 💬</p><p><strong>Follow me</strong> for more such beginner-friendly Python projects and game tutorials. 🚀 Let’s keep coding and building amazing things together! 🌟</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9853a7d7e26f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>