<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Dhanush Kumar Sivaji</title>
    <description>The latest articles on DEV Community by Dhanush Kumar Sivaji (@dhanushkumarsivaji).</description>
    <link>https://dev.to/dhanushkumarsivaji</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F909684%2Ff0e49f96-ee40-4b7b-a54a-f6694ecf40f1.png</url>
      <title>DEV Community: Dhanush Kumar Sivaji</title>
      <link>https://dev.to/dhanushkumarsivaji</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/dhanushkumarsivaji"/>
    <language>en</language>
    <item>
      <title>The path to AI FDE #25: API keys, authentication and rate limits</title>
      <dc:creator>Dhanush Kumar Sivaji</dc:creator>
      <pubDate>Fri, 27 Nov 2026 16:13:21 +0000</pubDate>
      <link>https://dev.to/dhanushkumarsivaji/the-path-to-ai-fde-25-api-keys-authentication-and-rate-limits-29a6</link>
      <guid>https://dev.to/dhanushkumarsivaji/the-path-to-ai-fde-25-api-keys-authentication-and-rate-limits-29a6</guid>
      <description>&lt;p&gt;&lt;em&gt;Originally published on my newsletter, The Path to AI FDE. &lt;a href="https://dhanushkumarsivaji.substack.com/subscribe" rel="noopener noreferrer"&gt;Subscribe free&lt;/a&gt; to get each issue by email.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;This is a &lt;strong&gt;“From Zero” issue&lt;/strong&gt;. So far, every API we’ve called has been open to anyone. Real AI APIs aren’t: they need to know &lt;strong&gt;who you are&lt;/strong&gt; (so they can bill you) and they cap &lt;strong&gt;how much you can ask for&lt;/strong&gt; (so one user can’t swamp everyone else). Today covers both.&lt;/p&gt;

&lt;p&gt;You need the same setup as yesterday (#24): your &lt;code&gt;api-practice&lt;/code&gt; uv project with &lt;code&gt;httpx&lt;/code&gt; added (run scripts with &lt;code&gt;uv run&lt;/code&gt;). Everything here is safe to run. We use httpbin’s practice login check, a fake API that runs entirely on your computer, and &lt;strong&gt;made-up tokens&lt;/strong&gt;. No real key appears anywhere, and you shouldn’t paste one in either.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fgty06wc6iyr27di4d6a2.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fgty06wc6iyr27di4d6a2.png" alt="Cover card titled &amp;quot;API keys, auth and rate limits, from Zero&amp;quot; for issue 25 of The Path to AI FDE by Dhanush Kumar Sivaji. Subtitle: how an API knows who you are and how much you're allowed. Six numbered cards in two lanes. Part A, who you are: 1, authentication, proving who you are with a key, with a chip saying no key gets 401; 2, the header, shown as Authorization: Bearer &lt;key&gt;, though some providers use their own header name; 3, keys stay on the server, where your backend holds the key, with a warning: never in browser or app code. Part B, how much you're allowed: 4, rate limits, requests or tokens per minute, with a chip saying too many gets 429; 5, Retry-After, shown as Retry-After: 2, where the server says how long to wait; 6, quotas and billing, where usage costs money, with a warning to set a spending limit first. A tip bar says the key is your ticket, and the rate limit is the turnstile." width="800" height="613"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  Part A · Who you are
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fmgl7ytfhiipkh1qi8z1m.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fmgl7ytfhiipkh1qi8z1m.png" alt="Diagram titled &amp;quot;Authentication: who are you?&amp;quot;, subtitle: the same request, without and with a key. Left panel, no key: GET /bearer with Host: httpbin.org gets 401 Unauthorized, plus WWW-Authenticate: Bearer, meaning send me a bearer token. Right panel, with a made-up key: the same request plus the highlighted header Authorization: Bearer demo-token-123 gets 200 and {'authenticated': True, 'token': 'demo-token-123'}. Below, a code panel says the key comes from an environment variable, not the code: token = os.environ(&amp;quot;DEMO_TOKEN&amp;quot;), then r = httpx.get(url, headers={&amp;quot;Authorization&amp;quot;: f&amp;quot;Bearer {token}&amp;quot;}, timeout=10), then print(&amp;quot;With key:&amp;quot;, r.status_code, r.json()); the output is With key: 200 and the same dictionary. A note says to set it first in the terminal with export DEMO_TOKEN=&amp;quot;demo-token-123&amp;quot;, a made-up value. A tip bar says a key is a ticket: whoever holds it gets in, so guard it like a password." width="800" height="613"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Authentication: proving who you are.&lt;/strong&gt; An &lt;strong&gt;API key&lt;/strong&gt; (or &lt;strong&gt;token&lt;/strong&gt;) is a long random string the provider gives you. You send it with every request, and the server checks it. httpbin has a practice endpoint, &lt;code&gt;/bearer&lt;/code&gt;, that accepts any token, so you can see both sides safely.&lt;/p&gt;

&lt;p&gt;First, put a &lt;strong&gt;made-up&lt;/strong&gt; token in an environment variable, a named value your terminal hands to programs (#13). On macOS or Linux:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="n"&gt;export&lt;/span&gt; &lt;span class="no"&gt;DEMO_TOKEN&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"demo-token-123"&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;(On Windows PowerShell: &lt;code&gt;$env:DEMO_TOKEN = "demo-token-123"&lt;/code&gt;.) Then, in the same terminal:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;os&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;httpx&lt;/span&gt;

&lt;span class="n"&gt;url&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"https://httpbin.org/bearer"&lt;/span&gt;

&lt;span class="n"&gt;r&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;httpx&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;url&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;timeout&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"No key:"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;status_code&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;headers&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"www-authenticate"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="n"&gt;token&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;os&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;environ&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"DEMO_TOKEN"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;span class="n"&gt;r&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;httpx&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;url&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;headers&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;"Authorization"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"Bearer {token}"&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;timeout&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"With key:"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;status_code&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;json&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="nc"&gt;No&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;401&lt;/span&gt; &lt;span class="nc"&gt;Bearer&lt;/span&gt;
&lt;span class="nc"&gt;With&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;200&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s1"&gt;'authenticated'&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;True&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'token'&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s1"&gt;'demo-token-123'&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;No key gets &lt;code&gt;401 Unauthorized&lt;/code&gt;, plus a &lt;code&gt;WWW-Authenticate&lt;/code&gt; header naming the kind of credential it expects. With a key, you get &lt;code&gt;200&lt;/code&gt;. The standard calls this a &lt;strong&gt;bearer&lt;/strong&gt; token for a reason: anyone who holds it can use it. Treat a real key like a password.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Feo4e5jpczpg2aju2a5sg.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Feo4e5jpczpg2aju2a5sg.png" alt="Diagram titled &amp;quot;Where the key goes&amp;quot;, subtitle: two common header styles, and two errors to tell apart. Left card, the standard style: Authorization: Bearer &lt;key&gt;, the word Bearer, a space, then the key, used by many APIs. Right card, a provider's own header: x-api-key: &lt;key&gt;, an example, since some providers pick their own name. A bar says it's the same kind of secret with a different label, so copy the header name from your provider's docs. Two error cards: 401 Unauthorized, the key is missing, mistyped or revoked, so check the key; 403 Forbidden, the server knows who you are, but this key isn't allowed to do this. A card titled &amp;quot;Headers, never the URL&amp;quot; contrasts a header, ticked, with https://api.example.com/v1/data?key=..., crossed out, because URLs end up in logs and history. A tip bar says 401 means who are you, and 403 means I know you, and no." width="800" height="613"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. The Authorization header, and its cousins.&lt;/strong&gt; The key travels in a &lt;strong&gt;header&lt;/strong&gt;. There are two common styles:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Standard · &lt;code&gt;Authorization: Bearer &amp;lt;key&amp;gt;&lt;/code&gt; · The word &lt;code&gt;Bearer&lt;/code&gt;, a space, then the key. Many APIs use this.&lt;/li&gt;
&lt;li&gt;Provider-specific · for example &lt;code&gt;x-api-key: &amp;lt;key&amp;gt;&lt;/code&gt; · Some providers pick their own header name.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Both carry the same kind of secret; only the label differs. Your provider’s docs tell you which one to use, so copy the header name from there. Two status codes to tell apart:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;401 Unauthorized&lt;/code&gt;: the key is missing, mistyped or revoked. Check the key.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;403 Forbidden&lt;/code&gt;: the server knows who you are, but your key isn’t allowed to do this, for example a model your account can’t use.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;And as #23 warned: keys go in &lt;strong&gt;headers&lt;/strong&gt;, never in the URL, because URLs end up in logs.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fhow45fbfiv19p907z6wa.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fhow45fbfiv19p907z6wa.png" alt="Diagram titled &amp;quot;Keys stay on the server&amp;quot;, subtitle: the browser talks to you, and you talk to the provider. A green panel, the safe shape, shows three boxes joined by arrows: browser or app, with no provider key; your server, which reads the key from an environment variable; AI provider, which checks the key. An orange warning panel: key in browser JavaScript or a mobile app, where anyone can open developer tools, or unpack the app, and copy it, then spend your money. A code panel titled &amp;quot;On your server: read it, check it, never print it whole&amp;quot;: key = os.environ.get(&amp;quot;DEMO_API_KEY&amp;quot;); if not key, raise SystemExit(&amp;quot;Set DEMO_API_KEY first. Never paste a key into your code.&amp;quot;); otherwise print(&amp;quot;Key loaded, ending in&amp;quot;, key(-4:)). The output is Key loaded, ending in 7f3a, run with the made-up value demo-key-not-real-7f3a, and a note says to list any .env file in .gitignore. A tip bar says the provider key lives only on a server you control." width="800" height="669"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. Keys stay on the server.&lt;/strong&gt; Anything you ship to a &lt;strong&gt;browser&lt;/strong&gt; or a &lt;strong&gt;phone app&lt;/strong&gt; can be read by whoever uses it: open the browser’s developer tools, or unpack the app, and the key is right there. So the rule is simple: &lt;strong&gt;the provider key lives only on a server you control.&lt;/strong&gt; The browser talks to your server, and your server talks to the provider.&lt;/p&gt;

&lt;p&gt;On that server, read the key from the environment, never from your code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;os&lt;/span&gt;

&lt;span class="n"&gt;key&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;os&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;environ&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"DEMO_API_KEY"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;raise&lt;/span&gt; &lt;span class="nc"&gt;SystemExit&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Set DEMO_API_KEY first. Never paste a key into your code."&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Key loaded, ending in"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;With nothing set, it stops with the message &lt;code&gt;Set DEMO_API_KEY first. Never paste a key into your code.&lt;/code&gt; With a made-up value such as &lt;code&gt;demo-key-not-real-7f3a&lt;/code&gt;, it prints:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="nc"&gt;Key&lt;/span&gt; &lt;span class="n"&gt;loaded&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;ending&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="mi"&gt;7f3a&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Printing just the last four characters lets you check &lt;em&gt;which&lt;/em&gt; key loaded without exposing it. If you keep keys in a &lt;code&gt;.env&lt;/code&gt; file for convenience, add &lt;code&gt;.env&lt;/code&gt; to your &lt;code&gt;.gitignore&lt;/code&gt; (#11) so it never reaches GitHub.&lt;/p&gt;

&lt;h2&gt;
  
  
  Part B · How much you’re allowed
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F4u5twt91jyut594m5jui.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F4u5twt91jyut594m5jui.png" alt="Diagram titled &amp;quot;Rate limits: the turnstile&amp;quot;, subtitle: your key is the ticket, and the counter decides when you wait. A code panel shows a fake fortune-cookie API that runs offline and allows 3: a function toy_api counts calls and, after 3, returns httpx.Response(429, headers={&amp;quot;Retry-After&amp;quot;: &amp;quot;2&amp;quot;}); otherwise it returns 200 with a fortune, &amp;quot;Good news is on its way.&amp;quot; A client is built with transport=httpx.MockTransport(toy_api) and base_url=&amp;quot;https://fortune.example&amp;quot;. Below, five quick requests as tiles: requests 1, 2 and 3 return 200 in green; requests 4 and 5 return 429 in orange, each with Retry-After: 2. Three cards: per minute, requests per minute and for AI APIs often tokens per minute; per day, some limits run over longer windows; by tier, limits often grow with your account tier. A tip bar says going over any limit gets 429 Too Many Requests." width="800" height="718"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;4. Rate limits: how much, how fast.&lt;/strong&gt; Providers cap how much each key can do: &lt;strong&gt;requests per minute&lt;/strong&gt;, and for AI APIs often &lt;strong&gt;tokens per minute&lt;/strong&gt; (tokens are chunks of text, a later issue) or per day. The limits usually depend on your account tier. Go over any of them and you get &lt;code&gt;429 Too Many Requests&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;To see one without hammering a real service, here’s a fake fortune-cookie API that runs entirely on your computer. httpx’s &lt;code&gt;MockTransport&lt;/code&gt; sends requests to a Python function instead of the internet. This one allows three requests:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;httpx&lt;/span&gt;

&lt;span class="n"&gt;calls&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;

&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;toy_api&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;request&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;global&lt;/span&gt; &lt;span class="n"&gt;calls&lt;/span&gt;
    &lt;span class="n"&gt;calls&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;calls&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;httpx&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Response&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;429&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;headers&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;"Retry-After"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"2"&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;httpx&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Response&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;200&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;json&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;"fortune"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"Good news is on its way."&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="n"&gt;client&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;httpx&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Client&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="n"&gt;transport&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;httpx&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;MockTransport&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;toy_api&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;base_url&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"https://fortune.example"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;6&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;r&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;client&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"/fortune"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;status_code&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;headers&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Retry-After"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="mi"&gt;1&lt;/span&gt; &lt;span class="mi"&gt;200&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;
&lt;span class="mi"&gt;2&lt;/span&gt; &lt;span class="mi"&gt;200&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;
&lt;span class="mi"&gt;3&lt;/span&gt; &lt;span class="mi"&gt;200&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;
&lt;span class="mi"&gt;4&lt;/span&gt; &lt;span class="mi"&gt;429&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;
&lt;span class="mi"&gt;5&lt;/span&gt; &lt;span class="mi"&gt;429&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Requests four and five are turned away. (&lt;code&gt;fortune.example&lt;/code&gt; is a reserved example name, and nothing leaves your machine.) Real limits reset over time, such as each minute, while this toy just counts.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fpxhg1hcs0mm6e788kw23.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fpxhg1hcs0mm6e788kw23.png" alt="Diagram titled &amp;quot;Retry-After: wait, then retry&amp;quot;, subtitle: when the server says how long, listen. A code panel titled &amp;quot;Read the header, sleep, try again, and stop after a few tries&amp;quot; shows get_with_retry(path, max_tries=4): for each attempt it gets the path and returns the response unless the status is 429; otherwise it reads Retry-After (default 5), prints the attempt and wait, and sleeps; after max_tries it raises RuntimeError(&amp;quot;Still rate limited, giving up&amp;quot;). The output is Try 1: 429, waiting 1 s; Try 2: 429, waiting 1 s; 200 Patience pays. A note says the toy API answers the first two tries with 429 and Retry-After: 1, then 200. Two contrast cards: polite client, 429, wait 1 s, 429, wait 1 s, 200, capped at 4 tries; tight loop, 429 again and again, instantly, forever, earning more 429s. Two notes: Retry-After can be a number of seconds or an HTTP date, and this toy handles only seconds; with no header, wait a little longer after each failure, called backoff, with a full lesson later. A tip bar says retry 429 and some 5xx, and never retry a 401." width="800" height="741"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;5. Retry-After: the server tells you when.&lt;/strong&gt; A &lt;code&gt;429&lt;/code&gt; (or a &lt;code&gt;503&lt;/code&gt;) may come with a &lt;code&gt;Retry-After&lt;/code&gt; header: how long to wait before trying again. The polite client reads it, sleeps, then retries, and gives up after a few tries:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;time&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;httpx&lt;/span&gt;

&lt;span class="n"&gt;calls&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;

&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;toy_api&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;request&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;global&lt;/span&gt; &lt;span class="n"&gt;calls&lt;/span&gt;
    &lt;span class="n"&gt;calls&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;calls&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;=&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;httpx&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Response&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;429&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;headers&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;"Retry-After"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"1"&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;httpx&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Response&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;200&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;json&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;"fortune"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"Patience pays."&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="n"&gt;client&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;httpx&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Client&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="n"&gt;transport&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;httpx&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;MockTransport&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;toy_api&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;base_url&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"https://fortune.example"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;get_with_retry&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;path&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;max_tries&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;attempt&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;max_tries&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;r&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;client&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;path&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;status_code&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="mi"&gt;429&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;r&lt;/span&gt;
        &lt;span class="n"&gt;wait&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;headers&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Retry-After"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"5"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"Try {attempt}: 429, waiting {wait} s"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="n"&gt;time&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;sleep&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;wait&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;raise&lt;/span&gt; &lt;span class="nc"&gt;RuntimeError&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Still rate limited, giving up"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="n"&gt;r&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;get_with_retry&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"/fortune"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;status_code&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;json&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"fortune"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="nc"&gt;Try&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;429&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;waiting&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt; &lt;span class="n"&gt;s&lt;/span&gt;
&lt;span class="nc"&gt;Try&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;429&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;waiting&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt; &lt;span class="n"&gt;s&lt;/span&gt;
&lt;span class="mi"&gt;200&lt;/span&gt; &lt;span class="nc"&gt;Patience&lt;/span&gt; &lt;span class="n"&gt;pays&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Two honest caveats. &lt;code&gt;Retry-After&lt;/code&gt; can also be a &lt;strong&gt;date&lt;/strong&gt; rather than a number of seconds; this toy handles only seconds. And when there’s no header, the usual move is to wait a little longer after each failure (”backoff”). Proper retries get a full issue later in the series.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fit28r4geetuzvkbmgdr3.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fit28r4geetuzvkbmgdr3.png" alt="Diagram titled &amp;quot;Quotas and billing&amp;quot;, subtitle: usage costs money, so cap it before you loop. An orange panel labelled &amp;quot;Illustrative numbers only (not any provider's price)&amp;quot; shows the sum $0.002 per call, times 600 calls per minute from a buggy loop, times 60 minutes, equals $72.00 per hour, and $1,728.00 per day if nobody notices. A green checklist titled &amp;quot;Before your first loop over a paid API&amp;quot;: set a spending limit or budget alert in the provider's console, where offered; use a separate key per project, so you can see and revoke each one; test on small inputs first; check the usage page after your first runs. Two cards: rate limits protect the provider; spending limits protect you. A tip bar says a fraction of a cent per call becomes a real bill overnight." width="799" height="621"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;6. Quotas and billing: usage costs money.&lt;/strong&gt; Every successful call to a paid API is billed, usually by how much text goes in and out. Small amounts add up fast when code goes wrong. Here’s illustrative arithmetic (the price is &lt;strong&gt;made up&lt;/strong&gt;, not any provider’s):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="n"&gt;price_per_call&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mf"&gt;0.002&lt;/span&gt;   &lt;span class="c1"&gt;# illustrative price in US dollars, not a real one&lt;/span&gt;
&lt;span class="n"&gt;calls_per_minute&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;600&lt;/span&gt;   &lt;span class="c1"&gt;# a loop with a bug in it&lt;/span&gt;

&lt;span class="n"&gt;per_hour&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;price_per_call&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;calls_per_minute&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="mi"&gt;60&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"${per_hour:,.2f} per hour"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"${per_hour * 24:,.2f} per day"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;$&lt;span class="mf"&gt;72.00&lt;/span&gt; &lt;span class="n"&gt;per&lt;/span&gt; &lt;span class="n"&gt;hour&lt;/span&gt;
$&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="mf"&gt;728.00&lt;/span&gt; &lt;span class="n"&gt;per&lt;/span&gt; &lt;span class="n"&gt;day&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A fraction of a cent per call turns into a real bill overnight. Before you write your first loop over a paid API:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Set a spending limit or budget alert&lt;/strong&gt; in the provider’s console, where the provider offers one.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Use a separate key per project&lt;/strong&gt;, so you can see who spent what and revoke one without breaking the others.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Test on small inputs first&lt;/strong&gt;, and check the usage page after your first runs.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Rate limits protect the provider. Spending limits protect &lt;strong&gt;you&lt;/strong&gt;.&lt;/p&gt;




&lt;h3&gt;
  
  
  Try it (20 minutes)
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;Run the &lt;code&gt;/bearer&lt;/code&gt; snippet from point 1. Then change the environment variable to a different made-up value and run it again: httpbin echoes back whatever token you sent.&lt;/li&gt;
&lt;li&gt;Run the rate-limit toy from point 4 with &lt;code&gt;calls &amp;gt; 1&lt;/code&gt; instead of &lt;code&gt;calls &amp;gt; 3&lt;/code&gt;. How many &lt;code&gt;200&lt;/code&gt;s do you get now?&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;The main exercise:&lt;/strong&gt; pick one AI provider you’re curious about and find its &lt;strong&gt;rate limits&lt;/strong&gt; page in the official docs. Don’t sign up and don’t create a key; reading is enough. Fill in this table:&lt;/li&gt;
&lt;/ol&gt;

&lt;ul&gt;
&lt;li&gt;Which limit types? (requests/min, tokens/min, per day...)&lt;/li&gt;
&lt;li&gt;Do limits change with account tier or spend?&lt;/li&gt;
&lt;li&gt;Which response headers report your remaining limit?&lt;/li&gt;
&lt;li&gt;What status code do you get when you go over?&lt;/li&gt;
&lt;li&gt;Do they send &lt;code&gt;Retry-After&lt;/code&gt;?&lt;/li&gt;
&lt;li&gt;Where do you set a spending limit or alert?&lt;/li&gt;
&lt;li&gt;Which header carries the key? (&lt;code&gt;Authorization: Bearer&lt;/code&gt; or their own)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Keep the table: you’ll want it next week.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Check your understanding:&lt;/strong&gt; your script gets &lt;code&gt;401&lt;/code&gt; on one call and &lt;code&gt;429&lt;/code&gt; on another. What does each mean, and should you retry either one?&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Answer:&lt;/em&gt; &lt;code&gt;401&lt;/code&gt; &lt;em&gt;means the key is missing or wrong. Retrying won’t help, so fix the key.&lt;/em&gt; &lt;code&gt;429&lt;/code&gt; &lt;em&gt;means you’re over a rate limit. Wait (for&lt;/em&gt; &lt;code&gt;Retry-After&lt;/code&gt; &lt;em&gt;if it’s sent), then retry a limited number of times.&lt;/em&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Common beginner mistakes
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Putting a key in front-end code.&lt;/strong&gt; Browser JavaScript and mobile apps can be read by anyone who has them. Keep keys on your server (point 3).&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Retrying in a tight loop.&lt;/strong&gt; Hitting the API again the instant you get a &lt;code&gt;429&lt;/code&gt; just earns more &lt;code&gt;429&lt;/code&gt;s and can get your key throttled further. Wait, and cap the number of tries.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Pasting a key into code and committing it.&lt;/strong&gt; Even in a private repo, it ends up in history. Use environment variables, and add &lt;code&gt;.env&lt;/code&gt; to &lt;code&gt;.gitignore&lt;/code&gt;. If a key ever leaks, &lt;strong&gt;revoke it in the console and make a new one&lt;/strong&gt;. Deleting the file isn’t enough.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Printing the whole key in logs.&lt;/strong&gt; Logs get shared. Print the last four characters at most.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Retrying a&lt;/strong&gt; &lt;code&gt;401&lt;/code&gt;&lt;strong&gt;.&lt;/strong&gt; A wrong key stays wrong. Only &lt;code&gt;429&lt;/code&gt; and some &lt;code&gt;5xx&lt;/code&gt; are worth waiting out.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Takeaway
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;An API key proves who you are; send it in a header (&lt;/strong&gt;&lt;code&gt;Authorization: Bearer ...&lt;/code&gt; &lt;strong&gt;or the provider’s own name) and keep it on your server.&lt;/strong&gt; &lt;code&gt;401&lt;/code&gt; &lt;strong&gt;means fix the key.&lt;/strong&gt; &lt;code&gt;429&lt;/code&gt; &lt;strong&gt;means slow down: wait for&lt;/strong&gt; &lt;code&gt;Retry-After&lt;/code&gt;&lt;strong&gt;, retry a few times, then stop. Usage costs money, so set a spending limit before your first loop.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Where this fits in my roadmap:&lt;/strong&gt; this finishes the “how APIs work” basics. Next week: &lt;strong&gt;your first LLM API call&lt;/strong&gt;, where everything from #23 to #25 comes together. Later in the series, timeouts, rate limits and safe retries get a full lesson of their own.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Over to you:&lt;/strong&gt; which provider’s rate-limit page did you read for the Try it, and what surprised you? Reply with one line.&lt;/p&gt;




&lt;h3&gt;
  
  
  Sources
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;IETF, RFC 6750 “The OAuth 2.0 Authorization Framework: Bearer Token Usage”: a bearer token is one where “any party in possession of the token (a “bearer”) can use the token in any way that any other party in possession of it can”, and the example header &lt;code&gt;Authorization: Bearer mF_9.B5f-4.1JqM&lt;/code&gt;. &lt;a href="https://www.rfc-editor.org/rfc/rfc6750.html" rel="noopener noreferrer"&gt;https://www.rfc-editor.org/rfc/rfc6750.html&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;IETF, RFC 9110 “HTTP Semantics”: 401 “lacks valid authentication credentials for the target resource” (15.5.2); &lt;code&gt;Authorization&lt;/code&gt; (11.6.2); &lt;code&gt;Retry-After&lt;/code&gt; “can be either an HTTP-date or a number of seconds to delay after receiving the response” (10.2.3). &lt;a href="https://www.rfc-editor.org/rfc/rfc9110.html" rel="noopener noreferrer"&gt;https://www.rfc-editor.org/rfc/rfc9110.html&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;IETF, RFC 6585, section 4 (429 Too Many Requests): responses “MAY include a Retry-After header indicating how long to wait before making a new request.” &lt;a href="https://www.rfc-editor.org/rfc/rfc6585.html#section-4" rel="noopener noreferrer"&gt;https://www.rfc-editor.org/rfc/rfc6585.html#section-4&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;MDN, “Authorization header”. &lt;a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Authorization" rel="noopener noreferrer"&gt;https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Authorization&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;MDN, “401 Unauthorized”. &lt;a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/401" rel="noopener noreferrer"&gt;https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/401&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;MDN, “429 Too Many Requests”. &lt;a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/429" rel="noopener noreferrer"&gt;https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/429&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;MDN, “Retry-After header”. &lt;a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Retry-After" rel="noopener noreferrer"&gt;https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Retry-After&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;HTTPX, Transports: “The httpx.MockTransport class accepts a handler function, which can be used to map requests onto pre-determined responses”. &lt;a href="https://www.python-httpx.org/advanced/transports/" rel="noopener noreferrer"&gt;https://www.python-httpx.org/advanced/transports/&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Python docs, &lt;code&gt;os&lt;/code&gt; module (&lt;code&gt;os.environ&lt;/code&gt;). &lt;a href="https://docs.python.org/3/library/os.html" rel="noopener noreferrer"&gt;https://docs.python.org/3/library/os.html&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;OWASP, Secrets Management Cheat Sheet (keeping secrets out of code, rotation and revocation). &lt;a href="https://cheatsheetseries.owasp.org/cheatsheets/Secrets_Management_Cheat_Sheet.html" rel="noopener noreferrer"&gt;https://cheatsheetseries.owasp.org/cheatsheets/Secrets_Management_Cheat_Sheet.html&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;httpbin, “A simple HTTP Request &amp;amp; Response Service” (&lt;code&gt;/bearer&lt;/code&gt;). &lt;a href="https://httpbin.org/" rel="noopener noreferrer"&gt;https://httpbin.org/&lt;/a&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;em&gt;All code ran on Nov 2, 2026 with Python 3.13 and httpx 0.28.1. The /bearer call used a made-up token; the rate-limit and retry examples use an offline fake API; prices are illustrative, not any provider’s. No real API keys were used. Sources checked Nov 2, 2026.&lt;/em&gt;&lt;/p&gt;




&lt;p&gt;Free: &lt;a href="https://dhanushkumarsivaji.substack.com/p/the-path-to-ai-fde-the-free-roadmap" rel="noopener noreferrer"&gt;the 5-page roadmap from Novice to AI FDE&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;If this was useful, &lt;a href="https://dhanushkumarsivaji.substack.com/subscribe" rel="noopener noreferrer"&gt;subscribe to The Path to AI FDE&lt;/a&gt; for the next issue.&lt;/p&gt;

</description>
      <category>api</category>
      <category>beginners</category>
      <category>webdev</category>
      <category>security</category>
    </item>
    <item>
      <title>The path to AI FDE #21: Classes, objects and dataclasses</title>
      <dc:creator>Dhanush Kumar Sivaji</dc:creator>
      <pubDate>Tue, 24 Nov 2026 03:15:50 +0000</pubDate>
      <link>https://dev.to/dhanushkumarsivaji/the-path-to-ai-fde-21-classes-objects-and-dataclasses-4fdb</link>
      <guid>https://dev.to/dhanushkumarsivaji/the-path-to-ai-fde-21-classes-objects-and-dataclasses-4fdb</guid>
      <description>&lt;p&gt;&lt;em&gt;Originally published on my newsletter, The Path to AI FDE. &lt;a href="https://dhanushkumarsivaji.substack.com/subscribe" rel="noopener noreferrer"&gt;Subscribe free&lt;/a&gt; to get each issue by email.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;This is a &lt;strong&gt;“From Zero” issue&lt;/strong&gt;. So far your data and your functions have lived apart: a dictionary over here, a function that changes it over there. That works, but as a program grows you start passing the same five values into every function. A &lt;strong&gt;class&lt;/strong&gt; lets you bundle the data with the actions that belong to it.&lt;/p&gt;

&lt;p&gt;Think of a cookie cutter and the cookies it makes. The cutter is the &lt;strong&gt;class&lt;/strong&gt;, the blueprint. Each cookie is an &lt;strong&gt;object&lt;/strong&gt; made from it: same shape, its own sprinkles. By the end you’ll have a toy reading tracker built from a dataclass, and you’ll know when a class is overkill.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fueyzsvbd8irqb87udc6y.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fueyzsvbd8irqb87udc6y.png" alt="Cover card titled &amp;quot;Classes and objects, from Zero&amp;quot; for issue 21 of The Path to AI FDE by Dhanush Kumar Sivaji. Subtitle: bundle data with the actions that belong to it. Six numbered cards in two lanes. Part A, classes and objects: 1, classes, shown as class Cookie: a blueprint that bundles data and behaviour; 2, objects, shown as a = Cookie() and b = Cookie(): one concrete thing made from the blueprint; 3, __init__ and self, shown as self.balance = balance: __init__ sets up each object's data, and self means &amp;quot;this object&amp;quot;. Part B, classes in practice: 4, methods, shown as asha.deposit(30): functions that belong to a class and use its data; 5, dataclasses, shown as @dataclass: writes __init__, a readable printout and == for data-holding classes; 6, when to use one: state plus behaviour, a class; just a calculation, a function; with a warning that forgetting self gives &amp;quot;takes 1 positional argument but 2 were given&amp;quot;. A tip bar says a class is a blueprint, and objects are the things you make from it." width="800" height="606"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  Part A · Classes and objects
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F9cp7ys6xq6n6r17nmo0o.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F9cp7ys6xq6n6r17nmo0o.png" alt="Diagram titled &amp;quot;A class is a blueprint&amp;quot;, subtitle: you've used them already, now make your own. Top, you already use classes: print(type(&amp;quot;hello&amp;quot;)), print(type((1, 2, 3))) and print(&amp;quot;hello&amp;quot;.upper()) print &lt;class 'str'&gt;, &lt;class 'list'&gt; and HELLO; &amp;quot;hello&amp;quot; is made from the str class, and .upper() is an action that belongs to it. Bottom left, your own blueprint: class Cookie: with pass inside, then print(Cookie), which prints &lt;class '__main__.Cookie'&gt;. An arrow points to three notes: class equals blueprint, like a cookie cutter that says what every cookie has (data) and can do (behaviour); pass means nothing inside yet, a placeholder so the block isn't empty; and CapitalWords, so class names look like Cookie and PiggyBank while variables and functions stay lowercase. A tip bar says a class keeps data and the actions that belong to it in one place." width="800" height="682"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. A class is a blueprint that bundles data and behaviour.&lt;/strong&gt; You’ve been using classes since #14 without the name. Try this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kd"&gt;type&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"hello"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kd"&gt;type&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"hello"&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;upper&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="s1"&gt;'str'&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;
&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="s1"&gt;'list'&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;
&lt;span class="no"&gt;HELLO&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;"hello"&lt;/code&gt; is made from the &lt;code&gt;str&lt;/code&gt; class, and &lt;code&gt;[1, 2, 3]&lt;/code&gt; from the &lt;code&gt;list&lt;/code&gt; class. Each class knows what data it holds (the letters, the items) and what it can do (&lt;code&gt;.upper()&lt;/code&gt;, &lt;code&gt;.append()&lt;/code&gt;). That’s the whole idea: &lt;strong&gt;data and the actions that belong to it, in one place&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Now make your own. Save &lt;code&gt;cookie.py&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Cookie&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;pass&lt;/span&gt;

&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Cookie&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="s1"&gt;'__main__.Cookie'&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;class Cookie:&lt;/code&gt; starts the blueprint. &lt;code&gt;pass&lt;/code&gt; means “nothing inside yet”. &lt;code&gt;__main__&lt;/code&gt; is the name of the file you ran (#20). By convention, class names use &lt;strong&gt;CapitalWords&lt;/strong&gt; (&lt;code&gt;Cookie&lt;/code&gt;, &lt;code&gt;PiggyBank&lt;/code&gt;), while variables and functions stay lowercase.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F2x24c0cxidvtht6xzjif.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F2x24c0cxidvtht6xzjif.png" alt="Diagram titled &amp;quot;One blueprint, many objects&amp;quot;, subtitle: each call to Cookie() makes a new cookie. A dashed cookie-cutter box labelled Cookie, the class, has two arrows to two cookies: a = Cookie(), object 1, and b = Cookie(), object 2. Below, code defines class Cookie with pass, makes a and b, then prints isinstance(a, Cookie) and a is b, giving True and False. Three notes: isinstance(a, Cookie) is True because a was made from Cookie; a is b is False because two calls make two separate objects; object and instance mean the same thing. A tip bar says call the class, with brackets, to make a new object each time." width="800" height="608"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. An object (or instance) is one concrete thing made from the blueprint.&lt;/strong&gt; You make one by &lt;strong&gt;calling&lt;/strong&gt; the class, with brackets, like a function:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Cookie&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;pass&lt;/span&gt;

&lt;span class="n"&gt;a&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Cookie&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;b&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Cookie&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;isinstance&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Cookie&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt; &lt;span class="k"&gt;is&lt;/span&gt; &lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="kc"&gt;True&lt;/span&gt;
&lt;span class="kc"&gt;False&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;isinstance(a, Cookie)&lt;/code&gt; asks “was &lt;code&gt;a&lt;/code&gt; made from &lt;code&gt;Cookie&lt;/code&gt;?” Yes.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;a is b&lt;/code&gt; asks “are these the very same object?” No: two calls, two cookies.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;“Object” and “instance” mean the same thing. You’ll hear “an instance of &lt;code&gt;Cookie&lt;/code&gt;“ just as often as “a &lt;code&gt;Cookie&lt;/code&gt; object”.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F4d99ljd9cx36lvzsq46n.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F4d99ljd9cx36lvzsq46n.png" alt="Diagram titled &amp;quot;__init__ and self&amp;quot;, subtitle: set up each object's own data as it's made. Left, piggy.py: class PiggyBank with def __init__(self, owner, balance=0) storing self.owner = owner and self.balance = balance; then asha = PiggyBank(&amp;quot;Asha&amp;quot;) and ravi = PiggyBank(&amp;quot;Ravi&amp;quot;, 50), and two prints that output Asha 0 and Ravi 50. Right, two object boxes: asha with .owner &amp;quot;Asha&amp;quot; and .balance 0; ravi with .owner &amp;quot;Ravi&amp;quot; and .balance 50; each object keeps its own attributes. Three steps below: 1, Python makes it, PiggyBank(&amp;quot;Asha&amp;quot;) makes a fresh, empty object; 2, __init__ runs, the new object goes in as self and &amp;quot;Asha&amp;quot; as owner, and you never pass self; 3, stored on self, self.owner = owner saves an attribute, reached with a dot as asha.owner. A tip bar says __init__ sets up each new object, and self means &amp;quot;this object&amp;quot;." width="800" height="637"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3.&lt;/strong&gt; &lt;code&gt;__init__&lt;/code&gt; &lt;strong&gt;sets up an object’s data, and&lt;/strong&gt; &lt;code&gt;self&lt;/code&gt; &lt;strong&gt;means “this object”.&lt;/strong&gt; An empty cookie isn’t much use. Most classes have a special method called &lt;code&gt;__init__&lt;/code&gt; (two underscores each side) that runs &lt;strong&gt;every time&lt;/strong&gt; you make an object. Save &lt;code&gt;piggy.py&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;PiggyBank&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;__init__&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;owner&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;balance&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;owner&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;owner&lt;/span&gt;
        &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;balance&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;balance&lt;/span&gt;

&lt;span class="n"&gt;asha&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;PiggyBank&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Asha"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;ravi&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;PiggyBank&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Ravi"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;50&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;asha&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;owner&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;asha&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;balance&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;ravi&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;owner&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;ravi&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;balance&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="nc"&gt;Asha&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;
&lt;span class="nc"&gt;Ravi&lt;/span&gt; &lt;span class="mi"&gt;50&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When you write &lt;code&gt;PiggyBank("Asha")&lt;/code&gt;, Python makes a fresh, empty object, then calls &lt;code&gt;__init__&lt;/code&gt; with that object as the first argument, &lt;code&gt;self&lt;/code&gt;, and &lt;code&gt;"Asha"&lt;/code&gt; as &lt;code&gt;owner&lt;/code&gt;. You never pass &lt;code&gt;self&lt;/code&gt; yourself; Python does it.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;self.owner = owner&lt;/code&gt; stores the value &lt;strong&gt;on that object&lt;/strong&gt;. Values stored this way are called &lt;strong&gt;attributes&lt;/strong&gt;, and you reach them with a dot: &lt;code&gt;asha.owner&lt;/code&gt;. Asha’s balance and Ravi’s balance are separate, because each object has its own &lt;code&gt;self&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Part B · Classes in practice
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fj9lvxm5g4ea4eq3wrlkw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fj9lvxm5g4ea4eq3wrlkw.png" alt="Diagram titled &amp;quot;Methods belong to a class&amp;quot;, subtitle: functions that use self to read and change the object. Left, inside class PiggyBank, under __init__: def deposit(self, amount) adds amount to self.balance; def withdraw(self, amount) raises ValueError(&amp;quot;not enough money&amp;quot;) if amount is more than self.balance, otherwise subtracts it; def describe(self) returns an f-string, owner has balance. Right, a method is a def in the class, whose first parameter is self so it can read and change this object's data; and a shorthand box: asha.deposit(30) means PiggyBank.deposit(asha, 30). Bottom, asha's balance step by step: PiggyBank(&amp;quot;Asha&amp;quot;) gives 0, .deposit(30) gives 30, .withdraw(10) gives 20, and .describe() returns &amp;quot;Asha has 20&amp;quot;. An orange note says .withdraw(100) raises ValueError: not enough money; the rule lives inside the class, next to the data it protects, as in issue 19. A tip bar says methods keep the rules for changing the data next to the data." width="800" height="652"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;4. Methods are functions that belong to a class.&lt;/strong&gt; A method is a &lt;code&gt;def&lt;/code&gt; inside the class. Its first parameter is always &lt;code&gt;self&lt;/code&gt;, so it can read and change &lt;strong&gt;this&lt;/strong&gt; object’s data. Add three to &lt;code&gt;piggy.py&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;PiggyBank&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;__init__&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;owner&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;balance&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;owner&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;owner&lt;/span&gt;
        &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;balance&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;balance&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;deposit&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;amount&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;balance&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="n"&gt;amount&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;withdraw&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;amount&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;amount&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;balance&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;raise&lt;/span&gt; &lt;span class="nc"&gt;ValueError&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"not enough money"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;balance&lt;/span&gt; &lt;span class="o"&gt;-=&lt;/span&gt; &lt;span class="n"&gt;amount&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;describe&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"{self.owner} has {self.balance}"&lt;/span&gt;

&lt;span class="n"&gt;asha&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;PiggyBank&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Asha"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;asha&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;deposit&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;30&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;asha&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;withdraw&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;asha&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;describe&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;asha&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;withdraw&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;100&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="nc"&gt;Asha&lt;/span&gt; &lt;span class="n"&gt;has&lt;/span&gt; &lt;span class="mi"&gt;20&lt;/span&gt;
&lt;span class="nc"&gt;Traceback&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;most&lt;/span&gt; &lt;span class="n"&gt;recent&lt;/span&gt; &lt;span class="n"&gt;call&lt;/span&gt; &lt;span class="n"&gt;last&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
  &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;
&lt;span class="nc"&gt;ValueError&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="n"&gt;enough&lt;/span&gt; &lt;span class="n"&gt;money&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The balance goes 0, then 30, then 20. The last line asks for more than there is, so &lt;code&gt;withdraw&lt;/code&gt; raises the error you learned to write in #19. The rule “you can’t take out more than you have” now lives &lt;strong&gt;inside&lt;/strong&gt; the class, next to the data it protects, instead of being repeated everywhere a balance changes.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;asha.deposit(30)&lt;/code&gt; is shorthand for &lt;code&gt;PiggyBank.deposit(asha, 30)&lt;/code&gt;. That’s where &lt;code&gt;self&lt;/code&gt; comes from.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F8zabmoputxi7wf2pqev5.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F8zabmoputxi7wf2pqev5.png" alt="Diagram titled &amp;quot;Dataclasses&amp;quot;, subtitle: same recipe, much less typing. Two columns. Left, a plain class Recipe with an __init__ taking name, servings and minutes=30 and three self lines; print(dal) shows &lt;__main__.Recipe object at 0x...&gt;, and comparing two equal-looking recipes with == gives False. Right, from dataclasses import dataclass, then @dataclass above class Recipe with three fields, name: str, servings: int and minutes: int = 30; print(dal) shows Recipe(name='Dal', servings=4, minutes=40), and == gives True. Three cards below: writes for you, __init__, a readable printout and == that compares fields; name: str is a field, a name plus a type hint, and hints are labels that Python doesn't check; a list default, tags: list = (), fails with &amp;quot;mutable default ... use default_factory&amp;quot;, so write field(default_factory=list). A tip bar says for classes that mainly hold data, let @dataclass write the setup code." width="800" height="658"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;5.&lt;/strong&gt; &lt;code&gt;@dataclass&lt;/code&gt; &lt;strong&gt;writes the setup code for classes that mainly hold data.&lt;/strong&gt; Lots of classes are mostly a bundle of named values: a recipe, a book, a row from a JSON file. Writing &lt;code&gt;__init__&lt;/code&gt; with a &lt;code&gt;self.x = x&lt;/code&gt; line per value gets dull. Python’s &lt;code&gt;dataclasses&lt;/code&gt; module writes it for you:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="n"&gt;dataclasses&lt;/span&gt; &lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;dataclass&lt;/span&gt;

&lt;span class="nd"&gt;@dataclass&lt;/span&gt;
&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Recipe&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;str&lt;/span&gt;
    &lt;span class="n"&gt;servings&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt;
    &lt;span class="n"&gt;minutes&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;30&lt;/span&gt;

&lt;span class="n"&gt;dal&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Recipe&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Dal"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;40&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;dal&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;dal&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;minutes&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;dal&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="nc"&gt;Recipe&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Dal"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;40&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Recipe&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Rice"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="nc"&gt;Recipe&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s1"&gt;'Dal'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;servings&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;minutes&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;40&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="mi"&gt;40&lt;/span&gt;
&lt;span class="kc"&gt;True&lt;/span&gt;
&lt;span class="nc"&gt;Recipe&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s1"&gt;'Rice'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;servings&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;minutes&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;30&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;@dataclass&lt;/code&gt; is a &lt;strong&gt;decorator&lt;/strong&gt;: a line starting with &lt;code&gt;@&lt;/code&gt; that adds features to whatever sits under it. Each line like &lt;code&gt;name: str&lt;/code&gt; is a &lt;strong&gt;field&lt;/strong&gt;: a name plus a type hint (#14). &lt;code&gt;minutes: int = 30&lt;/code&gt; gives a default. From these lines, the decorator writes three things for you:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;an &lt;code&gt;__init__&lt;/code&gt; that takes the fields in order;&lt;/li&gt;
&lt;li&gt;a readable printout, &lt;code&gt;Recipe(name='Dal', ...)&lt;/code&gt;, instead of something like &lt;code&gt;&amp;lt;__main__.Recipe object at 0x...&amp;gt;&lt;/code&gt;;&lt;/li&gt;
&lt;li&gt;an &lt;code&gt;==&lt;/code&gt; that compares the fields. A plain class with the same values compares as &lt;code&gt;False&lt;/code&gt;, because it only checks “same object?”.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The type hints are labels for you and your editor. Python doesn’t check them: &lt;code&gt;Recipe("Dal", "four")&lt;/code&gt; still runs. (Pydantic, later in this series, does check them.)&lt;/p&gt;

&lt;p&gt;Dataclasses can have methods too:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="n"&gt;dataclasses&lt;/span&gt; &lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;dataclass&lt;/span&gt;

&lt;span class="nd"&gt;@dataclass&lt;/span&gt;
&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Recipe&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;str&lt;/span&gt;
    &lt;span class="n"&gt;servings&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt;
    &lt;span class="n"&gt;minutes&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;30&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;per_serving&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nb"&gt;round&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;minutes&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;servings&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;scaled&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;people&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nc"&gt;Recipe&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;people&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;minutes&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="n"&gt;dal&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Recipe&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Dal"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;40&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;dal&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;per_serving&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;dal&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;scaled&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;8&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="mf"&gt;10.0&lt;/span&gt;
&lt;span class="nc"&gt;Recipe&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s1"&gt;'Dal'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;servings&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;8&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;minutes&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;40&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;One trap: a list as a default. &lt;code&gt;tags: list = []&lt;/code&gt; fails straight away with &lt;code&gt;ValueError: mutable default &amp;lt;class 'list'&amp;gt; for field tags is not allowed: use default_factory&lt;/code&gt;. Python is protecting you from every recipe sharing &lt;strong&gt;one&lt;/strong&gt; list. Write &lt;code&gt;tags: list = field(default_factory=list)&lt;/code&gt; instead (import &lt;code&gt;field&lt;/code&gt; next to &lt;code&gt;dataclass&lt;/code&gt;), and each recipe gets its own empty list.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F06yr4738r4u7gw9sgwuw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F06yr4738r4u7gw9sgwuw.png" alt="Diagram titled &amp;quot;When to use a class&amp;quot;, subtitle: three questions, three answers. Each question has an arrow to its answer. 1, data that changes, plus actions that go with it, like a balance and the rules for changing it: a class, for example PiggyBank. 2, mainly named data, like a recipe, a book or a row from a JSON file: a dataclass, for example Recipe. 3, just inputs in, an answer out, with nothing to remember between calls: a function, for example c_to_f(celsius). Bottom left, an orange warning card, a function in disguise: class Adder with one method, add(self, a, b), returning a + b, with no data and one method. Bottom right, a green card, just write the function: def add(a, b) returning a + b, the same job with less to read. A tip bar says start with functions, and reach for a class when you keep passing the same values around." width="800" height="601"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;6. Use a class for things with state and behaviour. A plain function is fine otherwise.&lt;/strong&gt; “State” means data that changes over time, like a balance. Ask three questions:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Data that changes, plus actions that go with it?&lt;/strong&gt; A class. &lt;code&gt;PiggyBank&lt;/code&gt; has a balance and the rules for changing it.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Mainly named data?&lt;/strong&gt; A dataclass. &lt;code&gt;Recipe&lt;/code&gt; is a labelled bundle with a helper or two.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Just inputs in, answer out?&lt;/strong&gt; A function. &lt;code&gt;c_to_f(celsius)&lt;/code&gt; from #20 needs no class:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;c_to_f&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;celsius&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;celsius&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="mi"&gt;9&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="mi"&gt;5&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;32&lt;/span&gt;

&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;c_to_f&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;30&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="mf"&gt;86.0&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A good sign you need a class: you keep passing the same three or four values into every function. A good sign you don’t: your class has only &lt;code&gt;__init__&lt;/code&gt; and one method, or no data at all. Start with functions. Reach for a class when the code asks for one.&lt;/p&gt;




&lt;h3&gt;
  
  
  Try it (15 minutes)
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;In your &lt;code&gt;sandbox&lt;/code&gt; folder, create &lt;code&gt;books.py&lt;/code&gt;:
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="n"&gt;dataclasses&lt;/span&gt; &lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;dataclass&lt;/span&gt;

&lt;span class="nd"&gt;@dataclass&lt;/span&gt;
&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Book&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;title&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;str&lt;/span&gt;
    &lt;span class="n"&gt;author&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;str&lt;/span&gt;
    &lt;span class="n"&gt;pages&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt;
    &lt;span class="n"&gt;pages_read&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;read&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;pages_read&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;min&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;pages&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;pages_read&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;progress&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"{self.title}: {self.pages_read}/{self.pages} pages ({self.pages_read / self.pages:.0%})"&lt;/span&gt;

&lt;span class="n"&gt;book&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Book&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"The Tiny Robot"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"A. Writer"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;120&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;book&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;book&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;read&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;30&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;book&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;progress&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;book&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;read&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;200&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;book&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;progress&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;Run &lt;code&gt;python3 books.py&lt;/code&gt;. You should see:
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="nc"&gt;Book&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;title&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s1"&gt;'The Tiny Robot'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;author&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s1"&gt;'A. Writer'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;pages&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;120&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;pages_read&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="nc"&gt;The&lt;/span&gt; &lt;span class="nc"&gt;Tiny&lt;/span&gt; &lt;span class="nc"&gt;Robot&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;30&lt;/span&gt;&lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="mi"&gt;120&lt;/span&gt; &lt;span class="n"&gt;pages&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;25&lt;/span&gt;&lt;span class="o"&gt;%&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="nc"&gt;The&lt;/span&gt; &lt;span class="nc"&gt;Tiny&lt;/span&gt; &lt;span class="nc"&gt;Robot&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;120&lt;/span&gt;&lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="mi"&gt;120&lt;/span&gt; &lt;span class="n"&gt;pages&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;100&lt;/span&gt;&lt;span class="o"&gt;%&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;min(...)&lt;/code&gt; stops &lt;code&gt;pages_read&lt;/code&gt; going past the last page, and &lt;code&gt;:.0%&lt;/code&gt; (an f-string format) shows a fraction as a whole-number percentage.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Make a second book and read some of it. Check that the first book’s progress didn’t change: each object has its own data.&lt;/li&gt;
&lt;li&gt;Add a method &lt;code&gt;is_finished(self)&lt;/code&gt; that returns &lt;code&gt;True&lt;/code&gt; when every page is read. Print it before and after the big &lt;code&gt;read(200)&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Delete &lt;code&gt;self&lt;/code&gt; from &lt;code&gt;def read(self, n):&lt;/code&gt; and run it again. Read the error (it’s in the mistakes below), then put &lt;code&gt;self&lt;/code&gt; back.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Check your understanding:&lt;/strong&gt; (a) What’s the difference between a class and an object? (b) What is &lt;code&gt;self&lt;/code&gt; inside a method? (c) Name two things &lt;code&gt;@dataclass&lt;/code&gt; writes for you.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Answer: (a) A class is the blueprint; an object is one thing made from it by calling the class, like&lt;/em&gt; &lt;code&gt;Book(...)&lt;/code&gt;&lt;em&gt;. (b) The object the method was called on: in&lt;/em&gt; &lt;code&gt;book.read(30)&lt;/code&gt;&lt;em&gt;,&lt;/em&gt; &lt;code&gt;self&lt;/code&gt; &lt;em&gt;is&lt;/em&gt; &lt;code&gt;book&lt;/code&gt;&lt;em&gt;. (c) Any two of:&lt;/em&gt; &lt;code&gt;__init__&lt;/code&gt;&lt;em&gt;, a readable printout, and&lt;/em&gt; &lt;code&gt;==&lt;/code&gt; &lt;em&gt;that compares the fields.&lt;/em&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Common beginner mistakes
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Forgetting&lt;/strong&gt; &lt;code&gt;self&lt;/code&gt; &lt;strong&gt;in a method.&lt;/strong&gt; Write &lt;code&gt;def deposit(amount):&lt;/code&gt; and call &lt;code&gt;asha.deposit(30)&lt;/code&gt;, and Python passes two things (the object and 30) into a method that accepts one:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="nc"&gt;TypeError&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;PiggyBank&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;deposit&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="n"&gt;takes&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt; &lt;span class="n"&gt;positional&lt;/span&gt; &lt;span class="n"&gt;argument&lt;/span&gt; &lt;span class="n"&gt;but&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt; &lt;span class="n"&gt;were&lt;/span&gt; &lt;span class="n"&gt;given&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Read “takes 1 but 2 were given” in a method call as “I forgot &lt;code&gt;self&lt;/code&gt;“. - &lt;strong&gt;Forgetting&lt;/strong&gt; &lt;code&gt;self.&lt;/code&gt; &lt;strong&gt;in front of the data.&lt;/strong&gt; Inside a method, &lt;code&gt;balance += amount&lt;/code&gt; means a local variable called &lt;code&gt;balance&lt;/code&gt;, not the object’s. Python 3.13 says &lt;code&gt;UnboundLocalError: cannot access local variable 'balance' where it is not associated with a value&lt;/code&gt;. Write &lt;code&gt;self.balance&lt;/code&gt;. - &lt;strong&gt;Turning everything into a class.&lt;/strong&gt; A class with no data, or with one method, is usually a function in disguise: &lt;code&gt;class Adder&lt;/code&gt; with &lt;code&gt;def add(self, a, b)&lt;/code&gt; is just &lt;code&gt;def add(a, b)&lt;/code&gt;. - Forgetting the brackets: &lt;code&gt;asha = PiggyBank&lt;/code&gt; (no brackets) gives you the blueprint itself, not a new object. - A list default in a dataclass without &lt;code&gt;field(default_factory=list)&lt;/code&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  Takeaway
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;A class is a blueprint; calling it makes objects, each with its own data.&lt;/strong&gt; &lt;code&gt;__init__&lt;/code&gt; &lt;strong&gt;sets that data up,&lt;/strong&gt; &lt;code&gt;self&lt;/code&gt; &lt;strong&gt;means “this object”, and methods are functions that belong to the class.&lt;/strong&gt; &lt;code&gt;@dataclass&lt;/code&gt; &lt;strong&gt;writes&lt;/strong&gt; &lt;code&gt;__init__&lt;/code&gt;&lt;strong&gt;, a readable printout and&lt;/strong&gt; &lt;code&gt;==&lt;/code&gt; &lt;strong&gt;for classes that mainly hold data. Use a class for state plus behaviour, and a plain function for everything else.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Where this fits in my roadmap:&lt;/strong&gt; this is the last new building block of my Python on-ramp. AI code is full of classes you’ll use rather than write: HTTP clients, model SDK clients, and data models that check their fields. Knowing what an object, an attribute and a method are makes all of them readable. Next issue: &lt;strong&gt;a one-page Python cheat sheet&lt;/strong&gt;, with every piece from this section in one small program.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Over to you:&lt;/strong&gt; what’s the first thing you’d model as a class? Reply with one line (nothing private).&lt;/p&gt;




&lt;h3&gt;
  
  
  Sources
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;Python tutorial, “Classes” (”Classes provide a means of bundling data and functionality together”; class definitions, class objects, instance objects; the &lt;code&gt;__init__()&lt;/code&gt; method; “the instance object is passed as the first argument of the function”). &lt;a href="https://docs.python.org/3/tutorial/classes.html" rel="noopener noreferrer"&gt;https://docs.python.org/3/tutorial/classes.html&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Python tutorial, “Classes”, Random Remarks (”Often, the first argument of a method is called &lt;code&gt;self&lt;/code&gt;. This is nothing more than a convention”). &lt;a href="https://docs.python.org/3/tutorial/classes.html#random-remarks" rel="noopener noreferrer"&gt;https://docs.python.org/3/tutorial/classes.html#random-remarks&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Python docs, “&lt;code&gt;dataclasses&lt;/code&gt; — Data Classes” (&lt;code&gt;@dataclass&lt;/code&gt; adds generated methods such as &lt;code&gt;__init__()&lt;/code&gt;, &lt;code&gt;__repr__()&lt;/code&gt; and &lt;code&gt;__eq__()&lt;/code&gt;; fields with defaults; mutable default values and &lt;code&gt;default_factory&lt;/code&gt;). &lt;a href="https://docs.python.org/3/library/dataclasses.html" rel="noopener noreferrer"&gt;https://docs.python.org/3/library/dataclasses.html&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;PEP 557, “Data Classes” (the design and reasons behind dataclasses). &lt;a href="https://peps.python.org/pep-0557/" rel="noopener noreferrer"&gt;https://peps.python.org/pep-0557/&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Python docs, “Built-in Functions” (&lt;code&gt;isinstance()&lt;/code&gt;, &lt;code&gt;type()&lt;/code&gt;, &lt;code&gt;min()&lt;/code&gt;). &lt;a href="https://docs.python.org/3/library/functions.html" rel="noopener noreferrer"&gt;https://docs.python.org/3/library/functions.html&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;PEP 8, “Style Guide for Python Code”, Class Names (”Class names should normally use the CapWords convention”). &lt;a href="https://peps.python.org/pep-0008/#class-names" rel="noopener noreferrer"&gt;https://peps.python.org/pep-0008/#class-names&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Python glossary (”object”, “decorator”, “method”). &lt;a href="https://docs.python.org/3/glossary.html" rel="noopener noreferrer"&gt;https://docs.python.org/3/glossary.html&lt;/a&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;em&gt;All examples are made up and were run with Python 3.13 on Nov 2, 2026. Error messages are from Python 3.13; other versions word some of them differently. Sources checked Nov 2, 2026.&lt;/em&gt;&lt;/p&gt;




&lt;p&gt;Free: &lt;a href="https://dhanushkumarsivaji.substack.com/p/the-path-to-ai-fde-the-free-roadmap" rel="noopener noreferrer"&gt;the 5-page roadmap from Novice to AI FDE&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;If this was useful, &lt;a href="https://dhanushkumarsivaji.substack.com/subscribe" rel="noopener noreferrer"&gt;subscribe to The Path to AI FDE&lt;/a&gt; for the next issue.&lt;/p&gt;

</description>
      <category>python</category>
      <category>beginners</category>
      <category>programming</category>
      <category>oop</category>
    </item>
    <item>
      <title>The path to AI FDE #18: Strings, files and JSON: reading and writing data</title>
      <dc:creator>Dhanush Kumar Sivaji</dc:creator>
      <pubDate>Thu, 19 Nov 2026 06:52:24 +0000</pubDate>
      <link>https://dev.to/dhanushkumarsivaji/the-path-to-ai-fde-18-strings-files-and-json-reading-and-writing-data-2kne</link>
      <guid>https://dev.to/dhanushkumarsivaji/the-path-to-ai-fde-18-strings-files-and-json-reading-and-writing-data-2kne</guid>
      <description>&lt;p&gt;&lt;em&gt;Originally published on my newsletter, The Path to AI FDE. &lt;a href="https://dhanushkumarsivaji.substack.com/subscribe" rel="noopener noreferrer"&gt;Subscribe free&lt;/a&gt; to get each issue by email.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;This is a &lt;strong&gt;“From Zero” issue&lt;/strong&gt;. Yesterday you held data in lists and dictionaries. But that data vanished the moment your script ended. Today you &lt;strong&gt;save it to a file and read it back&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Most of an AI engineer’s day is text: cleaning it, putting it into prompts, reading it from files, and passing JSON back and forth. So today covers the three tools for that: &lt;strong&gt;strings&lt;/strong&gt;, &lt;strong&gt;files&lt;/strong&gt; and &lt;strong&gt;JSON&lt;/strong&gt;. By the end you’ll have a script that tidies a messy, made-up shopping list and saves it as JSON.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fu3kf8q2qz2wpqs5dp5is.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fu3kf8q2qz2wpqs5dp5is.png" alt="Cover card titled &amp;quot;Strings, files and JSON, from Zero&amp;quot; for issue 18 of The Path to AI FDE by Dhanush Kumar Sivaji. Subtitle: text in, text out, saved and read back. Six numbered cards in two lanes. Part A, strings: 1, f-strings, shown as f&amp;quot;{name} ordered {cups} cups&amp;quot;: values inside text, the start of every prompt template; 2, string methods, shown as .strip(), .lower(), .split() and .join(): clean text, and each returns a new string, with a warning that s.strip() alone changes nothing. Part B, files and JSON: 3, with open(), shown as with open(p, encoding=&amp;quot;utf-8&amp;quot;): read or write, then closed for you, with a warning that a missing file gives FileNotFoundError; 4, pathlib, shown as here / &amp;quot;notes&amp;quot; leading to .glob(&amp;quot;*.txt&amp;quot;): paths that work on any computer; 5, JSON in and out, shown as json.loads and json.dumps converting to and from a dict: text to Python data and back, and without the s, files; 6, encoding=&amp;quot;utf-8&amp;quot;: write and read with the same table, every time, or café turns into cafÃ©. A tip bar says methods return new strings, and always say encoding=&amp;quot;utf-8&amp;quot;." width="800" height="708"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  Part A · Strings
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fdfigtisbtmn8n525s2z5.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fdfigtisbtmn8n525s2z5.png" alt="Diagram titled &amp;quot;f-strings put values inside text&amp;quot;, subtitle: an f before the quotes, and each {name} becomes its value. Top: with name = &amp;quot;Asha&amp;quot; and cups = 2, the text f&amp;quot;{name} ordered {cups} cups&amp;quot; has its two highlighted gaps filled, and an arrow leads to Asha ordered 2 cups. Left, sums and formats: cups = 2, price = 1.5, print(f&amp;quot;Total: {cups * price}&amp;quot;) and print(f&amp;quot;Price: {price:.2f}&amp;quot;) print Total: 3.0 and Price: 1.50; :.2f means 2 decimal places. Right, a toy prompt template: n = 10, text = &amp;quot;The cat sat on the mat.&amp;quot;, prompt = f&amp;quot;Summarise this in {n} words: {text}&amp;quot; and print(prompt) print Summarise this in 10 words: The cat sat on the mat., wrapped in the figure but printed on one line. Bottom, forgot the f: print(&amp;quot;Asha ordered {cups} cups&amp;quot;) prints Asha ordered {cups} cups, no error, just the braces as they are. A tip bar says f before the quote, names in curly braces: that's a prompt template." width="800" height="818"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. f-strings put values inside text.&lt;/strong&gt; Put an &lt;code&gt;f&lt;/code&gt; just before the opening quote, and anything inside curly braces &lt;code&gt;{ }&lt;/code&gt; is replaced by its value. Save this as &lt;code&gt;fstrings.py&lt;/code&gt; in your &lt;code&gt;sandbox&lt;/code&gt; folder:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="n"&gt;name&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"Asha"&lt;/span&gt;
&lt;span class="n"&gt;cups&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;
&lt;span class="n"&gt;price&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mf"&gt;1.5&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"{name} ordered {cups} cups"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"Total: {cups * price}"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"Price: {price:.2f}"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="n"&gt;n&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;10&lt;/span&gt;
&lt;span class="n"&gt;text&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"The cat sat on the mat."&lt;/span&gt;
&lt;span class="n"&gt;prompt&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"Summarise this in {n} words: {text}"&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;prompt&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Run it with &lt;code&gt;python3 fstrings.py&lt;/code&gt; (Windows: &lt;code&gt;python fstrings.py&lt;/code&gt;):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="nc"&gt;Asha&lt;/span&gt; &lt;span class="n"&gt;ordered&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt; &lt;span class="n"&gt;cups&lt;/span&gt;
&lt;span class="nc"&gt;Total&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mf"&gt;3.0&lt;/span&gt;
&lt;span class="nc"&gt;Price&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mf"&gt;1.50&lt;/span&gt;
&lt;span class="nc"&gt;Summarise&lt;/span&gt; &lt;span class="n"&gt;this&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="mi"&gt;10&lt;/span&gt; &lt;span class="n"&gt;words&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;The&lt;/span&gt; &lt;span class="n"&gt;cat&lt;/span&gt; &lt;span class="n"&gt;sat&lt;/span&gt; &lt;span class="n"&gt;on&lt;/span&gt; &lt;span class="n"&gt;the&lt;/span&gt; &lt;span class="n"&gt;mat&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The braces can hold a name or a small calculation, such as &lt;code&gt;{cups * price}&lt;/code&gt;. Add a colon and a &lt;strong&gt;format&lt;/strong&gt; after it to control how a value looks: &lt;code&gt;:.2f&lt;/code&gt; means “a number with 2 decimal places”, so 1.5 shows as &lt;code&gt;1.50&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The last example is a toy &lt;strong&gt;prompt template&lt;/strong&gt;: a fixed sentence with gaps for values. Later in the series, you’ll build prompts for AI models in exactly this way. Forget the &lt;code&gt;f&lt;/code&gt; and Python prints the braces as they are: &lt;code&gt;Asha ordered {cups} cups&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fwk13kd7ffbnsx8uqgsxo.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fwk13kd7ffbnsx8uqgsxo.png" alt="Diagram titled &amp;quot;String methods clean up text&amp;quot;, subtitle: strip, lower, replace, split and join, most cleaning jobs. Top, raw = &amp;quot; Hello, World! &amp;quot; with shaded spaces at both ends: raw.strip() gives &amp;quot;Hello, World!&amp;quot;; raw.strip().lower() gives &amp;quot;hello, world!&amp;quot;; raw.replace(&amp;quot;World&amp;quot;, &amp;quot;Python&amp;quot;) gives &amp;quot; Hello, Python! &amp;quot; with the spaces still there. Chains read left to right: strip first, then lower. Bottom left, split cuts and join glues: words = &amp;quot;tea,milk,sugar&amp;quot;.split(&amp;quot;,&amp;quot;), print(words) and print(&amp;quot; + &amp;quot;.join(words)) print ('tea', 'milk', 'sugar') and tea + milk + sugar. Bottom right, strings never change: raw = &amp;quot; Hello, World! &amp;quot;, then raw.strip() on its own line, then print(raw) still prints the spaces; the method returned a new string and nobody kept it, so write clean = raw.strip(). A tip bar says every string method returns a new string, so keep the result." width="800" height="650"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. String methods clean up text.&lt;/strong&gt; A &lt;strong&gt;method&lt;/strong&gt; is a function that belongs to a value, called with a dot. Strings come with dozens. These five cover most cleaning jobs:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="n"&gt;raw&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"  Hello, World!  "&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;raw&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;strip&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;raw&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;strip&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;lower&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;raw&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;replace&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"World"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"Python"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;words&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"tea,milk,sugar"&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;split&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;","&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;words&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;" + "&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;join&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;words&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;raw&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="nc"&gt;Hello&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;World&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;
&lt;span class="n"&gt;hello&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;world&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;
  &lt;span class="nc"&gt;Hello&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Python&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;  
&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'tea'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'milk'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'sugar'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;span class="n"&gt;tea&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;milk&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;sugar&lt;/span&gt;
  &lt;span class="nc"&gt;Hello&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;World&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;.strip()&lt;/code&gt; removes spaces (and newlines) from both ends.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;.lower()&lt;/code&gt; makes it all lowercase, handy before comparing text. &lt;code&gt;.upper()&lt;/code&gt; does the opposite.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;.replace(old, new)&lt;/code&gt; swaps every match.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;.split(",")&lt;/code&gt; cuts a string into a &lt;strong&gt;list&lt;/strong&gt; at each comma. With no argument, &lt;code&gt;.split()&lt;/code&gt; cuts at any run of spaces.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;" + ".join(words)&lt;/code&gt; does the reverse: it glues a list of strings into one, with &lt;code&gt;" + "&lt;/code&gt; between them.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;You can &lt;strong&gt;chain&lt;/strong&gt; methods, read left to right: &lt;code&gt;raw.strip().lower()&lt;/code&gt; strips first, then lowercases. And notice the last line: &lt;code&gt;raw&lt;/code&gt; still has its spaces. &lt;strong&gt;Strings never change.&lt;/strong&gt; Each method hands back a &lt;strong&gt;new&lt;/strong&gt; string, so keep the result: &lt;code&gt;clean = raw.strip()&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Part B · Files and JSON
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Ftj2g6dhxbt1wvjwq29qn.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Ftj2g6dhxbt1wvjwq29qn.png" alt="Diagram titled &amp;quot;with open() reads and writes files&amp;quot;, subtitle: open, use, and closed automatically when the block ends. Top left, write, and Python closes it for you: with open(&amp;quot;note.txt&amp;quot;, &amp;quot;w&amp;quot;, encoding=&amp;quot;utf-8&amp;quot;) as f: then f.write(&amp;quot;first line\n&amp;quot;) and f.write(&amp;quot;second line\n&amp;quot;), with a comment that the file is closed here; below, the file note.txt holds first line and second line. Top right, the mode: &amp;quot;r&amp;quot; read, the default; &amp;quot;w&amp;quot; write, which wipes the file first; &amp;quot;a&amp;quot; append, add to the end; the block ends and the file closes, even after an error. Middle left, read it all: f.read() then print(text.splitlines()) prints ('first line', 'second line'). Middle right, one line at a time: for line in f: print(line.strip().upper()) prints FIRST LINE and SECOND LINE. Bottom, no such file: open(&amp;quot;missing.txt&amp;quot;, encoding=&amp;quot;utf-8&amp;quot;) gives FileNotFoundError: (Errno 2) No such file or directory: 'missing.txt'. A tip bar says with open(...) as f: opens, you work, it closes, every time." width="800" height="782"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3.&lt;/strong&gt; &lt;code&gt;with open(...)&lt;/code&gt; &lt;strong&gt;reads and writes files, and closes them for you.&lt;/strong&gt; Here’s how to write a small file, then read it back two ways:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;with&lt;/span&gt; &lt;span class="nb"&gt;open&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"note.txt"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"w"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;encoding&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"utf-8"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;write&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"first line\n"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;write&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"second line\n"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="k"&gt;with&lt;/span&gt; &lt;span class="nb"&gt;open&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"note.txt"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;encoding&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"utf-8"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;text&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;read&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;text&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;splitlines&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="k"&gt;with&lt;/span&gt; &lt;span class="nb"&gt;open&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"note.txt"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;encoding&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"utf-8"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;line&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;line&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;strip&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;upper&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'first line'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'second line'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;span class="no"&gt;FIRST&lt;/span&gt; &lt;span class="no"&gt;LINE&lt;/span&gt;
&lt;span class="no"&gt;SECOND&lt;/span&gt; &lt;span class="no"&gt;LINE&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;open()&lt;/code&gt; takes the file name, a &lt;strong&gt;mode&lt;/strong&gt;, and an encoding (point 6). The mode &lt;code&gt;"w"&lt;/code&gt; means write, and it &lt;strong&gt;replaces&lt;/strong&gt; anything already in the file. &lt;code&gt;"a"&lt;/code&gt; adds to the end. Leave the mode out and it reads (&lt;code&gt;"r"&lt;/code&gt;). &lt;code&gt;\n&lt;/code&gt; is the newline character, the end of a line.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;with&lt;/code&gt; line opens the file and names it &lt;code&gt;f&lt;/code&gt;. When the indented block ends, Python &lt;strong&gt;closes the file for you&lt;/strong&gt;, even if an error happens halfway through. That’s why the Python tutorial recommends &lt;code&gt;with&lt;/code&gt;: a file left open can lose writes or stay locked.&lt;/p&gt;

&lt;p&gt;To read, &lt;code&gt;f.read()&lt;/code&gt; gives the whole file as one string, and &lt;code&gt;.splitlines()&lt;/code&gt; cuts it into a list of lines. Or loop over &lt;code&gt;f&lt;/code&gt; to get &lt;strong&gt;one line at a time&lt;/strong&gt;, which works even for huge files. Each line still ends with &lt;code&gt;\n&lt;/code&gt;, which is why we strip it.&lt;/p&gt;

&lt;p&gt;Open a file that doesn’t exist and you get:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="nc"&gt;FileNotFoundError&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nc"&gt;Errno&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="nc"&gt;No&lt;/span&gt; &lt;span class="n"&gt;such&lt;/span&gt; &lt;span class="n"&gt;file&lt;/span&gt; &lt;span class="ow"&gt;or&lt;/span&gt; &lt;span class="n"&gt;directory&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s1"&gt;'missing.txt'&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fs4f8ku1gl5ynat4mpr7f.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fs4f8ku1gl5ynat4mpr7f.png" alt="Diagram titled &amp;quot;Paths with pathlib&amp;quot;, subtitle: build addresses with a slash, and find files with glob. Left, the folder: sandbox holds script.py, marked as __file__, and a notes folder with a.txt and b.txt highlighted and c.md greyed out. Right, building paths: Path(__file__).parent gives sandbox/; here / &amp;quot;notes&amp;quot; gives sandbox/notes/; notes / &amp;quot;a.txt&amp;quot; gives the path to a.txt; the slash joins parts on Windows, macOS and Linux alike. Middle, glob finds files by pattern, where * means anything: for p in sorted(notes.glob(&amp;quot;*.txt&amp;quot;)): print(p.name, p.suffix, p.read_text(encoding=&amp;quot;utf-8&amp;quot;).strip()) prints a.txt .txt apple and b.txt .txt banana; c.md doesn't match *.txt, so it's skipped. Bottom, two warnings: a hard-coded path such as C:\Users\asha\Desktop\notes works on one computer only; a bare &amp;quot;note.txt&amp;quot; is looked for in the folder you ran the command from, not where the script is. A tip bar says start from Path(__file__).parent and the script works wherever the folder goes." width="800" height="763"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;4. Build paths with&lt;/strong&gt; &lt;code&gt;pathlib&lt;/code&gt;&lt;strong&gt;, and find files with&lt;/strong&gt; &lt;code&gt;glob&lt;/code&gt;&lt;strong&gt;.&lt;/strong&gt; A &lt;strong&gt;path&lt;/strong&gt; is a file’s address, like &lt;code&gt;sandbox/notes/a.txt&lt;/code&gt;. Python’s built-in &lt;code&gt;pathlib&lt;/code&gt; module handles paths for you:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="n"&gt;pathlib&lt;/span&gt; &lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="nc"&gt;Path&lt;/span&gt;

&lt;span class="n"&gt;here&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Path&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;__file__&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;
&lt;span class="n"&gt;notes&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;here&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="s2"&gt;"notes"&lt;/span&gt;
&lt;span class="n"&gt;notes&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;mkdir&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;exist_ok&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="kc"&gt;True&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;notes&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="s2"&gt;"a.txt"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;write_text&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"apple\n"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;encoding&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"utf-8"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;notes&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="s2"&gt;"b.txt"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;write_text&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"banana\n"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;encoding&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"utf-8"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;notes&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="s2"&gt;"c.md"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;write_text&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"# not a txt\n"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;encoding&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"utf-8"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;p&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;sorted&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;notes&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;glob&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"*.txt"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;p&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;p&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;suffix&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;p&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;read_text&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;encoding&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"utf-8"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;strip&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;notes&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="s2"&gt;"a.txt"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;exists&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;txt&lt;/span&gt; &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;txt&lt;/span&gt; &lt;span class="n"&gt;apple&lt;/span&gt;
&lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;txt&lt;/span&gt; &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;txt&lt;/span&gt; &lt;span class="n"&gt;banana&lt;/span&gt;
&lt;span class="kc"&gt;True&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Line by line:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;Path(__file__).parent&lt;/code&gt; is the folder this script lives in. (&lt;code&gt;__file__&lt;/code&gt; is the script’s own path.)&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;here / "notes"&lt;/code&gt; joins path parts with a slash. It works on Windows, macOS and Linux alike, so you never type &lt;code&gt;\&lt;/code&gt; or &lt;code&gt;/&lt;/code&gt; yourself.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;.mkdir(exist_ok=True)&lt;/code&gt; makes the folder, and doesn’t complain if it’s already there.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;.write_text()&lt;/code&gt; and &lt;code&gt;.read_text()&lt;/code&gt; write or read a whole file in one line, for small files.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;.glob("*.txt")&lt;/code&gt; finds every file whose name matches the pattern. &lt;code&gt;*&lt;/code&gt; means “anything”, so it finds &lt;code&gt;a.txt&lt;/code&gt; and &lt;code&gt;b.txt&lt;/code&gt; but skips &lt;code&gt;c.md&lt;/code&gt;. &lt;code&gt;sorted()&lt;/code&gt; puts them in a fixed order.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Why bother? Because a &lt;strong&gt;hard-coded path&lt;/strong&gt; like &lt;code&gt;C:\Users\asha\Desktop\notes&lt;/code&gt; only works on one computer. And a plain &lt;code&gt;"note.txt"&lt;/code&gt; is looked for in whatever folder you &lt;strong&gt;ran the command from&lt;/strong&gt;, so the same script can fail if you run it from somewhere else. Building paths from &lt;code&gt;Path(__file__).parent&lt;/code&gt; works wherever the folder ends up.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fhcwqqjsieg7gs4ez34p3.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fhcwqqjsieg7gs4ez34p3.png" alt="Diagram titled &amp;quot;JSON in and out&amp;quot;, subtitle: the json module converts both ways. Top: on the left, JSON text, a string, '{&amp;quot;name&amp;quot;: &amp;quot;Asha&amp;quot;, &amp;quot;cups&amp;quot;: 2, &amp;quot;milk&amp;quot;: true}'; on the right, Python data, a dict, {&amp;quot;name&amp;quot;: &amp;quot;Asha&amp;quot;, &amp;quot;cups&amp;quot;: 2, &amp;quot;milk&amp;quot;: True}; json.loads points from text to data, and json.dumps points back. The s in loads and dumps means string, and indent=2 makes the text easy to read. Bottom left, ready to use: order = json.loads(text), print(order(&amp;quot;cups&amp;quot;) + 1) and print(type(order)) print 3 and &lt;class 'dict'&gt;. Bottom right, without the s, files: json.dump(order, f, indent=2) inside a with block writing order.json, then json.load(f) reading it back into back, and print(back == order) prints True. Bottom, JSON wants double quotes: json.loads(&amp;quot;{'name': 'Asha'}&amp;quot;) gives json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1). A tip bar says loads and dumps for strings, load and dump for files." width="800" height="758"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;5. JSON in and out with&lt;/strong&gt; &lt;code&gt;json&lt;/code&gt;&lt;strong&gt;.&lt;/strong&gt; Yesterday you met JSON text. Python’s built-in &lt;code&gt;json&lt;/code&gt; module converts it both ways:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;json&lt;/span&gt;

&lt;span class="n"&gt;text&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s1"&gt;'{"name": "Asha", "cups": 2, "milk": true}'&lt;/span&gt;
&lt;span class="n"&gt;order&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;json&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;loads&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;text&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;order&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"cups"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kd"&gt;type&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;order&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="n"&gt;order&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"milk"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;False&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;json&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;dumps&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;order&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;json&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;dumps&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;order&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;indent&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="mi"&gt;3&lt;/span&gt;
&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="s1"&gt;'dict'&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;"name"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"Asha"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"cups"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"milk"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;false&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="s2"&gt;"name"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"Asha"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="s2"&gt;"cups"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="s2"&gt;"milk"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;false&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;json.loads(text)&lt;/code&gt; turns JSON &lt;strong&gt;text&lt;/strong&gt; into Python data: here, a dictionary you can use straight away. JSON’s &lt;code&gt;true&lt;/code&gt; becomes Python’s &lt;code&gt;True&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;json.dumps(data)&lt;/code&gt; turns Python data back into JSON &lt;strong&gt;text&lt;/strong&gt;. &lt;code&gt;indent=2&lt;/code&gt; spreads it over lines so people can read it.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The &lt;code&gt;s&lt;/code&gt; at the end of &lt;code&gt;loads&lt;/code&gt; and &lt;code&gt;dumps&lt;/code&gt; stands for &lt;strong&gt;string&lt;/strong&gt;. Their twins without the &lt;code&gt;s&lt;/code&gt;, &lt;code&gt;json.dump(data, f)&lt;/code&gt; and &lt;code&gt;json.load(f)&lt;/code&gt;, write straight to and read straight from an open file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;json&lt;/span&gt;

&lt;span class="n"&gt;order&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;"name"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"Asha"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"cups"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="k"&gt;with&lt;/span&gt; &lt;span class="nb"&gt;open&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"order.json"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"w"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;encoding&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"utf-8"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;json&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;dump&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;order&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;indent&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="k"&gt;with&lt;/span&gt; &lt;span class="nb"&gt;open&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"order.json"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;encoding&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"utf-8"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;back&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;json&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;load&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;back&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;order&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="kc"&gt;True&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Save, then load, and you get back exactly what you saved. One gotcha: JSON needs &lt;strong&gt;double quotes&lt;/strong&gt;. &lt;code&gt;json.loads("{'name': 'Asha'}")&lt;/code&gt; fails with:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="n"&gt;json&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;decoder&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;JSONDecodeError&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;Expecting&lt;/span&gt; &lt;span class="nb"&gt;property&lt;/span&gt; &lt;span class="n"&gt;name&lt;/span&gt; &lt;span class="n"&gt;enclosed&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="n"&gt;double&lt;/span&gt; &lt;span class="n"&gt;quotes&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;line&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt; &lt;span class="n"&gt;column&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;char&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fpq4t3gtwk5v57gowkpt0.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fpq4t3gtwk5v57gowkpt0.png" alt="Diagram titled &amp;quot;Always say encoding=&amp;quot;utf-8&amp;quot;&amp;quot;, subtitle: write and read with the same table, or text turns to junk. Top, files store bytes and an encoding maps characters to bytes: the word café as four character boxes; c, a and f are one byte each, 63, 61 and 66, and é is two bytes, C3 and A9, shown in hex; len(&amp;quot;café&amp;quot;) is 4 characters and len(&amp;quot;café&amp;quot;.encode(&amp;quot;utf-8&amp;quot;)) is 5 bytes. Middle, the same 5 bytes read two ways: with encoding=&amp;quot;utf-8&amp;quot; they read as café, in green; with encoding=&amp;quot;cp1252&amp;quot;, an old Windows encoding, they read as cafÃ©, in orange; with the wrong table, é's two bytes turn into two wrong characters. Bottom left, leave encoding out: before Python 3.15 the default depended on the computer, fine on one computer and garbled on another. Bottom right, the fix: always write encoding=&amp;quot;utf-8&amp;quot;, then the version and computer don't matter. A tip bar says UTF-8 covers every language and emoji, so say it every time." width="800" height="656"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;6. Always say&lt;/strong&gt; &lt;code&gt;encoding="utf-8"&lt;/code&gt;&lt;strong&gt;.&lt;/strong&gt; Files don’t store letters. They store &lt;strong&gt;bytes&lt;/strong&gt;, numbers from 0 to 255. An &lt;strong&gt;encoding&lt;/strong&gt; is the table that turns characters into bytes and back. &lt;strong&gt;UTF-8&lt;/strong&gt; is the one to use: it covers every language and emoji, and it’s what the web and JSON use.&lt;/p&gt;

&lt;p&gt;Here’s what happens when the write and the read disagree:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;with&lt;/span&gt; &lt;span class="nb"&gt;open&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"menu.txt"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"w"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;encoding&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"utf-8"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;write&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"café\n"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="k"&gt;with&lt;/span&gt; &lt;span class="nb"&gt;open&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"menu.txt"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;encoding&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"utf-8"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;read&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;strip&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="k"&gt;with&lt;/span&gt; &lt;span class="nb"&gt;open&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"menu.txt"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;encoding&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"cp1252"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;read&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;strip&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"café"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nb"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"café"&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;encode&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"utf-8"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="n"&gt;caf&lt;/span&gt;é
&lt;span class="n"&gt;caf&lt;/span&gt;Ã©
&lt;span class="mi"&gt;4&lt;/span&gt; &lt;span class="mi"&gt;5&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Read with the same encoding and you get &lt;code&gt;café&lt;/code&gt;. Read the very same bytes as &lt;code&gt;cp1252&lt;/code&gt;, an older Windows encoding, and you get the garbled &lt;code&gt;cafÃ©&lt;/code&gt;. The last line shows why: &lt;code&gt;é&lt;/code&gt; takes &lt;strong&gt;two bytes&lt;/strong&gt; in UTF-8, so the 4-character word is 5 bytes long. With the wrong table, those two bytes turn into two wrong characters.&lt;/p&gt;

&lt;p&gt;Why can this bite you? If you leave &lt;code&gt;encoding&lt;/code&gt; out, Python picks a default. Before Python 3.15, that default &lt;strong&gt;depended on the computer’s settings&lt;/strong&gt;, so the same script could read a file fine on a Mac and garble it on Windows. Python 3.15 changed the default to UTF-8, but you’ll meet older Pythons for years. So always write &lt;code&gt;encoding="utf-8"&lt;/code&gt; and it doesn’t matter.&lt;/p&gt;




&lt;h3&gt;
  
  
  Try it (15 minutes)
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;In your &lt;code&gt;sandbox&lt;/code&gt; folder, create a file called &lt;code&gt;groceries.txt&lt;/code&gt; with this made-up, messy list. Type it exactly, including the extra spaces, the capitals, the blank line and the repeated milk:
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;  &lt;span class="nc"&gt;Milk&lt;/span&gt; 
&lt;span class="no"&gt;EGGS&lt;/span&gt;

&lt;span class="n"&gt;bread&lt;/span&gt;  
&lt;span class="n"&gt;milk&lt;/span&gt;
&lt;span class="nc"&gt;Tomatoes&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;Next to it, create &lt;code&gt;tidy_list.py&lt;/code&gt;:
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;json&lt;/span&gt;
&lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="n"&gt;pathlib&lt;/span&gt; &lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="nc"&gt;Path&lt;/span&gt;

&lt;span class="n"&gt;here&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Path&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;__file__&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;
&lt;span class="n"&gt;raw&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;here&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="s2"&gt;"groceries.txt"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;read_text&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;encoding&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"utf-8"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="n"&gt;items&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;line&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="n"&gt;raw&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;splitlines&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;item&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;line&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;strip&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;lower&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;item&lt;/span&gt; &lt;span class="ow"&gt;and&lt;/span&gt; &lt;span class="n"&gt;item&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="n"&gt;items&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;items&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;item&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"Found {len(items)} items: {', '.join(items)}"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="n"&gt;out&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;here&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="s2"&gt;"groceries.json"&lt;/span&gt;
&lt;span class="n"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;write_text&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;json&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;dumps&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;items&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;indent&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;encoding&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"utf-8"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="n"&gt;back&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;json&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;loads&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;out&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;read_text&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;encoding&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"utf-8"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;back&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;back&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;items&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;Run &lt;code&gt;python3 tidy_list.py&lt;/code&gt;. You should see:
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="nc"&gt;Found&lt;/span&gt; &lt;span class="mi"&gt;4&lt;/span&gt; &lt;span class="n"&gt;items&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;milk&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;eggs&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;bread&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;tomatoes&lt;/span&gt;
&lt;span class="n"&gt;milk&lt;/span&gt; &lt;span class="kc"&gt;True&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;if item&lt;/code&gt; skips the blank line, because an empty string counts as &lt;code&gt;False&lt;/code&gt;. &lt;code&gt;item not in items&lt;/code&gt; skips the second milk. Open &lt;code&gt;groceries.json&lt;/code&gt; in VS Code to see the saved list.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Run it from a different folder, for example &lt;code&gt;cd ..&lt;/code&gt; and then &lt;code&gt;python3 sandbox/tidy_list.py&lt;/code&gt;. It still works, because the paths are built from &lt;code&gt;Path(__file__).parent&lt;/code&gt;. Now change the line to &lt;code&gt;raw = Path("groceries.txt").read_text(encoding="utf-8")&lt;/code&gt; and run it from the parent folder again: &lt;code&gt;FileNotFoundError&lt;/code&gt;. Change it back.&lt;/li&gt;
&lt;li&gt;Add a line to &lt;code&gt;groceries.txt&lt;/code&gt;, such as &lt;code&gt;Café au lait&lt;/code&gt;, run the script again, and check that the &lt;code&gt;é&lt;/code&gt; survives the trip to JSON. (In the file, &lt;code&gt;json.dumps&lt;/code&gt; writes it as &lt;code&gt;\u00e9&lt;/code&gt; unless you pass &lt;code&gt;ensure_ascii=False&lt;/code&gt;. Both load back as &lt;code&gt;é&lt;/code&gt;.)&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Check your understanding:&lt;/strong&gt; (a) What’s the difference between &lt;code&gt;json.loads&lt;/code&gt; and &lt;code&gt;json.load&lt;/code&gt;? (b) Why use &lt;code&gt;with&lt;/code&gt; to open a file? (c) After &lt;code&gt;s = " hi "&lt;/code&gt; and &lt;code&gt;s.strip()&lt;/code&gt;, what is &lt;code&gt;s&lt;/code&gt;?&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Answer: (a)&lt;/em&gt; &lt;code&gt;json.loads&lt;/code&gt; &lt;em&gt;reads JSON from a string;&lt;/em&gt; &lt;code&gt;json.load&lt;/code&gt; &lt;em&gt;reads it from an open file. (b) It closes the file for you when the block ends, even if an error happens. (c) Still&lt;/em&gt; &lt;code&gt;" hi "&lt;/code&gt;&lt;em&gt;. Strings never change;&lt;/em&gt; &lt;code&gt;s.strip()&lt;/code&gt; &lt;em&gt;returns a new string, so write&lt;/em&gt; &lt;code&gt;s = s.strip()&lt;/code&gt;&lt;em&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Common beginner mistakes
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Opening files without &lt;code&gt;with&lt;/code&gt;, and forgetting to close them.&lt;/li&gt;
&lt;li&gt;Hard-coding a path that only exists on your computer. Build it with &lt;code&gt;pathlib&lt;/code&gt; from &lt;code&gt;Path(__file__).parent&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Leaving out &lt;code&gt;encoding="utf-8"&lt;/code&gt;, then getting garbled text, or a &lt;code&gt;UnicodeDecodeError&lt;/code&gt;, on another computer.&lt;/li&gt;
&lt;li&gt;Calling &lt;code&gt;s.strip()&lt;/code&gt; and expecting &lt;code&gt;s&lt;/code&gt; to change. Keep the result.&lt;/li&gt;
&lt;li&gt;Opening a file with &lt;code&gt;"w"&lt;/code&gt; when you meant to add to it. &lt;code&gt;"w"&lt;/code&gt; wipes it first; &lt;code&gt;"a"&lt;/code&gt; appends.&lt;/li&gt;
&lt;li&gt;Writing JSON by hand with single quotes. Let &lt;code&gt;json.dumps&lt;/code&gt; write it.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Takeaway
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;f-strings put values into text. String methods (&lt;/strong&gt;&lt;code&gt;.strip()&lt;/code&gt;&lt;strong&gt;,&lt;/strong&gt; &lt;code&gt;.lower()&lt;/code&gt;&lt;strong&gt;,&lt;/strong&gt; &lt;code&gt;.split()&lt;/code&gt;&lt;strong&gt;,&lt;/strong&gt; &lt;code&gt;.replace()&lt;/code&gt;&lt;strong&gt;,&lt;/strong&gt; &lt;code&gt;.join()&lt;/code&gt;&lt;strong&gt;) return new strings, so keep the result.&lt;/strong&gt; &lt;code&gt;with open(path, encoding="utf-8")&lt;/code&gt; &lt;strong&gt;reads and writes files and closes them for you.&lt;/strong&gt; &lt;code&gt;pathlib&lt;/code&gt; &lt;strong&gt;builds paths that work on any computer, and&lt;/strong&gt; &lt;code&gt;glob&lt;/code&gt; &lt;strong&gt;finds files.&lt;/strong&gt; &lt;code&gt;json.loads&lt;/code&gt;&lt;strong&gt;/&lt;/strong&gt;&lt;code&gt;json.dumps&lt;/code&gt; &lt;strong&gt;convert JSON text, and&lt;/strong&gt; &lt;code&gt;json.load&lt;/code&gt;&lt;strong&gt;/&lt;/strong&gt;&lt;code&gt;json.dump&lt;/code&gt; &lt;strong&gt;work with files.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Where this fits in my roadmap:&lt;/strong&gt; this is part of my on-ramp, the Python basics everything else sits on. An AI app is mostly text plumbing: read files, clean the text, drop it into a prompt template, and parse JSON that comes back. Tomorrow: &lt;strong&gt;errors and exceptions&lt;/strong&gt;, so that when a file is missing or the JSON is broken, your script says why instead of just crashing.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Over to you:&lt;/strong&gt; what’s the messiest text file you’ve had to clean by hand? Reply with one line of it (nothing private), and the string method you’d use first.&lt;/p&gt;




&lt;h3&gt;
  
  
  Sources
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;Python tutorial, “Input and Output”, Formatted String Literals (f-strings, format specifiers such as &lt;code&gt;:.2f&lt;/code&gt;). &lt;a href="https://docs.python.org/3/tutorial/inputoutput.html#formatted-string-literals" rel="noopener noreferrer"&gt;https://docs.python.org/3/tutorial/inputoutput.html#formatted-string-literals&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Python docs, “Built-in Types”, String Methods (&lt;code&gt;str.strip&lt;/code&gt;, &lt;code&gt;str.lower&lt;/code&gt;, &lt;code&gt;str.split&lt;/code&gt;, &lt;code&gt;str.replace&lt;/code&gt;, &lt;code&gt;str.join&lt;/code&gt;; strings are immutable). &lt;a href="https://docs.python.org/3/builtins/stdtypes.html#string-methods" rel="noopener noreferrer"&gt;https://docs.python.org/3/builtins/stdtypes.html#string-methods&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Python tutorial, “Input and Output”, Reading and Writing Files (modes &lt;code&gt;"r"&lt;/code&gt;, &lt;code&gt;"w"&lt;/code&gt;, &lt;code&gt;"a"&lt;/code&gt;; “It is good practice to use the &lt;code&gt;with&lt;/code&gt; keyword”; specifying &lt;code&gt;encoding="utf-8"&lt;/code&gt;) and Methods of File Objects. &lt;a href="https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files" rel="noopener noreferrer"&gt;https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Python docs, “pathlib” (&lt;code&gt;Path&lt;/code&gt;, the &lt;code&gt;/&lt;/code&gt; operator, &lt;code&gt;Path.glob&lt;/code&gt;, &lt;code&gt;Path.read_text&lt;/code&gt;, &lt;code&gt;Path.write_text&lt;/code&gt;, &lt;code&gt;Path.mkdir&lt;/code&gt;, &lt;code&gt;Path.exists&lt;/code&gt;). &lt;a href="https://docs.python.org/3/library/pathlib.html" rel="noopener noreferrer"&gt;https://docs.python.org/3/library/pathlib.html&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Python docs, “json” (&lt;code&gt;json.loads&lt;/code&gt;, &lt;code&gt;json.dumps&lt;/code&gt;, &lt;code&gt;json.load&lt;/code&gt;, &lt;code&gt;json.dump&lt;/code&gt;, &lt;code&gt;indent&lt;/code&gt;, &lt;code&gt;ensure_ascii&lt;/code&gt;, &lt;code&gt;JSONDecodeError&lt;/code&gt;). &lt;a href="https://docs.python.org/3/library/json.html" rel="noopener noreferrer"&gt;https://docs.python.org/3/library/json.html&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Python docs, “Built-in Functions”, &lt;code&gt;open()&lt;/code&gt; (the default encoding; “Changed in version 3.15: UTF-8 is now the default encoding”). &lt;a href="https://docs.python.org/3/builtins/functions.html#open" rel="noopener noreferrer"&gt;https://docs.python.org/3/builtins/functions.html#open&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;PEP 686, “Make UTF-8 mode default” (status Final; the reason for the change). &lt;a href="https://peps.python.org/pep-0686/" rel="noopener noreferrer"&gt;https://peps.python.org/pep-0686/&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Python HOWTO, “Unicode HOWTO” (characters, bytes and encodings). &lt;a href="https://docs.python.org/3/howto/unicode.html" rel="noopener noreferrer"&gt;https://docs.python.org/3/howto/unicode.html&lt;/a&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;em&gt;All examples are made up and were run with Python 3.13 on Nov 2, 2026. Error messages are from Python 3.13; other versions word some of them differently. Sources checked Nov 2, 2026.&lt;/em&gt;&lt;/p&gt;




&lt;p&gt;Free: &lt;a href="https://dhanushkumarsivaji.substack.com/p/the-path-to-ai-fde-the-free-roadmap" rel="noopener noreferrer"&gt;the 5-page roadmap from Novice to AI FDE&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;If this was useful, &lt;a href="https://dhanushkumarsivaji.substack.com/subscribe" rel="noopener noreferrer"&gt;subscribe to The Path to AI FDE&lt;/a&gt; for the next issue.&lt;/p&gt;

</description>
      <category>python</category>
      <category>beginners</category>
      <category>programming</category>
      <category>json</category>
    </item>
    <item>
      <title>The path to AI FDE #17: Lists and dictionaries: holding many values</title>
      <dc:creator>Dhanush Kumar Sivaji</dc:creator>
      <pubDate>Wed, 18 Nov 2026 06:56:21 +0000</pubDate>
      <link>https://dev.to/dhanushkumarsivaji/the-path-to-ai-fde-17-lists-and-dictionaries-holding-many-values-23b1</link>
      <guid>https://dev.to/dhanushkumarsivaji/the-path-to-ai-fde-17-lists-and-dictionaries-holding-many-values-23b1</guid>
      <description>&lt;p&gt;&lt;em&gt;Originally published on my newsletter, The Path to AI FDE. &lt;a href="https://dhanushkumarsivaji.substack.com/subscribe" rel="noopener noreferrer"&gt;Subscribe free&lt;/a&gt; to get each issue by email.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;This is a &lt;strong&gt;“From Zero” issue&lt;/strong&gt;. Yesterday you wrapped code in functions. Today you learn to hold &lt;strong&gt;many values at once&lt;/strong&gt;, instead of one variable per value.&lt;/p&gt;

&lt;p&gt;Python has two containers you’ll use every day. A &lt;strong&gt;list&lt;/strong&gt; keeps things &lt;strong&gt;in order&lt;/strong&gt;, like a numbered queue. A &lt;strong&gt;dictionary&lt;/strong&gt; keeps things &lt;strong&gt;by name&lt;/strong&gt;, like a form with labelled boxes. Put them together, a list of dictionaries, and you get the exact shape of most data that AI tools send and receive. By the end you’ll have a small script that sums up a made-up playlist.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fa47xl1evza8ph2iegt0g.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fa47xl1evza8ph2iegt0g.png" alt="Cover card titled &amp;quot;Lists and dicts, from Zero&amp;quot; for issue 17 of The Path to AI FDE by Dhanush Kumar Sivaji. Subtitle: many values, one name, in order or by name. Six numbered cards in two lanes. Part A, lists: 1, lists from 0, shown as fruits = (&amp;quot;apple&amp;quot;, &amp;quot;banana&amp;quot;) where fruits(0) is &amp;quot;apple&amp;quot;: items in order and the first index is 0, with a warning that fruits(2) here gives IndexError; 2, change and read, shown as .append(5), len(), (1:3) and sorted(): add to the end, count, take a slice, sort; sorted() makes a new list, while .sort() changes the list itself. Part B, dictionaries and friends: 3, dictionaries, shown as book(&amp;quot;title&amp;quot;): values stored under unique keys, with a warning that a missing key gives KeyError; 4, .get and .items, shown as .get(&amp;quot;rating&amp;quot;) giving None: read safely and loop over key and value pairs; 5, tuples and sets, shown as (3, 4) and {&amp;quot;a&amp;quot;, &amp;quot;b&amp;quot;}: tuples are fixed and sets keep each value once; 6, lists of dicts, shown as books(1)(&amp;quot;title&amp;quot;): the shape of JSON, and of most AI data. A tip bar says lists count from 0, and dictionaries look up by key." width="800" height="777"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  Part A · Lists
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fyp0gq0oddde1w24pmppf.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fyp0gq0oddde1w24pmppf.png" alt="Diagram titled &amp;quot;A list keeps items in order&amp;quot;, subtitle: square brackets, commas, and counting from 0. The line fruits = (&amp;quot;apple&amp;quot;, &amp;quot;banana&amp;quot;, &amp;quot;cherry&amp;quot;) is drawn as a row of three blue boxes. Above each box is its index, 0, 1 and 2, counted from the start; below each is its negative index, -3, -2 and -1, counted from the end. A fourth dashed orange box at index 3 says nothing. Three cards below. Reading items: fruits(0) gives apple, fruits(2) gives cherry, fruits(-1) gives cherry, and len(fruits) gives 3. Length 3, last index 2: counting starts at 0, so the last index is always one less than the length, or just use (-1). One too far: fruits(3) gives IndexError: list index out of range, an off-by-one error. A tip bar says a list is a numbered row, and the first seat is number 0." width="800" height="603"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. A list keeps items in order, and counts from 0.&lt;/strong&gt; Make a list with square brackets and commas. Save this as &lt;code&gt;lists.py&lt;/code&gt; in your &lt;code&gt;sandbox&lt;/code&gt; folder:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="n"&gt;fruits&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"apple"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"banana"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"cherry"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;fruits&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;fruits&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;fruits&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;fruits&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Run it with &lt;code&gt;python3 lists.py&lt;/code&gt; (Windows: &lt;code&gt;python lists.py&lt;/code&gt;):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="n"&gt;apple&lt;/span&gt;
&lt;span class="n"&gt;cherry&lt;/span&gt;
&lt;span class="n"&gt;cherry&lt;/span&gt;
&lt;span class="mi"&gt;3&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Each item has a position number called an &lt;strong&gt;index&lt;/strong&gt;, and Python &lt;strong&gt;starts counting at 0&lt;/strong&gt;. So &lt;code&gt;fruits[0]&lt;/code&gt; is the first item and &lt;code&gt;fruits[2]&lt;/code&gt; is the third. A &lt;strong&gt;negative index counts from the end&lt;/strong&gt;: &lt;code&gt;fruits[-1]&lt;/code&gt; is always the last item. &lt;code&gt;len()&lt;/code&gt; tells you how many items there are.&lt;/p&gt;

&lt;p&gt;Because counting starts at 0, the last index is &lt;strong&gt;one less than the length&lt;/strong&gt;. Ask for &lt;code&gt;fruits[3]&lt;/code&gt; and you get:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="nc"&gt;IndexError&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;list&lt;/span&gt; &lt;span class="n"&gt;index&lt;/span&gt; &lt;span class="n"&gt;out&lt;/span&gt; &lt;span class="n"&gt;of&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That “one too far” slip is called an &lt;strong&gt;off-by-one error&lt;/strong&gt;. It’s the most common list mistake there is.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fomyy4ps7n7bqqxu1ghvd.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fomyy4ps7n7bqqxu1ghvd.png" alt="Diagram titled &amp;quot;Add, count, slice and sort&amp;quot;, subtitle: the four things you'll do to almost every list. Left, append adds to the end: scores = (7, 3, 9) as three numbered boxes, then scores.append(5) adds a highlighted fourth box, 5, at index 3, and len(scores) gives 4. Right, slicing takes a piece: scores(1:3) highlights the boxes at index 1 and 2, giving (3, 9), from 1 up to but not including 3; scores(:2) highlights the first two, giving (7, 3). Below, a green card, sorted() makes a new list: print(sorted(scores)) gives (3, 5, 7, 9), and print(scores) still gives (7, 3, 9, 5), so the original is left alone. A blue card, .sort() changes the list itself: scores.sort(reverse=True) then print(scores) gives (9, 7, 5, 3), with a warning that it returns None, so never write x = scores.sort(). A tip bar says want a sorted copy, use sorted(x); want to sort x itself, use x.sort()." width="800" height="701"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Add, count, slice and sort.&lt;/strong&gt; Lists can grow and change. Try this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="n"&gt;scores&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;7&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;9&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;span class="n"&gt;scores&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;scores&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;scores&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;scores&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;scores&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;sorted&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;scores&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;scores&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;scores&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;sort&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;reverse&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="kc"&gt;True&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;scores&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;7&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;9&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;span class="mi"&gt;4&lt;/span&gt;
&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;9&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;7&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;7&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;9&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;7&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;9&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;9&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;7&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Line by line:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;.append(5)&lt;/code&gt; adds one item to the &lt;strong&gt;end&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Slicing&lt;/strong&gt;, &lt;code&gt;scores[1:3]&lt;/code&gt;, gives a new list from index 1 &lt;strong&gt;up to but not including&lt;/strong&gt; index 3. Leave out the first number and it starts at the beginning, so &lt;code&gt;scores[:2]&lt;/code&gt; is the first two items.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;sorted(scores)&lt;/code&gt; gives back a &lt;strong&gt;new&lt;/strong&gt; sorted list and leaves the original alone, which is why the next line still prints &lt;code&gt;[7, 3, 9, 5]&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;.sort()&lt;/code&gt; sorts the list &lt;strong&gt;itself&lt;/strong&gt;. &lt;code&gt;reverse=True&lt;/code&gt; (a keyword argument, from yesterday) sorts from biggest to smallest.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;One trap: &lt;code&gt;.sort()&lt;/code&gt; changes the list and returns &lt;code&gt;None&lt;/code&gt;. So &lt;code&gt;result = scores.sort()&lt;/code&gt; leaves &lt;code&gt;result&lt;/code&gt; as &lt;code&gt;None&lt;/code&gt;. If you want a sorted copy, use &lt;code&gt;sorted()&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Part B · Dictionaries and friends
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F4nbinu5x36mjiqxmz2ol.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F4nbinu5x36mjiqxmz2ol.png" alt="Diagram titled &amp;quot;A dictionary stores values under keys&amp;quot;, subtitle: curly braces, and a key: value pair for each entry. Left, keys point to values: &amp;quot;title&amp;quot; points to &amp;quot;Moon Garden&amp;quot;, &amp;quot;author&amp;quot; to &amp;quot;A. Rao&amp;quot;, &amp;quot;year&amp;quot; to 2019, changed to 2020, and &amp;quot;pages&amp;quot; to 320, marked new; each key appears once, and setting it again replaces the value. Right, book.py: it creates the book dictionary, prints book(&amp;quot;title&amp;quot;), adds book(&amp;quot;pages&amp;quot;) = 320, sets book(&amp;quot;year&amp;quot;) = 2020 and prints the dictionary; the output is Moon Garden, then {'title': 'Moon Garden', 'author': 'A. Rao', 'year': 2020, 'pages': 320}; the keys stay in the order you added them. Bottom left, a missing key: print(book(&amp;quot;rating&amp;quot;)) gives KeyError: 'rating'. Bottom right, list or dictionary: a list uses fruits(2), &amp;quot;the third one&amp;quot;; a dict uses book(&amp;quot;title&amp;quot;), &amp;quot;the one called title&amp;quot;. A tip bar says a list looks things up by position, and a dictionary looks them up by name." width="800" height="658"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. A dictionary stores values under names, called keys.&lt;/strong&gt; Use curly braces, with a &lt;strong&gt;key&lt;/strong&gt;, a colon, and a &lt;strong&gt;value&lt;/strong&gt; for each entry:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="n"&gt;book&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;"title"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"Moon Garden"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"author"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"A. Rao"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"year"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;2019&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;book&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"title"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;book&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"pages"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;320&lt;/span&gt;
&lt;span class="n"&gt;book&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"year"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;2020&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;book&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;book&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="nc"&gt;Moon&lt;/span&gt; &lt;span class="nc"&gt;Garden&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s1"&gt;'title'&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s1"&gt;'Moon Garden'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'author'&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s1"&gt;'A. Rao'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'year'&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;2020&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'pages'&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;320&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="mi"&gt;4&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You look a value up &lt;strong&gt;by its key&lt;/strong&gt;, not by position: &lt;code&gt;book["title"]&lt;/code&gt;. Assigning to a new key, &lt;code&gt;book["pages"] = 320&lt;/code&gt;, adds an entry. Assigning to a key that already exists replaces its value, because &lt;strong&gt;each key appears only once&lt;/strong&gt;. And the dictionary remembers the order you added the keys.&lt;/p&gt;

&lt;p&gt;Ask for a key that isn’t there and Python stops with:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="nc"&gt;KeyError&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s1"&gt;'rating'&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A list is for “the third one”. A dictionary is for “the one called title”.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fq4igf5jranjmtd2w06ih.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fq4igf5jranjmtd2w06ih.png" alt="Diagram titled &amp;quot;Read safely, loop over pairs&amp;quot;, subtitle: .get() for maybe-missing keys, .items() for loops. Left, a green card, .get() never crashes: book.get(&amp;quot;rating&amp;quot;) gives None; book.get(&amp;quot;rating&amp;quot;, &amp;quot;no rating yet&amp;quot;) gives no rating yet; &amp;quot;year&amp;quot; in book gives True; the second value you give .get() is the fallback. Right, a blue card, .items() gives pairs: for key, value in book.items(): print(key, &amp;quot;-&gt;&amp;quot;, value) prints title -&gt; Moon Garden, author -&gt; A. Rao and year -&gt; 2019, one key and value pair per turn. Two cards below: book(&amp;quot;year&amp;quot;), use when the key must be there, because a crash tells you something is wrong; book.get(&amp;quot;rating&amp;quot;), use when the key might be missing and you have a sensible fallback. A tip bar says brackets when it must exist, .get() when it might not." width="800" height="568"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;4. Read safely with&lt;/strong&gt; &lt;code&gt;.get()&lt;/code&gt;&lt;strong&gt;, and loop with&lt;/strong&gt; &lt;code&gt;.items()&lt;/code&gt;&lt;strong&gt;.&lt;/strong&gt; When a key might be missing, use &lt;code&gt;.get()&lt;/code&gt; instead of square brackets:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="n"&gt;book&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;"title"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"Moon Garden"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"author"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"A. Rao"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"year"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;2019&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;book&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"rating"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;book&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"rating"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"no rating yet"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"year"&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="n"&gt;book&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;value&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="n"&gt;book&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;items&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"-&amp;gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;value&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="kc"&gt;None&lt;/span&gt;
&lt;span class="n"&gt;no&lt;/span&gt; &lt;span class="n"&gt;rating&lt;/span&gt; &lt;span class="n"&gt;yet&lt;/span&gt;
&lt;span class="kc"&gt;True&lt;/span&gt;
&lt;span class="n"&gt;title&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="nc"&gt;Moon&lt;/span&gt; &lt;span class="nc"&gt;Garden&lt;/span&gt;
&lt;span class="n"&gt;author&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="no"&gt;A&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt; &lt;span class="nc"&gt;Rao&lt;/span&gt;
&lt;span class="n"&gt;year&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="mi"&gt;2019&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;.get("rating")&lt;/code&gt; gives &lt;code&gt;None&lt;/code&gt; for a missing key instead of crashing, and &lt;code&gt;.get("rating", "no rating yet")&lt;/code&gt; gives the fallback you choose. &lt;code&gt;in&lt;/code&gt; checks whether a key exists. &lt;code&gt;.items()&lt;/code&gt; hands you each &lt;strong&gt;key and value as a pair&lt;/strong&gt;, so a &lt;code&gt;for&lt;/code&gt; loop can unpack both at once.&lt;/p&gt;

&lt;p&gt;A simple rule: use square brackets when the key &lt;strong&gt;must&lt;/strong&gt; be there (a crash tells you something is wrong), and &lt;code&gt;.get()&lt;/code&gt; when it &lt;strong&gt;might&lt;/strong&gt; be missing.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fpjgq8b9qdo305n8318lt.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fpjgq8b9qdo305n8318lt.png" alt="Diagram titled &amp;quot;Tuples are fixed, sets drop duplicates&amp;quot;, subtitle: two more containers, each with one trick. Left, a lavender card, tuple, a list you can't change: point = (3, 4), x, y = point and print(x, y) give 3 4; point(0) = 10 gives TypeError: 'tuple' object does not support item assignment; x, y = point unpacks it into two names. Right, a green card, set, each value once: tags = {&amp;quot;sci-fi&amp;quot;, &amp;quot;classic&amp;quot;, &amp;quot;sci-fi&amp;quot;}; print(len(tags)) gives 2, &amp;quot;classic&amp;quot; in tags gives True, and sorted(set((&amp;quot;b&amp;quot;, &amp;quot;a&amp;quot;, &amp;quot;b&amp;quot;, &amp;quot;c&amp;quot;, &amp;quot;a&amp;quot;))) gives ('a', 'b', 'c'); sets have no order and no index, and an empty set is set() because {} is an empty dict. Below, the four containers: list, (1, 2, 2), in order, can change, duplicates allowed; tuple, (3, 4), in order, fixed once made; set, {&amp;quot;a&amp;quot;, &amp;quot;b&amp;quot;}, each value once, no order; dict, {&amp;quot;k&amp;quot;: &amp;quot;v&amp;quot;}, values looked up by key. A tip bar says &amp;quot;which different values are there?&amp;quot; is a job for a set." width="800" height="691"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;5. Tuples are fixed, and sets drop duplicates.&lt;/strong&gt; Two more containers, each with one special trick:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="n"&gt;point&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;x&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;y&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;point&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;x&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;y&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;tags&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;"sci-fi"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"classic"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"sci-fi"&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;tags&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"classic"&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="n"&gt;tags&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;sorted&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;set&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"b"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"a"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"b"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"c"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"a"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="mi"&gt;3&lt;/span&gt; &lt;span class="mi"&gt;4&lt;/span&gt;
&lt;span class="mi"&gt;2&lt;/span&gt;
&lt;span class="kc"&gt;True&lt;/span&gt;
&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'a'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'b'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'c'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A &lt;strong&gt;tuple&lt;/strong&gt; uses round brackets. It’s like a list you &lt;strong&gt;can’t change&lt;/strong&gt; after it’s made, which suits values that belong together, such as a point’s x and y. &lt;code&gt;x, y = point&lt;/code&gt; &lt;strong&gt;unpacks&lt;/strong&gt; it into two names. Try &lt;code&gt;point[0] = 10&lt;/code&gt; and you get &lt;code&gt;TypeError: 'tuple' object does not support item assignment&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;A &lt;strong&gt;set&lt;/strong&gt; uses curly braces without colons. It keeps each value &lt;strong&gt;only once&lt;/strong&gt;, so the repeated “sci-fi” counts once and &lt;code&gt;len(tags)&lt;/code&gt; is 2. That makes sets great for “which different values are there?” Sets have &lt;strong&gt;no order&lt;/strong&gt;, so there’s no &lt;code&gt;tags[0]&lt;/code&gt;; use &lt;code&gt;sorted()&lt;/code&gt; when you want to show them in order. One gotcha: &lt;code&gt;{}&lt;/code&gt; on its own makes an empty dictionary, so an empty set is &lt;code&gt;set()&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fu54ktwxc98i79qczcv7s.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fu54ktwxc98i79qczcv7s.png" alt="Diagram titled &amp;quot;A list of dictionaries is the shape of JSON&amp;quot;, subtitle: records in a row, position first, then key. Left, books, a list of dictionaries: a blue outer box marked list holds two dictionary cards: (0) with &amp;quot;title&amp;quot;: &amp;quot;Moon Garden&amp;quot; and &amp;quot;year&amp;quot;: 2019, and (1), highlighted, with &amp;quot;title&amp;quot;: &amp;quot;Paper Boats&amp;quot; and &amp;quot;year&amp;quot;: 2023. Below, books(1) then (&amp;quot;title&amp;quot;) leads to Paper Boats: first the position in the list, then the key in the dictionary. Right, books.py: for b in books: print(b(&amp;quot;title&amp;quot;), b(&amp;quot;year&amp;quot;)) prints Moon Garden 2019 and Paper Boats 2023. Bottom left, a green card, json.dumps() turns it into JSON text: import json and print(json.dumps(books)) print one line, ({&amp;quot;title&amp;quot;: &amp;quot;Moon Garden&amp;quot;, &amp;quot;year&amp;quot;: 2019}, {&amp;quot;title&amp;quot;: &amp;quot;Paper Boats&amp;quot;, &amp;quot;year&amp;quot;: 2023}), the format web APIs and AI tools send and receive, always with double quotes. Bottom right, Python to JSON: list becomes array, dict becomes object, True becomes true, and None becomes null. A tip bar says most data you'll meet in AI work is a list of dictionaries." width="800" height="652"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;6. A list of dictionaries is the shape of JSON.&lt;/strong&gt; Put dictionaries inside a list and you can hold a whole table of records:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;json&lt;/span&gt;

&lt;span class="n"&gt;books&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;"title"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"Moon Garden"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"year"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;2019&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;"title"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"Paper Boats"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"year"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;2023&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;span class="p"&gt;]&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;books&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"title"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;b&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="n"&gt;books&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"title"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"year"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;json&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;dumps&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;books&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="nc"&gt;Paper&lt;/span&gt; &lt;span class="nc"&gt;Boats&lt;/span&gt;
&lt;span class="nc"&gt;Moon&lt;/span&gt; &lt;span class="nc"&gt;Garden&lt;/span&gt; &lt;span class="mi"&gt;2019&lt;/span&gt;
&lt;span class="nc"&gt;Paper&lt;/span&gt; &lt;span class="nc"&gt;Boats&lt;/span&gt; &lt;span class="mi"&gt;2023&lt;/span&gt;
&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;"title"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"Moon Garden"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"year"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;2019&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;"title"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"Paper Boats"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"year"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;2023&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Read &lt;code&gt;books[1]["title"]&lt;/code&gt; from left to right: &lt;strong&gt;position 1 in the list&lt;/strong&gt;, then &lt;strong&gt;the key “title”&lt;/strong&gt; in that dictionary. The &lt;code&gt;for&lt;/code&gt; loop visits each record in turn.&lt;/p&gt;

&lt;p&gt;The last line uses Python’s built-in &lt;code&gt;json&lt;/code&gt; module (you’ll learn how &lt;code&gt;import&lt;/code&gt; works in issue #20). &lt;code&gt;json.dumps()&lt;/code&gt; turns the data into &lt;strong&gt;JSON text&lt;/strong&gt;, the format web APIs, and the AI tools later in this series, send and receive. It looks almost the same as Python. The differences: JSON always uses &lt;strong&gt;double quotes&lt;/strong&gt;, &lt;code&gt;True&lt;/code&gt; becomes &lt;code&gt;true&lt;/code&gt;, and &lt;code&gt;None&lt;/code&gt; becomes &lt;code&gt;null&lt;/code&gt;. Tomorrow you’ll read and write JSON files.&lt;/p&gt;




&lt;h3&gt;
  
  
  Try it (15 minutes)
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;In your &lt;code&gt;sandbox&lt;/code&gt; folder, create &lt;code&gt;playlist.py&lt;/code&gt;, a made-up playlist as a list of dictionaries:
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="n"&gt;playlist&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;"title"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"Morning Run"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"artist"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"The Toys"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"minutes"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;"title"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"Rainy Bus"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"artist"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"Paper Cups"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"minutes"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;6&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;"title"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"Late Tea"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"artist"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"The Toys"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"minutes"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;span class="p"&gt;]&lt;/span&gt;

&lt;span class="n"&gt;total&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;
&lt;span class="n"&gt;titles&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;span class="n"&gt;artists&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kt"&gt;set&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;song&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="n"&gt;playlist&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;total&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;total&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;song&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"minutes"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
    &lt;span class="n"&gt;titles&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;song&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"title"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;artists&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;song&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"artist"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Songs:"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nb"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;playlist&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Total minutes:"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;total&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;sorted&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;titles&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;artists&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"artists"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;playlist&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"year"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"unknown"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;Run &lt;code&gt;python3 playlist.py&lt;/code&gt;. You should see:
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="nc"&gt;Songs&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;
&lt;span class="nc"&gt;Total&lt;/span&gt; &lt;span class="n"&gt;minutes&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;13&lt;/span&gt;
&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'Late Tea'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'Morning Run'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'Rainy Bus'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;span class="mi"&gt;2&lt;/span&gt; &lt;span class="n"&gt;artists&lt;/span&gt;
&lt;span class="n"&gt;unknown&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;“The Toys” appears twice, but the set keeps it once, so there are 2 artists. None of the songs has a &lt;code&gt;"year"&lt;/code&gt; key, so &lt;code&gt;.get()&lt;/code&gt; gives the fallback.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Change the last line to &lt;code&gt;print(playlist[0]["year"])&lt;/code&gt;. Read the last line of the error: &lt;code&gt;KeyError: 'year'&lt;/code&gt;. Change it back.&lt;/li&gt;
&lt;li&gt;Add &lt;code&gt;print(playlist[3])&lt;/code&gt;. You get &lt;code&gt;IndexError: list index out of range&lt;/code&gt;: three songs means indexes 0, 1 and 2. Remove the line.&lt;/li&gt;
&lt;li&gt;Find the longest song with a loop. Start with &lt;code&gt;longest = playlist[0]&lt;/code&gt;, then for each song, if &lt;code&gt;song["minutes"] &amp;gt; longest["minutes"]&lt;/code&gt;, set &lt;code&gt;longest = song&lt;/code&gt;. Print &lt;code&gt;longest["title"]&lt;/code&gt;. You should get &lt;code&gt;Rainy Bus&lt;/code&gt;.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Check your understanding:&lt;/strong&gt; (a) In &lt;code&gt;["a", "b", "c"]&lt;/code&gt;, what’s the index of &lt;code&gt;"c"&lt;/code&gt;? (b) What’s the difference between &lt;code&gt;book["rating"]&lt;/code&gt; and &lt;code&gt;book.get("rating")&lt;/code&gt; when there’s no rating? (c) What does &lt;code&gt;sorted()&lt;/code&gt; do that &lt;code&gt;.sort()&lt;/code&gt; doesn’t?&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Answer: (a) 2, because counting starts at 0 (or -1, counting from the end). (b) Square brackets raise&lt;/em&gt; &lt;code&gt;KeyError&lt;/code&gt;&lt;em&gt;;&lt;/em&gt; &lt;code&gt;.get()&lt;/code&gt; &lt;em&gt;returns&lt;/em&gt; &lt;code&gt;None&lt;/code&gt; &lt;em&gt;(or the fallback you give it). (c)&lt;/em&gt; &lt;code&gt;sorted()&lt;/code&gt; &lt;em&gt;returns a new sorted list and leaves the original alone;&lt;/em&gt; &lt;code&gt;.sort()&lt;/code&gt; &lt;em&gt;changes the list itself and returns&lt;/em&gt; &lt;code&gt;None&lt;/code&gt;&lt;em&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Common beginner mistakes
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Off-by-one: using &lt;code&gt;len(x)&lt;/code&gt; as an index. The last item is &lt;code&gt;x[len(x) - 1]&lt;/code&gt;, or just &lt;code&gt;x[-1]&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Expecting a slice to include the end: &lt;code&gt;x[1:3]&lt;/code&gt; stops &lt;strong&gt;before&lt;/strong&gt; index 3.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;KeyError&lt;/code&gt; from square brackets on a key that might be missing. Use &lt;code&gt;.get()&lt;/code&gt;, or check with &lt;code&gt;in&lt;/code&gt; first.&lt;/li&gt;
&lt;li&gt;Writing &lt;code&gt;x = x.sort()&lt;/code&gt;, which leaves &lt;code&gt;x&lt;/code&gt; as &lt;code&gt;None&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Writing &lt;code&gt;{}&lt;/code&gt; for an empty set. That’s an empty dictionary; use &lt;code&gt;set()&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Takeaway
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;A list keeps items in order and counts from 0.&lt;/strong&gt; &lt;code&gt;.append()&lt;/code&gt;&lt;strong&gt;,&lt;/strong&gt; &lt;code&gt;len()&lt;/code&gt;&lt;strong&gt;, slicing and&lt;/strong&gt; &lt;code&gt;sorted()&lt;/code&gt; &lt;strong&gt;cover most of what you’ll do with one. A dictionary stores values under unique keys: square brackets when the key must exist,&lt;/strong&gt; &lt;code&gt;.get()&lt;/code&gt; &lt;strong&gt;when it might not,&lt;/strong&gt; &lt;code&gt;.items()&lt;/code&gt; &lt;strong&gt;to loop. Tuples are fixed and sets keep each value once. A list of dictionaries is the shape of JSON.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Where this fits in my roadmap:&lt;/strong&gt; this is part of my on-ramp, the Python basics everything else sits on. Almost every AI tool I’ll call takes a list of dictionaries in and hands a dictionary back, so reading &lt;code&gt;data[0]["text"]&lt;/code&gt; without thinking is a skill worth drilling now. Tomorrow: &lt;strong&gt;strings, files and JSON&lt;/strong&gt;, so that data can come from a file and go back to one.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Over to you:&lt;/strong&gt; think of something you track, such as books, runs or recipes. Reply with one record as a Python dictionary, like &lt;code&gt;{"title": "Moon Garden", "year": 2019}&lt;/code&gt;.&lt;/p&gt;




&lt;h3&gt;
  
  
  Sources
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;Python tutorial, “An Informal Introduction to Python”, Lists (indexing from 0, negative indexes, slicing, &lt;code&gt;len()&lt;/code&gt;, &lt;code&gt;.append()&lt;/code&gt;). &lt;a href="https://docs.python.org/3/tutorial/introduction.html#lists" rel="noopener noreferrer"&gt;https://docs.python.org/3/tutorial/introduction.html#lists&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Python tutorial, “Data Structures”, More on Lists (&lt;code&gt;.append()&lt;/code&gt;, &lt;code&gt;.sort()&lt;/code&gt;, list methods). &lt;a href="https://docs.python.org/3/tutorial/datastructures.html#more-on-lists" rel="noopener noreferrer"&gt;https://docs.python.org/3/tutorial/datastructures.html#more-on-lists&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Python tutorial, “Data Structures”, Tuples and Sequences (tuples, unpacking) and Sets (duplicates removed, &lt;code&gt;set()&lt;/code&gt; for an empty set). &lt;a href="https://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences" rel="noopener noreferrer"&gt;https://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Python tutorial, “Data Structures”, Dictionaries (keys are unique, insertion order, &lt;code&gt;in&lt;/code&gt;, &lt;code&gt;KeyError&lt;/code&gt;) and Looping Techniques (&lt;code&gt;.items()&lt;/code&gt;). &lt;a href="https://docs.python.org/3/tutorial/datastructures.html#dictionaries" rel="noopener noreferrer"&gt;https://docs.python.org/3/tutorial/datastructures.html#dictionaries&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Python docs, “Built-in Types”, &lt;code&gt;dict.get&lt;/code&gt; (returns the default, or &lt;code&gt;None&lt;/code&gt;, for a missing key). &lt;a href="https://docs.python.org/3/builtins/stdtypes.html#dict.get" rel="noopener noreferrer"&gt;https://docs.python.org/3/builtins/stdtypes.html#dict.get&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Python HOWTO, “Sorting Techniques” (&lt;code&gt;sorted()&lt;/code&gt; returns a new list; &lt;code&gt;list.sort()&lt;/code&gt; sorts in place and returns &lt;code&gt;None&lt;/code&gt;; &lt;code&gt;reverse=True&lt;/code&gt;). &lt;a href="https://docs.python.org/3/howto/sorting.html" rel="noopener noreferrer"&gt;https://docs.python.org/3/howto/sorting.html&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Python docs, “json” (&lt;code&gt;json.dumps()&lt;/code&gt;, and how Python types map to JSON). &lt;a href="https://docs.python.org/3/library/json.html" rel="noopener noreferrer"&gt;https://docs.python.org/3/library/json.html&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Python docs, “Built-in Exceptions” (&lt;code&gt;IndexError&lt;/code&gt;, &lt;code&gt;KeyError&lt;/code&gt;, &lt;code&gt;TypeError&lt;/code&gt;). &lt;a href="https://docs.python.org/3/builtins/exceptions.html" rel="noopener noreferrer"&gt;https://docs.python.org/3/builtins/exceptions.html&lt;/a&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;em&gt;All examples are made up (the books, songs and artists are invented) and were run with Python 3.13 on Nov 2, 2026. Error messages are from Python 3.13; other versions word some of them differently. Sources checked Nov 2, 2026.&lt;/em&gt;&lt;/p&gt;




&lt;p&gt;Free: &lt;a href="https://dhanushkumarsivaji.substack.com/p/the-path-to-ai-fde-the-free-roadmap" rel="noopener noreferrer"&gt;the 5-page roadmap from Novice to AI FDE&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;If this was useful, &lt;a href="https://dhanushkumarsivaji.substack.com/subscribe" rel="noopener noreferrer"&gt;subscribe to The Path to AI FDE&lt;/a&gt; for the next issue.&lt;/p&gt;

</description>
      <category>python</category>
      <category>beginners</category>
      <category>programming</category>
      <category>json</category>
    </item>
    <item>
      <title>The path to AI FDE #16: Functions: reusable pieces of logic</title>
      <dc:creator>Dhanush Kumar Sivaji</dc:creator>
      <pubDate>Wed, 18 Nov 2026 06:56:09 +0000</pubDate>
      <link>https://dev.to/dhanushkumarsivaji/the-path-to-ai-fde-16-functions-reusable-pieces-of-logic-2l8l</link>
      <guid>https://dev.to/dhanushkumarsivaji/the-path-to-ai-fde-16-functions-reusable-pieces-of-logic-2l8l</guid>
      <description>&lt;p&gt;&lt;em&gt;Originally published on my newsletter, The Path to AI FDE. &lt;a href="https://dhanushkumarsivaji.substack.com/subscribe" rel="noopener noreferrer"&gt;Subscribe free&lt;/a&gt; to get each issue by email.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;This is a &lt;strong&gt;“From Zero” issue&lt;/strong&gt;. Last week your code learned to decide and repeat. Today you learn to &lt;strong&gt;name a piece of code and reuse it&lt;/strong&gt;, so you write it once and call it whenever you need it.&lt;/p&gt;

&lt;p&gt;That named piece of code is a &lt;strong&gt;function&lt;/strong&gt;. You’ve already used other people’s functions: &lt;code&gt;print()&lt;/code&gt;, &lt;code&gt;len()&lt;/code&gt;, &lt;code&gt;type()&lt;/code&gt;. Today you write your own. By the end you’ll have a small script that shares pizzas fairly between friends, built from two tiny functions.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F0kcr7aktz2pwhlpk6xy8.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F0kcr7aktz2pwhlpk6xy8.png" alt="Cover card titled &amp;quot;Functions, from Zero&amp;quot; for issue 16 of The Path to AI FDE by Dhanush Kumar Sivaji. Subtitle: write it once, name it well, use it everywhere. Six numbered cards in two lanes. Part A, building a function: 1, def and calls, shown as def greet(name): with print(&amp;quot;Hello,&amp;quot;, name) indented below: def stores the code, and a call, greet(&amp;quot;Asha&amp;quot;), runs it; 2, parameters, shown as width, height receiving 3, 4: parameters are the input slots and arguments are the values you pass; 3, return, shown as return width * height: hands a result back to your code, with a warning that no return gives None. Part B, easy to use: 4, defaults and keywords, shown as make_tea(2, sugar=0): callers can skip inputs or name them, with a warning never to use a list as a default; 5, scope, shown as inside, then stays inside: pass values in as arguments and return results out; 6, one job each, shown as to_fahrenheit(c): small, well-named functions are easy to test and reuse. A tip bar says: arguments go in, a return value comes out." width="800" height="644"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  Part A · Building a function
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fmd8etpeb5k69rano1p25.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fmd8etpeb5k69rano1p25.png" alt="Diagram titled &amp;quot;def defines, a call runs&amp;quot;, subtitle: write it once, run it whenever you need it. Left panel, the definition, stored but not run: the line def greet(name): is split into labelled tiles: def is the keyword, greet is the name, name in brackets is the parameter or input, and the line ends with a colon. Below it, the indented body print(&amp;quot;Hello,&amp;quot;, name) in a dashed box; the indented lines are the body, which Python remembers under the name greet. Right panel, the calls, each of which runs the body: greet(&amp;quot;Asha&amp;quot;) leads to Hello, Asha and greet(&amp;quot;Ben&amp;quot;) leads to Hello, Ben; a call is the name followed by brackets, so no brackets means no run. Below, greet.py shows the full code and its two lines of output. Two notes: Python reads the file top to bottom, so put the def above the first call; and print(), len() and type() are functions too. A tip bar says def writes the recipe, and a call cooks it as many times as you like." width="800" height="691"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1.&lt;/strong&gt; &lt;code&gt;def&lt;/code&gt; &lt;strong&gt;defines a function; calling it runs it.&lt;/strong&gt; Save this as &lt;code&gt;greet.py&lt;/code&gt; in your &lt;code&gt;sandbox&lt;/code&gt; folder:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;greet&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Hello,"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="nf"&gt;greet&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Asha"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="nf"&gt;greet&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Ben"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Run it with &lt;code&gt;python3 greet.py&lt;/code&gt; (Windows: &lt;code&gt;python greet.py&lt;/code&gt;):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="nc"&gt;Hello&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Asha&lt;/span&gt;
&lt;span class="nc"&gt;Hello&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Ben&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The first two lines are the &lt;strong&gt;definition&lt;/strong&gt;. &lt;code&gt;def&lt;/code&gt; starts it, &lt;code&gt;greet&lt;/code&gt; is the function’s name, &lt;code&gt;(name)&lt;/code&gt; lists its inputs, and the line ends with a colon. The indented lines under it are the function’s &lt;strong&gt;body&lt;/strong&gt;, just like the blocks in last week’s &lt;code&gt;if&lt;/code&gt; and &lt;code&gt;for&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Defining a function doesn’t run it. Python just remembers it under the name &lt;code&gt;greet&lt;/code&gt;. The body runs only when you &lt;strong&gt;call&lt;/strong&gt; the function: its name followed by brackets, &lt;code&gt;greet("Asha")&lt;/code&gt;. Two calls, two greetings. Python reads your file from top to bottom, so put the &lt;code&gt;def&lt;/code&gt; above the first line that calls it.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fk9crk0njsf1jvx941sdc.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fk9crk0njsf1jvx941sdc.png" alt="Diagram titled &amp;quot;Parameters and arguments&amp;quot;, subtitle: a function is a machine with named input slots. Two machines labelled area(width, height). In the first, the arguments 3 and 4 drop into the slots named width and height, so width = 3 and height = 4, and it prints 12. In the second, 10 and 2 go in and it prints 20. Labels mark the values you pass as arguments and the names in the def as parameters. Below, area.py shows the code and the output 12 and 20. A note says arguments are matched in order: the first argument goes into the first parameter. An orange box, an empty slot: area(3) gives TypeError: area() missing 1 required positional argument: 'height'. A tip bar says parameters are the slots in the definition, and arguments are what you put in them." width="800" height="768"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Parameters are the input slots; arguments are the values you put in them.&lt;/strong&gt; A function can take more than one input:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;area&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;width&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;height&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;width&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;height&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="nf"&gt;area&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="nf"&gt;area&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="mi"&gt;12&lt;/span&gt;
&lt;span class="mi"&gt;20&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;width&lt;/code&gt; and &lt;code&gt;height&lt;/code&gt; are the &lt;strong&gt;parameters&lt;/strong&gt;: the names in the definition. &lt;code&gt;3&lt;/code&gt; and &lt;code&gt;4&lt;/code&gt; are the &lt;strong&gt;arguments&lt;/strong&gt;: the values you pass when you call it. Python matches them &lt;strong&gt;in order&lt;/strong&gt;, so the first argument goes into the first parameter. Inside the body, &lt;code&gt;width&lt;/code&gt; is 3 and &lt;code&gt;height&lt;/code&gt; is 4.&lt;/p&gt;

&lt;p&gt;Leave one out, with &lt;code&gt;area(3)&lt;/code&gt;, and Python stops with:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="nc"&gt;TypeError&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nf"&gt;area&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="n"&gt;missing&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt; &lt;span class="n"&gt;required&lt;/span&gt; &lt;span class="n"&gt;positional&lt;/span&gt; &lt;span class="n"&gt;argument&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s1"&gt;'height'&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The message names the slot you left empty. People mix up the two words all the time, and it rarely matters, but now you know which is which.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fl3tuh58ofl1r9ufnacj3.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fl3tuh58ofl1r9ufnacj3.png" alt="Diagram titled &amp;quot;return sends a value back&amp;quot;, subtitle: print is for people, return is for your code. Left, the call is replaced by its answer, in three steps: total = area(3, 4) + area(10, 2); each call returns its value, giving total = 12 + 20; then the line finishes, giving total = 32. Right, area.py version 2 uses return width * height and prints 32. Three cards below: print shows a value to a human on screen, and your code can't use it afterwards; return hands a value back to your code to store or use, and ends the function at once; no return: def double(n): n * 2, then print(double(5)) shows None. A tip bar says forget return and the function still runs, but hands back None." width="800" height="664"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3.&lt;/strong&gt; &lt;code&gt;return&lt;/code&gt; &lt;strong&gt;sends a result back. Without it, you get&lt;/strong&gt; &lt;code&gt;None&lt;/code&gt;&lt;strong&gt;.&lt;/strong&gt; Our &lt;code&gt;area&lt;/code&gt; prints the answer, but the rest of your program can’t use it. Change &lt;code&gt;print&lt;/code&gt; to &lt;code&gt;return&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;area&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;width&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;height&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;width&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;height&lt;/span&gt;

&lt;span class="n"&gt;total&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;area&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="nf"&gt;area&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;total&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="mi"&gt;32&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;return&lt;/code&gt; hands a value back to the line that called the function. You can picture &lt;code&gt;area(3, 4)&lt;/code&gt; being replaced by &lt;code&gt;12&lt;/code&gt;, so the line becomes &lt;code&gt;total = 12 + 20&lt;/code&gt;. That’s the difference: &lt;code&gt;print&lt;/code&gt; &lt;strong&gt;shows a value to a human;&lt;/strong&gt; &lt;code&gt;return&lt;/code&gt; &lt;strong&gt;gives it to your code.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Forget &lt;code&gt;return&lt;/code&gt;, and the function still runs but hands back &lt;code&gt;None&lt;/code&gt; (Python’s “no value here” from issue #14):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;double&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;n&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;

&lt;span class="n"&gt;result&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;double&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="kc"&gt;None&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The function worked out 10 and then threw it away. &lt;code&gt;return&lt;/code&gt; also &lt;strong&gt;ends the function immediately&lt;/strong&gt;: any lines after it in the same block never run.&lt;/p&gt;

&lt;h2&gt;
  
  
  Part B · Functions that are easy to use
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fezm3ux7dyem7end9obbf.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fezm3ux7dyem7end9obbf.png" alt="Diagram titled &amp;quot;Defaults and keyword arguments&amp;quot;, subtitle: let callers skip an input, or name it. The definition def make_tea(cups, sugar=1, milk=True): with three calls: make_tea(2) gives 2 cup(s), 1 sugar, milk: True, using both defaults; make_tea(2, sugar=0) gives 2 cup(s), 0 sugar, milk: True, with one input set by name, a keyword argument; make_tea(milk=False, cups=1) gives 1 cup(s), 1 sugar, milk: False, with every input named so order doesn't matter. One rule: arguments without names come first; make_tea(sugar=0, 2) gives SyntaxError: positional argument follows keyword argument. An orange warning, never a list as a default, because it's made once and shared by every call: add_item with basket=() returns ('apple') the first time and ('apple', 'pear') the second. A green fix: default basket to None and make a new list inside, which gives ('apple') then ('pear'). A tip bar says names make calls readable: make_tea(2, sugar=0) says more than make_tea(2, 0)." width="800" height="840"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;4. Defaults and keyword arguments let callers skip or name inputs.&lt;/strong&gt; Give a parameter a &lt;strong&gt;default value&lt;/strong&gt; with &lt;code&gt;=&lt;/code&gt; in the definition, and callers can leave it out:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;make_tea&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;cups&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;sugar&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;milk&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="kc"&gt;True&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"{cups} cup(s), {sugar} sugar, milk: {milk}"&lt;/span&gt;

&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;make_tea&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;make_tea&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;sugar&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;make_tea&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;milk&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="kc"&gt;False&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;cups&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="mi"&gt;2&lt;/span&gt; &lt;span class="nf"&gt;cup&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt; &lt;span class="n"&gt;sugar&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;milk&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;True&lt;/span&gt;
&lt;span class="mi"&gt;2&lt;/span&gt; &lt;span class="nf"&gt;cup&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt; &lt;span class="n"&gt;sugar&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;milk&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;True&lt;/span&gt;
&lt;span class="mi"&gt;1&lt;/span&gt; &lt;span class="nf"&gt;cup&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt; &lt;span class="n"&gt;sugar&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;milk&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;False&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The first call uses both defaults. The second passes a &lt;strong&gt;keyword argument&lt;/strong&gt;, &lt;code&gt;sugar=0&lt;/code&gt;, which sets that one input by name. The third names every input, so the order no longer matters. Names make calls easier to read too: &lt;code&gt;make_tea(2, sugar=0)&lt;/code&gt; says more than &lt;code&gt;make_tea(2, 0)&lt;/code&gt;. One rule: arguments without names come first. &lt;code&gt;make_tea(sugar=0, 2)&lt;/code&gt; gives &lt;code&gt;SyntaxError: positional argument follows keyword argument&lt;/code&gt;. Later in the series you’ll see the same shape in AI code, such as a function that splits text with a default &lt;code&gt;size=500&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The one trap: never use a list as a default.&lt;/strong&gt; The default is created &lt;strong&gt;once&lt;/strong&gt;, when Python reads the &lt;code&gt;def&lt;/code&gt;, and then shared by every call:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;add_item&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;item&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;basket&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;basket&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;item&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;basket&lt;/span&gt;

&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;add_item&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"apple"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;add_item&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"pear"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'apple'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'apple'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'pear'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The second call “remembers” the apple. (&lt;code&gt;append&lt;/code&gt; adds an item to the end of a list; lists get their own issue tomorrow.) The fix is to default to &lt;code&gt;None&lt;/code&gt; and make a fresh list inside:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;add_item&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;item&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;basket&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;basket&lt;/span&gt; &lt;span class="k"&gt;is&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;basket&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
    &lt;span class="n"&gt;basket&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;item&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;basket&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now the two calls print &lt;code&gt;['apple']&lt;/code&gt; and &lt;code&gt;['pear']&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F3t7eps3j2aozs8scovcu.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F3t7eps3j2aozs8scovcu.png" alt="Diagram titled &amp;quot;Scope: what a function can see&amp;quot;, subtitle: every call is a room, and what's made inside stays inside. Left, a dashed lavender box marked inside bake(), local names: def bake(): sets dough = 200 and prints inside: 200. Outside the function, bake() then print(dough) gives NameError: name 'dough' is not defined. Right, a green box, reading an outside name works: greeting = &amp;quot;Hi&amp;quot; and a function welcome(name) that returns greeting + &amp;quot;, &amp;quot; + name prints Hi, Asha. An orange box, assigning makes it local: count = 0 and a function bump() that runs count = count + 1 gives UnboundLocalError: cannot access local variable 'count' where it is not associated with a value. Below, the clean pattern: def bump(n): return n + 1, and count = bump(count) twice prints 2; the function never touches the outside name, it gets a value and hands back a new one. A tip bar says each call gets its own workspace: arguments in, return value out." width="800" height="790"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;5. Scope: names made inside a function exist only inside it.&lt;/strong&gt; Each call gets its own private workspace. Names created there disappear when the function ends:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;bake&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;dough&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;200&lt;/span&gt;
    &lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"inside:"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;dough&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="nf"&gt;bake&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;dough&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="n"&gt;inside&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;200&lt;/span&gt;
&lt;span class="nc"&gt;NameError&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;name&lt;/span&gt; &lt;span class="s1"&gt;'dough'&lt;/span&gt; &lt;span class="k"&gt;is&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="n"&gt;defined&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;(Python prints a few more lines above the &lt;code&gt;NameError&lt;/code&gt;, called a traceback. You’ll learn to read those in issue #19.) The part of a program where a name exists is its &lt;strong&gt;scope&lt;/strong&gt;. &lt;code&gt;dough&lt;/code&gt; is a &lt;strong&gt;local&lt;/strong&gt; name: it belongs to &lt;code&gt;bake&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The other direction is softer: a function can &lt;strong&gt;read&lt;/strong&gt; a name defined outside it. With &lt;code&gt;greeting = "Hi"&lt;/code&gt; at the top of the file, a function can use &lt;code&gt;greeting&lt;/code&gt;. But if a function &lt;strong&gt;assigns&lt;/strong&gt; to a name, Python treats that name as local for the whole function. So this fails:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="n"&gt;count&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;

&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;bump&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;count&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;count&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;

&lt;span class="nf"&gt;bump&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="nc"&gt;UnboundLocalError&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;cannot&lt;/span&gt; &lt;span class="n"&gt;access&lt;/span&gt; &lt;span class="n"&gt;local&lt;/span&gt; &lt;span class="n"&gt;variable&lt;/span&gt; &lt;span class="s1"&gt;'count'&lt;/span&gt; &lt;span class="n"&gt;where&lt;/span&gt; &lt;span class="n"&gt;it&lt;/span&gt; &lt;span class="k"&gt;is&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="n"&gt;associated&lt;/span&gt; &lt;span class="k"&gt;with&lt;/span&gt; &lt;span class="n"&gt;a&lt;/span&gt; &lt;span class="n"&gt;value&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The clean habit: &lt;strong&gt;pass values in as arguments and return results out.&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;bump&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;

&lt;span class="n"&gt;count&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;
&lt;span class="n"&gt;count&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;bump&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;count&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;count&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;bump&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;count&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;count&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This prints &lt;code&gt;2&lt;/code&gt;. (Python has a &lt;code&gt;global&lt;/code&gt; keyword that lets a function change an outside name. You’ll rarely need it; passing in and returning out is easier to follow.)&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fnx1c33muq1pdsygd1hs2.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fnx1c33muq1pdsygd1hs2.png" alt="Diagram titled &amp;quot;One job per function&amp;quot;, subtitle: small, well-named functions are easier to read, test and reuse. Left, an orange box, one function with two jobs: report(c) converts Celsius to Fahrenheit and prints the sentence, so you can't reuse the number or check it. Below, good names say what the function does, in snake_case: to_fahrenheit, make_tea, add_item; if you need &amp;quot;and&amp;quot; to name it, it's doing two jobs. Right, a green box, two small functions with one job each: to_fahrenheit(c) has the docstring &amp;quot;Convert Celsius to Fahrenheit.&amp;quot; and returns c * 9 / 5 + 32; describe(c) calls it and returns a sentence. The output is 100°C is 212.0°F, -40°C is -40.0°F and True, the last from the quick check to_fahrenheit(0) == 32. Tags: docstring says what it does, describe reuses it, a quick check. A tip bar says a function that returns a value is easy to test, and that's where proper tests start." width="800" height="652"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;6. Give each function one job, and a name that says what it is.&lt;/strong&gt; Small functions are easier to read, test and reuse. Here, one function does the maths and another builds the sentence:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;to_fahrenheit&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="s2"&gt;"""Convert Celsius to Fahrenheit."""&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;c&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="mi"&gt;9&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="mi"&gt;5&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;32&lt;/span&gt;

&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;describe&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;f&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;to_fahrenheit&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"{c}°C is {f}°F"&lt;/span&gt;

&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;describe&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;100&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;describe&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;40&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;to_fahrenheit&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="mi"&gt;32&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="mi"&gt;100&lt;/span&gt;°&lt;span class="no"&gt;C&lt;/span&gt; &lt;span class="k"&gt;is&lt;/span&gt; &lt;span class="mf"&gt;212.0&lt;/span&gt;°&lt;span class="no"&gt;F&lt;/span&gt;
&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;40&lt;/span&gt;°&lt;span class="no"&gt;C&lt;/span&gt; &lt;span class="k"&gt;is&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mf"&gt;40.0&lt;/span&gt;°&lt;span class="no"&gt;F&lt;/span&gt;
&lt;span class="kc"&gt;True&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Three habits are packed in here:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;One job each.&lt;/strong&gt; &lt;code&gt;to_fahrenheit&lt;/code&gt; only converts. &lt;code&gt;describe&lt;/code&gt; only words the answer, and it reuses &lt;code&gt;to_fahrenheit&lt;/code&gt; instead of repeating the formula.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;A quick check.&lt;/strong&gt; &lt;code&gt;to_fahrenheit(0) == 32&lt;/code&gt; prints &lt;code&gt;True&lt;/code&gt;, so you know the maths is right. Because the function returns a value instead of printing it, it’s easy to test. That’s where proper tests (lesson 4.6) start.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;A docstring.&lt;/strong&gt; The string in triple quotes on the first line of the body says what the function does. Many editors show it when you hover over the name.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Give functions names that say what they do, in &lt;code&gt;snake_case&lt;/code&gt;, the Python style guide’s choice for function names: &lt;code&gt;to_fahrenheit&lt;/code&gt;, &lt;code&gt;make_tea&lt;/code&gt;, &lt;code&gt;add_item&lt;/code&gt;. If you can’t name a function without using “and”, it’s probably doing two jobs.&lt;/p&gt;




&lt;h3&gt;
  
  
  Try it (15 minutes)
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;In your &lt;code&gt;sandbox&lt;/code&gt; folder, create &lt;code&gt;pizza.py&lt;/code&gt;, for sharing made-up pizzas between friends:
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;slices_each&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;pizzas&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;people&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;per_pizza&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;8&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="s2"&gt;"""How many whole slices each person gets."""&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;pizzas&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;per_pizza&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;//&lt;/span&gt; &lt;span class="n"&gt;people&lt;/span&gt;

&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;leftover&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;pizzas&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;people&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;per_pizza&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;8&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="s2"&gt;"""How many slices are left after a fair share."""&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;pizzas&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;per_pizza&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;%&lt;/span&gt; &lt;span class="n"&gt;people&lt;/span&gt;

&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;slices_each&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nf"&gt;leftover&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;slices_each&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;per_pizza&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;6&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nf"&gt;leftover&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;per_pizza&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;6&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;slices_each&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;people&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;7&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;pizzas&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;Run &lt;code&gt;python3 pizza.py&lt;/code&gt;. You should see:
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="mi"&gt;4&lt;/span&gt; &lt;span class="mi"&gt;4&lt;/span&gt;
&lt;span class="mi"&gt;3&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;
&lt;span class="mi"&gt;1&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Three pizzas of 8 slices is 24; shared by 5, that’s 4 each with 4 left over. (&lt;code&gt;//&lt;/code&gt; and &lt;code&gt;%&lt;/code&gt; are whole-number division and remainder, from issue #14.)&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Delete the word &lt;code&gt;return&lt;/code&gt; in &lt;code&gt;slices_each&lt;/code&gt; (keep the maths) and run it again. The first number on each line becomes &lt;code&gt;None&lt;/code&gt;. Put it back.&lt;/li&gt;
&lt;li&gt;Add &lt;code&gt;print(slices_each(3, 0))&lt;/code&gt; at the end. Read the last line of the error: &lt;code&gt;ZeroDivisionError: integer division or modulo by zero&lt;/code&gt;. You can’t share between nobody. (Handling errors like this properly is issue #19.) Remove the line.&lt;/li&gt;
&lt;li&gt;Write a third function, &lt;code&gt;pizzas_needed(people, slices_each=3, per_pizza=8)&lt;/code&gt;, that returns how many pizzas to order. Hint: &lt;code&gt;-(-a // b)&lt;/code&gt; rounds a division up. With 10 people, it should return &lt;code&gt;4&lt;/code&gt;.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Check your understanding:&lt;/strong&gt; (a) In &lt;code&gt;def area(width, height):&lt;/code&gt;, are &lt;code&gt;width&lt;/code&gt; and &lt;code&gt;height&lt;/code&gt; parameters or arguments? (b) What does a function return if it has no &lt;code&gt;return&lt;/code&gt; line? (c) Why did the second &lt;code&gt;add_item("pear")&lt;/code&gt; call also show the apple?&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Answer: (a) Parameters: the names in the definition. The values you pass in a call are the arguments. (b)&lt;/em&gt; &lt;code&gt;None&lt;/code&gt;&lt;em&gt;. (c) A list default is created once, when the&lt;/em&gt; &lt;code&gt;def&lt;/code&gt; &lt;em&gt;runs, and every call shares it. Use&lt;/em&gt; &lt;code&gt;None&lt;/code&gt; &lt;em&gt;as the default and make a new list inside.&lt;/em&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Common beginner mistakes
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Forgetting &lt;code&gt;return&lt;/code&gt;, then wondering why the result is &lt;code&gt;None&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Printing inside a function when the caller needs the value. Return it, and print outside.&lt;/li&gt;
&lt;li&gt;Defining a function and never calling it (no brackets, no run).&lt;/li&gt;
&lt;li&gt;Using a list or dictionary as a default (&lt;code&gt;def f(x=[])&lt;/code&gt;). It’s shared between calls.&lt;/li&gt;
&lt;li&gt;Trying to change an outside variable from inside a function. Pass it in and return the new value.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Takeaway
&lt;/h3&gt;

&lt;p&gt;&lt;code&gt;def&lt;/code&gt; &lt;strong&gt;names a block of code, and calling it runs it. Parameters are the input slots, and arguments are the values you put in.&lt;/strong&gt; &lt;code&gt;return&lt;/code&gt; &lt;strong&gt;hands a result back; without it you get&lt;/strong&gt; &lt;code&gt;None&lt;/code&gt;&lt;strong&gt;. Defaults and keyword arguments make calls short and clear. Names made inside a function stay inside. Keep each function to one job.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Where this fits in my roadmap:&lt;/strong&gt; this is part of my on-ramp, the Python basics everything else sits on. Every AI app I build later is a stack of small functions: one to load text, one to call a model, one to check the answer. Tomorrow: &lt;strong&gt;lists and dictionaries&lt;/strong&gt;, the two containers that hold almost all the data you’ll touch.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Over to you:&lt;/strong&gt; what’s a task you’d turn into a function? Reply with its name and its inputs, like &lt;code&gt;make_tea(cups, sugar=1)&lt;/code&gt;.&lt;/p&gt;




&lt;h3&gt;
  
  
  Sources
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;Python tutorial, “More Control Flow Tools”, Defining Functions (&lt;code&gt;def&lt;/code&gt;, the body is indented, a function without &lt;code&gt;return&lt;/code&gt; returns &lt;code&gt;None&lt;/code&gt;; docstrings). &lt;a href="https://docs.python.org/3/tutorial/controlflow.html#defining-functions" rel="noopener noreferrer"&gt;https://docs.python.org/3/tutorial/controlflow.html#defining-functions&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Python tutorial, “More Control Flow Tools”, More on Defining Functions (default argument values, “the default value is evaluated only once”, keyword arguments, positional arguments before keyword arguments). &lt;a href="https://docs.python.org/3/tutorial/controlflow.html#more-on-defining-functions" rel="noopener noreferrer"&gt;https://docs.python.org/3/tutorial/controlflow.html#more-on-defining-functions&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Python glossary, “parameter” and “argument” (the difference between the two). &lt;a href="https://docs.python.org/3/glossary.html#term-parameter" rel="noopener noreferrer"&gt;https://docs.python.org/3/glossary.html#term-parameter&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Python reference, “Execution model”, Naming and binding (a name assigned inside a function is local to it). &lt;a href="https://docs.python.org/3/reference/executionmodel.html#naming-and-binding" rel="noopener noreferrer"&gt;https://docs.python.org/3/reference/executionmodel.html#naming-and-binding&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Python FAQ, “Why am I getting an UnboundLocalError when the variable has a value?” and “Why are default values shared between objects?”. &lt;a href="https://docs.python.org/3/faq/programming.html#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value" rel="noopener noreferrer"&gt;https://docs.python.org/3/faq/programming.html#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;PEP 8, “Style Guide for Python Code” (function names are lowercase, with words separated by underscores). &lt;a href="https://peps.python.org/pep-0008/#function-and-variable-names" rel="noopener noreferrer"&gt;https://peps.python.org/pep-0008/#function-and-variable-names&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;PEP 257, “Docstring Conventions” (what a docstring is; triple double quotes). &lt;a href="https://peps.python.org/pep-0257/" rel="noopener noreferrer"&gt;https://peps.python.org/pep-0257/&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Python docs, “Built-in Exceptions” (&lt;code&gt;TypeError&lt;/code&gt;, &lt;code&gt;NameError&lt;/code&gt;, &lt;code&gt;UnboundLocalError&lt;/code&gt;, &lt;code&gt;ZeroDivisionError&lt;/code&gt;). &lt;a href="https://docs.python.org/3/builtins/exceptions.html" rel="noopener noreferrer"&gt;https://docs.python.org/3/builtins/exceptions.html&lt;/a&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;em&gt;All examples are made up and were run with Python 3.13 on Nov 2, 2026. Error messages are from Python 3.13; other versions word some of them differently. Sources checked Nov 2, 2026.&lt;/em&gt;&lt;/p&gt;




&lt;p&gt;Free: &lt;a href="https://dhanushkumarsivaji.substack.com/p/the-path-to-ai-fde-the-free-roadmap" rel="noopener noreferrer"&gt;the 5-page roadmap from Novice to AI FDE&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;If this was useful, &lt;a href="https://dhanushkumarsivaji.substack.com/subscribe" rel="noopener noreferrer"&gt;subscribe to The Path to AI FDE&lt;/a&gt; for the next issue.&lt;/p&gt;

</description>
      <category>python</category>
      <category>beginners</category>
      <category>programming</category>
      <category>ai</category>
    </item>
    <item>
      <title>The path to AI FDE #07: APIs and JSON: how programs talk to each other</title>
      <dc:creator>Dhanush Kumar Sivaji</dc:creator>
      <pubDate>Mon, 09 Nov 2026 18:28:47 +0000</pubDate>
      <link>https://dev.to/dhanushkumarsivaji/the-path-to-ai-fde-07-apis-and-json-how-programs-talk-to-each-other-36f9</link>
      <guid>https://dev.to/dhanushkumarsivaji/the-path-to-ai-fde-07-apis-and-json-how-programs-talk-to-each-other-36f9</guid>
      <description>&lt;p&gt;&lt;em&gt;Originally published on my newsletter, The Path to AI FDE. &lt;a href="https://dhanushkumarsivaji.substack.com/subscribe" rel="noopener noreferrer"&gt;Subscribe free&lt;/a&gt; to get each issue by email.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;This is a &lt;strong&gt;“From Zero” issue&lt;/strong&gt;. Yesterday (#06) we followed one request from a client to a server and back. Today is about &lt;em&gt;what&lt;/em&gt; programs say to each other in those requests. The answer, almost always, is: they call an &lt;strong&gt;API&lt;/strong&gt;, and they speak &lt;strong&gt;JSON&lt;/strong&gt;. Every AI model you’ll use in this series is reached this way. No code to install today, just a toy café API and a browser.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fimoryxpwndzeuhnutgu7.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fimoryxpwndzeuhnutgu7.png" alt="Infographic titled &amp;quot;APIs and JSON, from Zero&amp;quot;, subtitled &amp;quot;How programs talk to each other: an API is a restaurant menu for software.&amp;quot; Legend: asking an API, the JSON data, gotcha. Part A, ordering from an API, has three cards. 1, API: a menu for software, with the chain menu, order, kitchen, plate: a set of operations one program offers another, with exact rules for asking. 2, Endpoint, with examples POST /v1/orders and GET /weather: one URL that does one job; the method says what to do there. 3, Request body, with the header Content-Type: application/json: the data you send along, usually JSON; a GET usually has none. Part B, JSON and the reply. 4, JSON values, with a small object containing &amp;quot;item&amp;quot;: &amp;quot;chai&amp;quot;, &amp;quot;qty&amp;quot;: 2, &amp;quot;to_go&amp;quot;: true, &amp;quot;note&amp;quot;: null and &amp;quot;extras&amp;quot;: (&amp;quot;ginger&amp;quot;): text, numbers, true/false, null, lists and objects. 5, Strict rules, a warning: double quotes, no trailing commas, no comments, and &amp;quot;2&amp;quot; is text, not a number. 6, Response plus status, with chips 201 Created and 404 Not Found: read the status first, then the JSON body; errors explain themselves. 7, Read the docs, with chips method plus URL, auth, params, examples, errors, limits: good APIs publish them, and reading them carefully is a core engineering skill. Tip bar: pick an endpoint, send JSON, check the status, read the JSON back." width="800" height="784"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Part A · Ordering from an API
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F81yuxp57f15f0jwi5dkf.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F81yuxp57f15f0jwi5dkf.png" alt="Diagram titled &amp;quot;An API is a menu for software&amp;quot;. Four cards in a row joined by arrows: the menu equals API docs, what you can order and how to ask for it; your order slip equals the JSON request, exactly what you want in a fixed format; the kitchen equals the server, it does the work and you never go in; the plate equals the JSON response, what comes back plus how it went. Three notes below: a fixed list, you can't order what isn't on the menu; exact rules, each operation says what to send and what you'll get back; hidden inside, the server can change its insides as long as the menu stays the same. A highlighted note: an AI model is just another kitchen; your code sends a request to the provider's API and gets a response back. Tip: API stands for application programming interface, a menu of operations one program offers another." width="800" height="640"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. An API is a menu that one program offers another.&lt;/strong&gt; API stands for &lt;strong&gt;application programming interface&lt;/strong&gt;. Picture a restaurant: the &lt;strong&gt;menu&lt;/strong&gt; tells you what you can order, you write an &lt;strong&gt;order slip&lt;/strong&gt;, the &lt;strong&gt;kitchen&lt;/strong&gt; does the work out of sight, and a &lt;strong&gt;plate&lt;/strong&gt; comes back. A web API is the same deal for software. A server offers a fixed set of operations, publishes exact rules for how to ask, and hides how it does the work. That last part matters: the kitchen can change its ovens as long as the menu stays the same. When your code “talks to” an AI model, it’s ordering from that provider’s API.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Ffya2flauuh5mx1ch51bc.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Ffya2flauuh5mx1ch51bc.png" alt="Diagram titled &amp;quot;Endpoints: one address, one job&amp;quot;. A toy URL, https://api.example.com/v1/weather?city=Chennai, split into labelled parts: base URL https://api.example.com, version /v1, path /weather, and query ?city=Chennai. A table for a toy café API, method plus path equals one operation: GET /v1/menu lists everything you can order; GET /v1/orders/1042 looks up one order by its id; POST /v1/orders places a new order with details in the body; DELETE /v1/orders/1042 cancels that order. Two notes: why /v1, so an API can launch a changed /v2 without breaking code written for /v1; query strings, small options ride in the URL after a question mark as name=value pairs joined by ampersands. Tip: an endpoint is one specific address that does one job, and the same path can do different jobs with different methods." width="800" height="673"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. An endpoint is one address that does one job.&lt;/strong&gt; Each item on the menu has its own URL, called an &lt;strong&gt;endpoint&lt;/strong&gt;: &lt;code&gt;https://api.example.com/v1/weather?city=Chennai&lt;/code&gt; breaks into a base URL, a version (&lt;code&gt;/v1&lt;/code&gt;), a path (&lt;code&gt;/weather&lt;/code&gt;) and an optional &lt;strong&gt;query string&lt;/strong&gt; after the &lt;code&gt;?&lt;/code&gt;. The HTTP &lt;strong&gt;method&lt;/strong&gt; says what to do at that address. In our toy café API:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;GET /v1/menu&lt;/code&gt; lists the menu;&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;GET /v1/orders/1042&lt;/code&gt; looks up one order;&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;POST /v1/orders&lt;/code&gt; places a new one;&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;DELETE /v1/orders/1042&lt;/code&gt; cancels it.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The version in the path lets an API launch a changed &lt;code&gt;/v2&lt;/code&gt; without breaking code written for &lt;code&gt;/v1&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fqjx81ccgiiuuc1j01oai.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fqjx81ccgiiuuc1j01oai.png" alt="Diagram titled &amp;quot;The request body: your order slip&amp;quot;. A code panel shows a request: POST /v1/orders HTTP/1.1, Host: api.example.com, Content-Type: application/json, a blank line, then the JSON body with &amp;quot;item&amp;quot;: &amp;quot;masala chai&amp;quot;, &amp;quot;qty&amp;quot;: 2 and &amp;quot;to_go&amp;quot;: true. Four numbered labels: 1, method plus path, which operation; 2, headers, Content-Type says the body is JSON; 3, blank line, headers end here; 4, body, the details of your order written in JSON. Two notes: body when you send data, creating or changing something, usually POST, PUT or PATCH, carries details in the body; no body when you only ask, a GET normally has no body and options go in the URL like ?city=Chennai. Preview note: calling an AI model is a POST whose JSON body holds your messages and settings, covered in Section 3. Tip: the request body is the data you send along with the request, usually as JSON." width="800" height="671"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. The request body carries the data you’re sending.&lt;/strong&gt; When you &lt;em&gt;create&lt;/em&gt; or &lt;em&gt;change&lt;/em&gt; something, usually with POST, PUT or PATCH, the details travel in the request &lt;strong&gt;body&lt;/strong&gt;: the order slip itself. A header, &lt;code&gt;Content-Type: application/json&lt;/code&gt;, tells the server the body is JSON. A GET, which only asks for something, normally has no body; its small options go in the URL instead. Calling an AI model is the same pattern: a POST whose JSON body holds your messages and settings.&lt;/p&gt;

&lt;h2&gt;
  
  
  Part B · JSON and the reply
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fp1j9gmdxbn6f3zj416rr.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fp1j9gmdxbn6f3zj416rr.png" alt="Diagram titled &amp;quot;JSON's six kinds of value&amp;quot;. On the left, one JSON object: &amp;quot;item&amp;quot;: &amp;quot;masala chai&amp;quot;, &amp;quot;qty&amp;quot;: 2, &amp;quot;to_go&amp;quot;: true, &amp;quot;note&amp;quot;: null, &amp;quot;extras&amp;quot;: (&amp;quot;ginger&amp;quot;, &amp;quot;less sugar&amp;quot;), and &amp;quot;customer&amp;quot; holding a nested object with &amp;quot;name&amp;quot;: &amp;quot;Asha&amp;quot; and &amp;quot;table&amp;quot;: 7. A caption says a key, left of the colon, names each value, right of it. On the right, six numbered cards: 1, text or string, &amp;quot;masala chai&amp;quot;, always in double quotes; 2, number, 2 or 4.5, no quotes, since quotes would make it text; 3, true or false, lowercase only; 4, nothing, null, a value that is deliberately empty; 5, list or array, (&amp;quot;ginger&amp;quot;, &amp;quot;less sugar&amp;quot;), ordered values in square brackets; 6, object, {&amp;quot;name&amp;quot;: &amp;quot;Asha&amp;quot;}, key-value pairs in curly braces, keys are text. A note: nest them like boxes; &amp;quot;customer&amp;quot; is an object inside the order object. Tip: JSON is plain text with just six kinds of value, and almost every language can read and write it." width="799" height="727"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;4. JSON is plain text built from six kinds of value.&lt;/strong&gt; &lt;strong&gt;JSON&lt;/strong&gt; (JavaScript Object Notation) writes data as &lt;strong&gt;keys&lt;/strong&gt; and &lt;strong&gt;values&lt;/strong&gt;. The JSON standard (RFC 8259) defines four simple types and two containers:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;text&lt;/strong&gt; (a &lt;em&gt;string&lt;/em&gt;) in double quotes: &lt;code&gt;"masala chai"&lt;/code&gt;;&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;numbers&lt;/strong&gt; with no quotes: &lt;code&gt;2&lt;/code&gt; or &lt;code&gt;4.5&lt;/code&gt;;&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;true&lt;/strong&gt; or &lt;strong&gt;false&lt;/strong&gt;;&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;null&lt;/strong&gt;, a deliberately empty value;&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;lists&lt;/strong&gt; (&lt;em&gt;arrays&lt;/em&gt;) of values in square brackets: &lt;code&gt;["ginger", "less sugar"]&lt;/code&gt;;&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;objects&lt;/strong&gt; of key-value pairs in curly braces: &lt;code&gt;{"name": "Asha"}&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Lists and objects can hold anything, including more lists and objects, so you can nest them like boxes. Despite the name, JSON isn’t tied to JavaScript; practically every language reads and writes it.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F2tu3plshw2b7le80etw5.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F2tu3plshw2b7le80etw5.png" alt="Diagram titled &amp;quot;Strict rules: spot the five mistakes&amp;quot;. Left panel, five mistakes, four of which won't even parse: an object with 'item': 'masala chai' in single quotes, marked 1; &amp;quot;qty&amp;quot;: &amp;quot;2&amp;quot; with the number in quotes, marked 2; &amp;quot;to_go&amp;quot;: True with a capital T, marked 3; &amp;quot;extras&amp;quot;: (&amp;quot;ginger&amp;quot;,) with a trailing comma, marked 4; and a comment line // no sugar, marked 5. Right panel, valid JSON: &amp;quot;item&amp;quot;: &amp;quot;masala chai&amp;quot;, &amp;quot;qty&amp;quot;: 2, &amp;quot;to_go&amp;quot;: true, &amp;quot;extras&amp;quot;: (&amp;quot;ginger&amp;quot;), &amp;quot;note&amp;quot;: &amp;quot;no sugar&amp;quot;. The five rules: 1, double quotes only for keys and text; 2, numbers without quotes, since &amp;quot;2&amp;quot; parses but as text so maths fails later; 3, lowercase true, false, null, because True and None are Python, not JSON; 4, no trailing commas after the last item; 5, no comments, make a note a real key and value. A sixth card: check it by pasting into a JSON validator or a browser console's JSON.parse. Tip: JSON is strict on purpose, so programs never have to guess." width="800" height="703"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;5. JSON is strict, and that’s a feature.&lt;/strong&gt; One slip and a parser rejects the whole message, so programs never have to guess what you meant. The same handful of mistakes cause most failures:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Double quotes only&lt;/strong&gt;, for keys and text. Single quotes are an error.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;No trailing comma&lt;/strong&gt; after the last item in a list or object.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;No comments.&lt;/strong&gt; If you need a note, make it a real key and value.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Lowercase&lt;/strong&gt; &lt;code&gt;true&lt;/code&gt;, &lt;code&gt;false&lt;/code&gt; and &lt;code&gt;null&lt;/code&gt;. &lt;code&gt;True&lt;/code&gt; and &lt;code&gt;None&lt;/code&gt; are Python, not JSON.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Don’t quote numbers.&lt;/strong&gt; &lt;code&gt;"2"&lt;/code&gt; is valid JSON, but it’s &lt;em&gt;text&lt;/em&gt;, so maths on it fails later. This is the sneaky one because nothing complains straight away.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F2v7p8895wy99tuhpuoug.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F2v7p8895wy99tuhpuoug.png" alt="Diagram titled &amp;quot;The response: a status code and a JSON answer&amp;quot;. Two code panels. It worked: HTTP/1.1 201 Created, Content-Type: application/json, body with &amp;quot;id&amp;quot;: &amp;quot;ord_1042&amp;quot;, &amp;quot;status&amp;quot;: &amp;quot;received&amp;quot;, &amp;quot;total_inr&amp;quot;: 120. It didn't: HTTP/1.1 404 Not Found, Content-Type: application/json, body with an &amp;quot;error&amp;quot; object holding &amp;quot;code&amp;quot;: &amp;quot;not_found&amp;quot; and &amp;quot;message&amp;quot;: &amp;quot;No order ord_9999&amp;quot;. Eight status code cards, the first two green, the rest orange: 200 OK, here's what you asked for; 201 Created, your new thing exists now; 400 Bad Request, the request is malformed; 401 Unauthorized, missing or wrong credentials; 404 Not Found, nothing at that address; 429 Too Many Requests, slow down and retry later; 500 Internal Server Error, the server broke; 503 Service Unavailable, overloaded or down for now. Tip: check the status code first, then read the body; an error reply still has a JSON body that usually tells you what went wrong." width="799" height="688"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;6. The response is a status code plus a JSON answer.&lt;/strong&gt; The plate comes back with a note saying how it went. Read the &lt;strong&gt;status code&lt;/strong&gt; first:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;200 OK&lt;/code&gt; or &lt;code&gt;201 Created&lt;/code&gt; mean it worked;&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;400&lt;/code&gt; means your request was malformed;&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;401&lt;/code&gt; means your credentials are missing or wrong;&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;404&lt;/code&gt; means there’s nothing at that address;&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;429&lt;/code&gt; means slow down;&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;500&lt;/code&gt; and &lt;code&gt;503&lt;/code&gt; mean the server is having a bad time.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Then read the &lt;strong&gt;body&lt;/strong&gt;. A good API sends JSON even when things fail, and that error object usually tells you exactly what went wrong: &lt;code&gt;"No order ord_9999"&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fay6vrj1wvqyzu24whtpf.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fay6vrj1wvqyzu24whtpf.png" alt="Diagram titled &amp;quot;How to read an API docs page&amp;quot;. A toy docs page for POST /v1/orders with seven numbered rows: 1, method and URL, POST https://api.example.com/v1/orders; 2, authentication, send your key in a header and never paste it into code you share; 3, parameters, item is text and required, qty is a number and required, to_go is true or false, optional, default false; 4, example request, a full JSON body you can copy and adapt; 5, example response, 201 plus the new order as JSON; 6, errors, 400 bad body, 401 bad key, 429 too many requests; 7, limits, how many requests per minute and how big a body can be. Two notes: read before you code, since most &amp;quot;it doesn't work&amp;quot; moments are a field name, type or required header the docs mentioned; often machine-readable too, since many APIs publish an OpenAPI file that tools can read and test against. Tip: reading API docs carefully is a core engineering skill, and a daily one in customer-facing roles." width="800" height="642"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;7. The docs are the menu, so read them first.&lt;/strong&gt; Good APIs publish documentation, and nearly all of it covers the same seven things:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;the method and URL;&lt;/li&gt;
&lt;li&gt;how to authenticate;&lt;/li&gt;
&lt;li&gt;the parameters, with their types and which are required;&lt;/li&gt;
&lt;li&gt;an example request;&lt;/li&gt;
&lt;li&gt;an example response;&lt;/li&gt;
&lt;li&gt;the errors it returns;&lt;/li&gt;
&lt;li&gt;the limits.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Most “it doesn’t work” moments turn out to be a field name, a type or a required header that the docs already mentioned. Many APIs also publish an &lt;strong&gt;OpenAPI&lt;/strong&gt; file: the same menu in a format tools can read. Reading docs carefully is a core engineering skill, and a daily one for anyone who integrates systems for customers.&lt;/p&gt;




&lt;h3&gt;
  
  
  Try it (10 minutes, no code)
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;Write a JSON object for a &lt;strong&gt;book you like&lt;/strong&gt; with five keys:&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;"title"&lt;/code&gt; (text);&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;"authors"&lt;/code&gt; (a list of text);&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;"pages"&lt;/code&gt; (a number);&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;"available"&lt;/code&gt; (true or false);&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;"rating"&lt;/code&gt; (null, because you haven’t decided yet).&lt;/li&gt;
&lt;li&gt;Check it. Either paste it into any online JSON validator, or open your browser’s developer tools (F12), click &lt;strong&gt;Console&lt;/strong&gt;, and type &lt;code&gt;JSON.parse('...')&lt;/code&gt; with your JSON between the single quotes. If it’s valid, you’ll see the object; if not, you’ll get an error pointing at the problem.&lt;/li&gt;
&lt;li&gt;Now break it on purpose, once for each rule in point 5, and read each error message.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Check your understanding:&lt;/strong&gt; how many problems can you find in this?&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;city&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;Pune&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;temp_c&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;31&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;raining&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="bp"&gt;False&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;(Answer: four. Single quotes around&lt;/em&gt; &lt;code&gt;city&lt;/code&gt;&lt;em&gt;;&lt;/em&gt; &lt;code&gt;False&lt;/code&gt; &lt;em&gt;should be&lt;/em&gt; &lt;code&gt;false&lt;/code&gt;&lt;em&gt;; there’s a trailing comma before&lt;/em&gt; &lt;code&gt;}&lt;/code&gt;&lt;em&gt;; and&lt;/em&gt; &lt;code&gt;"31"&lt;/code&gt; &lt;em&gt;parses but is text, not a number.)&lt;/em&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Common beginner mistakes
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Using single quotes or trailing commas. Both are invalid JSON.&lt;/li&gt;
&lt;li&gt;Writing numbers in quotes (&lt;code&gt;"5"&lt;/code&gt;), which turns them into text.&lt;/li&gt;
&lt;li&gt;Reading the body and ignoring the status code, or ignoring the error body when the status is bad.&lt;/li&gt;
&lt;li&gt;Guessing field names instead of opening the docs.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Takeaway
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;An API is a menu of operations. You pick an endpoint, send a JSON request body if you’re sending data, then check the status code and read the JSON that comes back. JSON has six kinds of value and strict rules, and docs tell you the rest.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Where this fits in my roadmap:&lt;/strong&gt; this is on-ramp material, outside my current study block. I work with APIs and JSON daily as a TypeScript engineer, so I’m writing it for readers starting from zero. Section 3 picks it up with real code: calling a web API from Python, API keys and rate limits, then your first LLM API call.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Over to you:&lt;/strong&gt; what’s an app on your phone that you now suspect is “just” calling an API? What would one of its endpoints be?&lt;/p&gt;




&lt;h3&gt;
  
  
  Sources
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;MDN: API (glossary). &lt;a href="https://developer.mozilla.org/en-US/docs/Glossary/API" rel="noopener noreferrer"&gt;https://developer.mozilla.org/en-US/docs/Glossary/API&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;MDN: Introduction to web APIs. &lt;a href="https://developer.mozilla.org/en-US/docs/Learn_web_development/Extensions/Client-side_APIs/Introduction" rel="noopener noreferrer"&gt;https://developer.mozilla.org/en-US/docs/Learn_web_development/Extensions/Client-side_APIs/Introduction&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;MDN: What is a URL? (scheme, domain, path, query parameters). &lt;a href="https://developer.mozilla.org/en-US/docs/Learn_web_development/Howto/Web_mechanics/What_is_a_URL" rel="noopener noreferrer"&gt;https://developer.mozilla.org/en-US/docs/Learn_web_development/Howto/Web_mechanics/What_is_a_URL&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;MDN: HTTP request methods and POST. &lt;a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Methods" rel="noopener noreferrer"&gt;https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Methods&lt;/a&gt; · &lt;a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Methods/POST" rel="noopener noreferrer"&gt;https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Methods/POST&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;RFC 9110: HTTP Semantics (methods, message content, status codes in §15). &lt;a href="https://www.rfc-editor.org/rfc/rfc9110" rel="noopener noreferrer"&gt;https://www.rfc-editor.org/rfc/rfc9110&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;MDN: Content-Type header. &lt;a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Content-Type" rel="noopener noreferrer"&gt;https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Content-Type&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;RFC 8259: The JavaScript Object Notation (JSON) Data Interchange Format (four primitive types and two structured types; strings in double quotes; lowercase literal names; the application/json media type). &lt;a href="https://www.rfc-editor.org/rfc/rfc8259" rel="noopener noreferrer"&gt;https://www.rfc-editor.org/rfc/rfc8259&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;ECMA-404: The JSON data interchange syntax. &lt;a href="https://ecma-international.org/publications-and-standards/standards/ecma-404/" rel="noopener noreferrer"&gt;https://ecma-international.org/publications-and-standards/standards/ecma-404/&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;MDN: Working with JSON, and JSON.parse(). &lt;a href="https://developer.mozilla.org/en-US/docs/Learn_web_development/Core/Scripting/JSON" rel="noopener noreferrer"&gt;https://developer.mozilla.org/en-US/docs/Learn_web_development/Core/Scripting/JSON&lt;/a&gt; · &lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse" rel="noopener noreferrer"&gt;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;MDN: HTTP response status codes; 201 Created; 429 Too Many Requests. &lt;a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status" rel="noopener noreferrer"&gt;https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status&lt;/a&gt; · &lt;a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/201" rel="noopener noreferrer"&gt;https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/201&lt;/a&gt; · &lt;a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/429" rel="noopener noreferrer"&gt;https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/429&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;RFC 6585: Additional HTTP Status Codes (429). &lt;a href="https://www.rfc-editor.org/rfc/rfc6585" rel="noopener noreferrer"&gt;https://www.rfc-editor.org/rfc/rfc6585&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;OpenAPI Specification (a standard, language-agnostic description of HTTP APIs). &lt;a href="https://spec.openapis.org/oas/latest.html" rel="noopener noreferrer"&gt;https://spec.openapis.org/oas/latest.html&lt;/a&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;em&gt;The café API, its URLs, order ids and prices are made up for teaching. Sources checked Oct 31, 2026.&lt;/em&gt;&lt;/p&gt;




&lt;p&gt;Free: &lt;a href="https://dhanushkumarsivaji.substack.com/p/the-path-to-ai-fde-the-free-roadmap" rel="noopener noreferrer"&gt;the 5-page roadmap from Novice to AI FDE&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;If this was useful, &lt;a href="https://dhanushkumarsivaji.substack.com/subscribe" rel="noopener noreferrer"&gt;subscribe to The Path to AI FDE&lt;/a&gt; for the next issue.&lt;/p&gt;

</description>
      <category>api</category>
      <category>json</category>
      <category>beginners</category>
      <category>webdev</category>
    </item>
    <item>
      <title>The path to AI FDE #06: How the internet works: clients, servers and requests</title>
      <dc:creator>Dhanush Kumar Sivaji</dc:creator>
      <pubDate>Mon, 09 Nov 2026 18:27:46 +0000</pubDate>
      <link>https://dev.to/dhanushkumarsivaji/the-path-to-ai-fde-06-how-the-internet-works-clients-servers-and-requests-iao</link>
      <guid>https://dev.to/dhanushkumarsivaji/the-path-to-ai-fde-06-how-the-internet-works-clients-servers-and-requests-iao</guid>
      <description>&lt;p&gt;&lt;em&gt;Originally published on my newsletter, The Path to AI FDE. &lt;a href="https://dhanushkumarsivaji.substack.com/subscribe" rel="noopener noreferrer"&gt;Subscribe free&lt;/a&gt; to get each issue by email.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;This is a &lt;strong&gt;“From Zero” issue&lt;/strong&gt;. Every AI app is a web app first. When a chatbot answers you, your device has sent a message across the internet to a server and waited for a reply. Before we get to AI APIs, it helps to know what actually happens in that round trip. No code today, just six ideas you’ll use for the rest of this series.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Faw2itus9m96xmdwu80r5.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Faw2itus9m96xmdwu80r5.png" alt="Infographic, &amp;quot;The Path to AI FDE #06: How the Internet Works, from Zero&amp;quot;, by Dhanush Kumar Sivaji. Subtitle: clients, servers and requests; every AI app is a web app first. Legend: blue is who and where, lavender is what gets sent, orange is a gotcha. Part A, who talks to whom. 1, Client and server: client and server linked by a two-way arrow; the client asks, and the server, a program on a computer elsewhere, answers. 2, IP addresses and DNS: example.com leads to 192.0.2.10; servers have numeric addresses, and DNS is the phone book that turns names into numbers. 3, Request and response: &amp;quot;GET /page&amp;quot; leads to &amp;quot;200 OK plus data&amp;quot;; method, path and headers go out, and status, headers and body come back. Part B, how the message travels. 4, HTTP and HTTPS: HTTP is a postcard, HTTPS is a sealed envelope. Gotcha: HTTP is the delivery rules, HTML is a page format. 5, Ports: 443 HTTPS, 80 HTTP, 22 SSH; the IP finds the machine and the port picks the program on it. 6, Latency: DNS, connect, secure, ask; each step is a round trip, and distance and extra trips add milliseconds. AI calls add model time on top, so apps stream. Tip bar: your code asks, a server answers, and every round trip costs time. Sources: MDN pages on the Internet, HTTP, DNS, ports and latency; RFC 9110; RFC 1034; RFC 8446; the IANA port registry; checked October 2026." width="800" height="662"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Part A · Who talks to whom
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fegeclxoe0pyyugi6s8ks.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fegeclxoe0pyyugi6s8ks.png" alt="Figure &amp;quot;Client asks, server answers&amp;quot;: every web conversation has two sides, one asks and one answers. On the left, box 1, Client: the program that asks and starts every conversation; examples: browser, phone app, a Python script. On the right, box 2, Server: a program on a computer elsewhere that waits and answers, running all day and listening for requests; examples: web pages, weather data, an AI model. Between them, an arrow labelled request goes right and a green arrow labelled response comes back. Below, the postal version of the same idea, in four cards: your letter equals the request, the address book equals DNS, the office that replies equals the server, the reply letter equals the response. Two notes: &amp;quot;The cloud&amp;quot; is servers in someone else's data centre that you rent, still ordinary computers, just not yours. Roles, not machines: client and server are jobs; your laptop can run a small server for testing, and a server can be a client of another server. Tip bar: every AI app you'll build works this way; your code is the client, and the model sits behind a server you send requests to." width="800" height="693"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. A client asks, and a server answers.&lt;/strong&gt; The &lt;strong&gt;client&lt;/strong&gt; is the program that starts the conversation: your browser, a phone app, or a small Python script. The &lt;strong&gt;server&lt;/strong&gt; is a program on a computer somewhere else that sits waiting for requests and answers them. Think of the post: you write a letter (the request), look up the address, the office reads it, and a reply letter comes back (the response).&lt;/p&gt;

&lt;p&gt;Two things trip beginners up here. “Client” and “server” are &lt;em&gt;roles&lt;/em&gt;, not special kinds of machine: your laptop can run a small server while you test, and a server can be a client of another server. And “the cloud” isn’t magic. It’s servers in someone else’s data centre that you rent by the hour.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fe03bbpzlzdehznoulvcg.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fe03bbpzlzdehznoulvcg.png" alt="Figure &amp;quot;Names for people, numbers for computers&amp;quot;: every server has a numeric IP address, and DNS looks it up from the name you type. Computers find each other by number. IPv4 address example 192.0.2.10: four numbers from 0 to 255, about 4.3 billion possible addresses, which turned out not to be enough. IPv6 address example 2001:db8::10: the newer, much longer format written in hex; both are in use today, often side by side. People use names, and DNS turns a name into a number, in four steps. 1, you type a name: your browser needs the address for example.com. 2, ask a resolver: a DNS server run by your internet provider, or a public one, does the hunting for you. 3, follow the chain: it asks the root servers, then the .com servers, then example.com's own name server. 4, get the number: back comes 192.0.2.10, and your device connects to that address. Two notes. Answers are cached: resolvers and your device remember answers for a set time, the TTL, so most lookups skip steps 3 and 4. Warning: broken DNS looks like &amp;quot;the site is down&amp;quot;; if the name can't be turned into a number, nothing else can start, even if the server is fine. Tip bar: DNS is the internet's phone book, names for people and numbers for computers; the addresses shown are reserved documentation examples." width="800" height="702"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Every server has a number, and DNS finds it from the name.&lt;/strong&gt; Computers find each other by &lt;strong&gt;IP address&lt;/strong&gt;. The older format, IPv4, looks like &lt;code&gt;192.0.2.10&lt;/code&gt;: four numbers from 0 to 255. That only allows about 4.3 billion addresses, so a much longer format, IPv6 (like &lt;code&gt;2001:db8::10&lt;/code&gt;), is now used alongside it. (Both examples are addresses reserved for documentation, so they don’t point at anyone’s real server.)&lt;/p&gt;

&lt;p&gt;People don’t remember numbers, so we use names like &lt;code&gt;example.com&lt;/code&gt;. The &lt;strong&gt;Domain Name System (DNS)&lt;/strong&gt; is the internet’s phone book. Your device asks a &lt;strong&gt;resolver&lt;/strong&gt; (usually run by your internet provider, or a public one). If the resolver doesn’t already know, it asks along a chain: the root servers, then the servers for &lt;code&gt;.com&lt;/code&gt;, then the name server for &lt;code&gt;example.com&lt;/code&gt; itself. The answer comes back as an IP address, and everyone along the way remembers it for a set time (the &lt;strong&gt;TTL&lt;/strong&gt;, time to live). That’s why most lookups are instant.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F0ob51o47zlhx6oytrhmj.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F0ob51o47zlhx6oytrhmj.png" alt="Figure &amp;quot;One request, one response&amp;quot;: the client asks in a fixed format, and the server replies with a status and some data. Left, the request from client to server, shown as text: &amp;quot;GET /index.html HTTP/1.1&amp;quot;, &amp;quot;Host: example.com&amp;quot;, &amp;quot;Accept: text/html&amp;quot;. Labelled parts: 1, method, what you want done, where GET means send me this; 2, path, which thing on the server; 3, headers, extra notes like &amp;quot;I'd like HTML&amp;quot;. Right, the response from server to client: &amp;quot;HTTP/1.1 200 OK&amp;quot;, &amp;quot;Content-Type: text/html&amp;quot;, a blank line, then an HTML doctype and the title &amp;quot;Example Domain&amp;quot;. Labelled parts: 4, status, a number saying how it went; 5, headers, notes like &amp;quot;this is HTML&amp;quot;; 6, body, the data itself. Below, the first digit of the status tells you who to look at: 2xx success, 200 OK, here's what you asked for; 3xx look elsewhere, the thing moved; 4xx problem with the request, 404 no such thing here; 5xx problem on the server, 500 it broke while trying. Tip bar: one request, one response, every time; newer HTTP versions send the same parts in a compact binary form, and the meaning doesn't change." width="800" height="641"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. The client sends a request, and the server sends one response.&lt;/strong&gt; A request says three main things:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;the &lt;strong&gt;method&lt;/strong&gt;, which is the action you want (&lt;code&gt;GET&lt;/code&gt; means “send me this”);&lt;/li&gt;
&lt;li&gt;the &lt;strong&gt;path&lt;/strong&gt;, which says what you want (&lt;code&gt;/index.html&lt;/code&gt;);&lt;/li&gt;
&lt;li&gt;the &lt;strong&gt;headers&lt;/strong&gt;, which are extra notes, such as “I’d like HTML back”.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The response comes back with a &lt;strong&gt;status code&lt;/strong&gt;, its own headers, and a &lt;strong&gt;body&lt;/strong&gt;: the actual data, whether that’s a web page, an image or, later in this series, an AI model’s answer.&lt;/p&gt;

&lt;p&gt;The first digit of the status code tells you where to look when something goes wrong:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;2xx means success (&lt;code&gt;200 OK&lt;/code&gt;);&lt;/li&gt;
&lt;li&gt;3xx means “look somewhere else”;&lt;/li&gt;
&lt;li&gt;4xx means the problem is in the request (&lt;code&gt;404 Not Found&lt;/code&gt;);&lt;/li&gt;
&lt;li&gt;5xx means the server failed (&lt;code&gt;500 Internal Server Error&lt;/code&gt;).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;em&gt;(The text format in the figure is HTTP/1.1. Newer versions, HTTP/2 and HTTP/3, pack the same parts into a compact binary form, but the meaning is the same.)&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Part B · How the message travels
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fycccrljmu4zrxm31i2hl.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fycccrljmu4zrxm31i2hl.png" alt="Figure &amp;quot;HTTP is a postcard, HTTPS is a sealed envelope&amp;quot;: same language and messages, but HTTPS encrypts them on the way. Same message, two ways to send it. HTTP, like a postcard: the message &amp;quot;POST /login, password=sunflower42&amp;quot; travels readable, and anyone on the path, such as café Wi-Fi or a router, can read it. HTTPS, HTTP inside a sealed envelope (TLS): the message travels as scrambled hex bytes, and only the server can open them. What the padlock in your browser gives you: private, the content is encrypted on the way; untampered, any change in transit is detected; the real site, a certificate proves you reached the real example.com. Still visible: which server you're talking to, its IP address and usually the site name, but not what you said. Warning, HTTP is not HTML: HTTP is the delivery rules, HTML is a page format, and HTTP also carries JSON, images and AI replies. Tip bar: treat HTTPS as the default; API keys and user data should never travel over plain HTTP." width="799" height="688"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;4. HTTP is the shared language, and HTTPS is the sealed version.&lt;/strong&gt; &lt;strong&gt;HTTP&lt;/strong&gt; (HyperText Transfer Protocol) is the set of rules for the request and response you just saw. Plain HTTP is like a postcard: anyone handling it along the way, such as a café Wi-Fi network, can read it. &lt;strong&gt;HTTPS&lt;/strong&gt; is the same HTTP wrapped in &lt;strong&gt;TLS&lt;/strong&gt; encryption, like a sealed envelope. The padlock in your browser gives you three things:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;privacy:&lt;/strong&gt; the content is encrypted;&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;integrity:&lt;/strong&gt; changes made in transit are detected;&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;authenticity:&lt;/strong&gt; a certificate proves you reached the real site.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;People on the network can still see &lt;em&gt;which&lt;/em&gt; server you’re talking to, but not what you said. For anything carrying passwords, API keys or user data, HTTPS is the only acceptable choice.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fehjhiv0umvmht23ocbk2.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fehjhiv0umvmht23ocbk2.png" alt="Figure &amp;quot;Ports: which door on the server&amp;quot;: one computer can run many services, and the port number says which one you want. One server at 192.0.2.10. An IP address finds the machine; a port number, 0 to 65535, picks which program on it gets the message. Four doors: 443 HTTPS, secure web and APIs; 80 HTTP, plain web, usually redirects to 443; 22 SSH, admins logging in; 5432 PostgreSQL, a database, kept private. Below, where the port hides in a web address: &amp;quot;https://&amp;quot; is the scheme, &amp;quot;example.com&amp;quot; the host, &amp;quot;:443&amp;quot; the port, &amp;quot;/docs&amp;quot; the path. Usually invisible: 443 is the default for https and 80 for http, so browsers leave it out, and https://example.com means port 443. You'll see ports soon: when you run a server on your own laptop you'll visit addresses like http://localhost:8000, and port 8000 is just a common choice for testing. Tip bar: IP address equals which building, port equals which door, and the scheme says which language to speak at that door." width="800" height="637"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;5. Ports say which program on the server should get the message.&lt;/strong&gt; One computer can run many services at once: a website, a database, a remote-login service. The IP address finds the machine, and the &lt;strong&gt;port number&lt;/strong&gt; (0 to 65535) picks the program. HTTPS uses port &lt;strong&gt;443&lt;/strong&gt; by default and plain HTTP uses &lt;strong&gt;80&lt;/strong&gt;, which is why you never type them.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://example.com" rel="noopener noreferrer"&gt;https://example.com&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;already means port 443. You’ll meet ports properly when you run a server on your own laptop and visit something like&lt;/p&gt;

&lt;p&gt;&lt;a href="http://localhost:8000" rel="noopener noreferrer"&gt;http://localhost:8000&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fh9dq30uq6qt4c2kyfzva.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fh9dq30uq6qt4c2kyfzva.png" alt="Figure &amp;quot;Latency: every round trip costs time&amp;quot;: before the first byte arrives, a new connection makes several trips there and back. A timeline for a first visit to an HTTPS site, with illustrative numbers assuming each round trip takes 50 milliseconds. 1, DNS lookup, name to number: 0 to 50 ms. 2, connect, TCP handshake: 50 to 100 ms. 3, secure, TLS 1.3 handshake: 100 to 150 ms. 4, ask and wait, request to response: 150 to 200 ms, followed by a short block of server work, ending around 240 ms. Distance sets a floor: light in optical fibre covers roughly 200 kilometres per millisecond, so a server 13,000 km away, India to the US East Coast, costs at least about 130 ms per round trip before it does any work. Reuse saves trips: later requests reuse the cached DNS answer and the open, secured connection, so they pay only step 4. Why AI apps care: an AI request adds the model's thinking time on top, so apps reuse connections, pick nearby regions and stream the answer so you see the first words sooner. Tip bar: latency is the waiting time for a round trip; fewer trips and shorter distances make apps feel fast." width="800" height="698"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;6. Latency is waiting time, and every round trip adds some.&lt;/strong&gt; &lt;strong&gt;Latency&lt;/strong&gt; is how long a message takes to get there and back. A first visit to an HTTPS site needs several round trips before the first byte of the page arrives:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;one to look up the name;&lt;/li&gt;
&lt;li&gt;one to open a connection (the TCP handshake);&lt;/li&gt;
&lt;li&gt;one to set up encryption (a TLS 1.3 handshake);&lt;/li&gt;
&lt;li&gt;one for the request itself.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Distance sets a hard floor. Light in optical fibre travels roughly 200 km per millisecond, so a server about 13,000 km away (say, India to the US East Coast) costs at least about 130 ms per round trip before it does any work. Later requests are cheaper because the DNS answer is cached and the secure connection stays open.&lt;/p&gt;

&lt;p&gt;AI apps care about milliseconds because a model call adds its own thinking time on top. That’s why they reuse connections, pick nearby regions and stream the answer word by word.&lt;/p&gt;




&lt;h3&gt;
  
  
  Try it (10 minutes, no code)
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;Open&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;a href="https://example.com" rel="noopener noreferrer"&gt;https://example.com&lt;/a&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;in Chrome, Edge or Firefox. This domain is reserved for examples, so it’s a safe toy.&lt;/li&gt;
&lt;li&gt;Open the developer tools (F12, or Cmd+Option+I on a Mac) and click the &lt;strong&gt;Network&lt;/strong&gt; tab.&lt;/li&gt;
&lt;li&gt;Reload the page. Click the first row, the request for the page itself.&lt;/li&gt;
&lt;li&gt;Find three things: the &lt;strong&gt;status code&lt;/strong&gt; (you should see 200), the &lt;strong&gt;method&lt;/strong&gt; (GET), and how long it took in the &lt;strong&gt;Time&lt;/strong&gt; column or the &lt;strong&gt;Timing&lt;/strong&gt; tab.&lt;/li&gt;
&lt;li&gt;Bonus: reload again and see if the time drops. Can you explain why using point 6?&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Check your understanding:&lt;/strong&gt; a friend says “the site is down”, but when you type its IP address directly, the page loads. Which of the six ideas is most likely broken? &lt;em&gt;(Answer: DNS, point 2. The server is fine; the name lookup isn’t.)&lt;/em&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Common beginner mistakes
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Thinking “the cloud” is something other than computers. It’s other people’s computers, rented.&lt;/li&gt;
&lt;li&gt;Mixing up HTTP and HTML. HTTP is the delivery protocol; HTML is one format of content it can carry, alongside JSON, images and more.&lt;/li&gt;
&lt;li&gt;Reading every error as “the server is broken”. A 4xx status means the request was wrong; a 5xx means the server failed.&lt;/li&gt;
&lt;li&gt;Sending passwords or API keys over plain &lt;code&gt;http://&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Takeaway
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;A client sends a request to a server it found through DNS, at a port, usually over HTTPS. The server sends back a status and some data, and every round trip costs time. Every AI API call you’ll ever make follows this exact path.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Where this fits in my roadmap:&lt;/strong&gt; this is on-ramp material, outside my current study block. I use these ideas every day as a TypeScript engineer, and I’m writing them down for readers starting from zero. Section 3 comes back to HTTP up close: methods, URLs, headers and status codes, with real code.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Over to you:&lt;/strong&gt; what’s the slowest website or app you use regularly? After today, which of the six steps would you blame first?&lt;/p&gt;




&lt;h3&gt;
  
  
  Sources
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;MDN: How does the Internet work? (packets, routers, clients and servers). &lt;a href="https://developer.mozilla.org/en-US/docs/Learn_web_development/Howto/Web_mechanics/How_does_the_Internet_work" rel="noopener noreferrer"&gt;https://developer.mozilla.org/en-US/docs/Learn_web_development/Howto/Web_mechanics/How_does_the_Internet_work&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;MDN: An overview of HTTP (client-server protocol, message structure, HTTP/2 framing). &lt;a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/Overview" rel="noopener noreferrer"&gt;https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/Overview&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;RFC 9110: HTTP Semantics (methods, status code classes 1xx to 5xx, the http and https schemes, default ports 80 and 443). &lt;a href="https://www.rfc-editor.org/rfc/rfc9110" rel="noopener noreferrer"&gt;https://www.rfc-editor.org/rfc/rfc9110&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;MDN: HTTP response status codes. &lt;a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status" rel="noopener noreferrer"&gt;https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;RFC 1034: Domain Names, Concepts and Facilities (resolvers, name servers, caching, TTL). &lt;a href="https://www.rfc-editor.org/rfc/rfc1034" rel="noopener noreferrer"&gt;https://www.rfc-editor.org/rfc/rfc1034&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;MDN: DNS (glossary) and What is a domain name? &lt;a href="https://developer.mozilla.org/en-US/docs/Glossary/DNS" rel="noopener noreferrer"&gt;https://developer.mozilla.org/en-US/docs/Glossary/DNS&lt;/a&gt; · &lt;a href="https://developer.mozilla.org/en-US/docs/Learn_web_development/Howto/Web_mechanics/What_is_a_domain_name" rel="noopener noreferrer"&gt;https://developer.mozilla.org/en-US/docs/Learn_web_development/Howto/Web_mechanics/What_is_a_domain_name&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;RFC 791 (IPv4, 32-bit addresses) and RFC 8200 (IPv6). &lt;a href="https://www.rfc-editor.org/rfc/rfc791" rel="noopener noreferrer"&gt;https://www.rfc-editor.org/rfc/rfc791&lt;/a&gt; · &lt;a href="https://www.rfc-editor.org/rfc/rfc8200" rel="noopener noreferrer"&gt;https://www.rfc-editor.org/rfc/rfc8200&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;RFC 5737 (IPv4 documentation addresses, 192.0.2.0/24), RFC 3849 (IPv6 documentation prefix, 2001:db8::/32) and RFC 2606 (example.com reserved). &lt;a href="https://www.rfc-editor.org/rfc/rfc5737" rel="noopener noreferrer"&gt;https://www.rfc-editor.org/rfc/rfc5737&lt;/a&gt; · &lt;a href="https://www.rfc-editor.org/rfc/rfc3849" rel="noopener noreferrer"&gt;https://www.rfc-editor.org/rfc/rfc3849&lt;/a&gt; · &lt;a href="https://www.rfc-editor.org/rfc/rfc2606" rel="noopener noreferrer"&gt;https://www.rfc-editor.org/rfc/rfc2606&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;MDN: HTTPS and TLS (glossary). &lt;a href="https://developer.mozilla.org/en-US/docs/Glossary/HTTPS" rel="noopener noreferrer"&gt;https://developer.mozilla.org/en-US/docs/Glossary/HTTPS&lt;/a&gt; · &lt;a href="https://developer.mozilla.org/en-US/docs/Glossary/TLS" rel="noopener noreferrer"&gt;https://developer.mozilla.org/en-US/docs/Glossary/TLS&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;RFC 8446: TLS 1.3 (confidentiality, integrity, server authentication; one-round-trip full handshake). &lt;a href="https://www.rfc-editor.org/rfc/rfc8446" rel="noopener noreferrer"&gt;https://www.rfc-editor.org/rfc/rfc8446&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;MDN: Port (glossary) and What is a URL? &lt;a href="https://developer.mozilla.org/en-US/docs/Glossary/Port" rel="noopener noreferrer"&gt;https://developer.mozilla.org/en-US/docs/Glossary/Port&lt;/a&gt; · &lt;a href="https://developer.mozilla.org/en-US/docs/Learn_web_development/Howto/Web_mechanics/What_is_a_URL" rel="noopener noreferrer"&gt;https://developer.mozilla.org/en-US/docs/Learn_web_development/Howto/Web_mechanics/What_is_a_URL&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;IANA: Service Name and Transport Protocol Port Number Registry (22 ssh, 80 http, 443 https, 5432 postgresql). &lt;a href="https://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xhtml" rel="noopener noreferrer"&gt;https://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xhtml&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;MDN: Understanding latency (first request includes DNS lookup, TCP handshake and TLS negotiation) and Round Trip Time. &lt;a href="https://developer.mozilla.org/en-US/docs/Web/Performance/Guides/Understanding_latency" rel="noopener noreferrer"&gt;https://developer.mozilla.org/en-US/docs/Web/Performance/Guides/Understanding_latency&lt;/a&gt; · &lt;a href="https://developer.mozilla.org/en-US/docs/Glossary/Round_Trip_Time" rel="noopener noreferrer"&gt;https://developer.mozilla.org/en-US/docs/Glossary/Round_Trip_Time&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;RFC 9293: Transmission Control Protocol (three-way handshake). &lt;a href="https://www.rfc-editor.org/rfc/rfc9293" rel="noopener noreferrer"&gt;https://www.rfc-editor.org/rfc/rfc9293&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Chrome DevTools: Inspect network activity; Firefox: Network Monitor (for Try it). &lt;a href="https://developer.chrome.com/docs/devtools/network" rel="noopener noreferrer"&gt;https://developer.chrome.com/docs/devtools/network&lt;/a&gt; · &lt;a href="https://firefox-source-docs.mozilla.org/devtools-user/network_monitor/" rel="noopener noreferrer"&gt;https://firefox-source-docs.mozilla.org/devtools-user/network_monitor/&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Wikipedia: Optical fiber (typical core refractive index about 1.47, so light travels at roughly 200,000 km/s, about 200 km per millisecond). &lt;a href="https://en.wikipedia.org/wiki/Optical_fiber" rel="noopener noreferrer"&gt;https://en.wikipedia.org/wiki/Optical_fiber&lt;/a&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;em&gt;Sources checked Oct 31, 2026.&lt;/em&gt;&lt;/p&gt;




&lt;p&gt;Free: &lt;a href="https://dhanushkumarsivaji.substack.com/p/the-path-to-ai-fde-the-free-roadmap" rel="noopener noreferrer"&gt;the 5-page roadmap from Novice to AI FDE&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;If this was useful, &lt;a href="https://dhanushkumarsivaji.substack.com/subscribe" rel="noopener noreferrer"&gt;subscribe to The Path to AI FDE&lt;/a&gt; for the next issue.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>beginners</category>
      <category>networking</category>
      <category>ai</category>
    </item>
    <item>
      <title>The path to AI FDE #05: AI, ML and LLMs in plain words, and how an LLM writes</title>
      <dc:creator>Dhanush Kumar Sivaji</dc:creator>
      <pubDate>Fri, 23 Oct 2026 17:16:40 +0000</pubDate>
      <link>https://dev.to/dhanushkumarsivaji/the-path-to-ai-fde-05-ai-ml-and-llms-in-plain-words-and-how-an-llm-writes-370h</link>
      <guid>https://dev.to/dhanushkumarsivaji/the-path-to-ai-fde-05-ai-ml-and-llms-in-plain-words-and-how-an-llm-writes-370h</guid>
      <description>&lt;p&gt;&lt;em&gt;Originally published on my newsletter, The Path to AI FDE. &lt;a href="https://dhanushkumarsivaji.substack.com/subscribe" rel="noopener noreferrer"&gt;Subscribe free&lt;/a&gt; to get each issue by email.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;This is a &lt;strong&gt;“From Zero” issue&lt;/strong&gt;. If you’ve never written code or used an AI API, start here. If you’re a developer, the second half (how text actually gets generated) explains most of the weird behaviour you’ll meet later. No maths and no code: just the words people throw around, and what’s going on underneath.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fjlmmqf5byrmyhjjawmb7.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fjlmmqf5byrmyhjjawmb7.png" alt="Two panels. Part A, the words: nested boxes showing AI containing machine learning, containing deep learning, containing large language models, plus cards on foundation models, generative AI and hallucinations. Part B, how an LLM writes: text split into tokens, a ranked list of likely next tokens, a loop that adds one token at a time, a temperature dial, training stages, and a reminder that each call starts with no memory" width="800" height="1145"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  Part A · The words, in plain English
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F1773g98uo615wad72qgq.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F1773g98uo615wad72qgq.png" alt="Nested, not synonyms: artificial intelligence contains machine learning, which contains deep learning, which contains large language models, each with everyday examples" width="800" height="709"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. AI is the broad umbrella.&lt;/strong&gt; The OECD’s definition, widely cited in AI policy, boils down to this: an AI system is a machine that works out, from the input it gets, how to produce outputs such as predictions, content, recommendations or decisions. Systems differ in how independently they act and whether they keep adapting after launch.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fb5yaxhuffm6s0599h9ue.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fb5yaxhuffm6s0599h9ue.png" alt="Rules vs learning from examples: a spam filter built from hand-written rules next to one trained on labelled emails, plus Google's four ML families: supervised, unsupervised, reinforcement and generative AI" width="800" height="629"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Machine learning means learning from examples instead of hand-written rules.&lt;/strong&gt; You &lt;em&gt;train&lt;/em&gt; a piece of software called a &lt;strong&gt;model&lt;/strong&gt; on data, and it learns to make predictions or generate content. Google’s crash course sorts ML into four families: supervised (learning from labelled examples), unsupervised (finding patterns without labels), reinforcement (learning from rewards) and generative AI.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. Deep learning is ML with large neural networks.&lt;/strong&gt; Many-layered networks learn their own features from raw input (pixels, characters) instead of humans designing them. The approach took off around 2010 and powers nearly everything that follows.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;4. A large language model (LLM) is a deep network trained on a huge amount of text to predict what comes next.&lt;/strong&gt; Do that across a large slice of the written internet, and the model picks up grammar, facts, style and a surprising amount of reasoning-like behaviour along the way.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fiul3yf5krkvo71etpcoc.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fiul3yf5krkvo71etpcoc.png" alt="Foundation models and generative AI: one big model trained on broad data feeds many tasks; a generative model writes a new paragraph while a fraud detector only labels a payment" width="800" height="531"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;5. A foundation model is one big model reused for many jobs.&lt;/strong&gt; Researchers at Stanford coined the term in 2021 for models trained on broad data at scale and then adapted to a wide range of tasks. That’s why companies build products &lt;em&gt;on top of&lt;/em&gt; a few such models instead of training their own.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;6. Generative AI creates new content.&lt;/strong&gt; Text, images, audio or code from your input, instead of just a label. Every LLM chatbot is generative AI, but not all AI is generative: a fraud detector that says “suspicious: yes/no” isn’t.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F5v5xwe514j5tjg2e8coj.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F5v5xwe514j5tjg2e8coj.png" alt="Hallucinations: a confident wrong birthday; why guessing beats " width="800" height="653"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;7. A hallucination is a confident answer that’s wrong.&lt;/strong&gt; OpenAI defines it as a plausible but false statement. Part of the cause is that training and evaluation reward a good guess over “I don’t know”, and rare facts, like one person’s birthday, can’t be inferred from patterns in text. So an LLM is a brilliant pattern engine, not a database of verified facts. This is why later issues ground answers in real documents.&lt;/p&gt;

&lt;h2&gt;
  
  
  Part B · How an LLM writes text (no maths)
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fduc55q5ovlojx19erfyy.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fduc55q5ovlojx19erfyy.png" alt="Tokens in, scores out: " width="800" height="594"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;8. Text becomes tokens first.&lt;/strong&gt; The model reads &lt;strong&gt;tokens&lt;/strong&gt;: common words, word pieces and punctuation, not letters or whole words. Everything is counted in tokens, including limits and prices.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;9. At each step it scores every possible next token.&lt;/strong&gt; Given everything so far, each token in the vocabulary gets a likelihood. (The figure’s bars are illustrative, not from a real model.)&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F1qkfmesu4002krxsoa6o.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F1qkfmesu4002krxsoa6o.png" alt="How an LLM writes: a loop of score, pick and append that repeats until an end token, stop sequence or length limit; low temperature is focused, high temperature is varied" width="800" height="646"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;10. It writes one token at a time, in a loop.&lt;/strong&gt; Each new token depends on all the ones before it, and the loop stops at a special end token, a stop sequence you set, or a length limit. That’s why answers stream in word by word, and why long answers take longer.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;11. A little randomness is on purpose.&lt;/strong&gt; The model doesn’t always take the top choice. &lt;strong&gt;Temperature&lt;/strong&gt; is the dial (higher is more varied, lower more focused), and settings like top-p limit picks to the most likely candidates. So the same question can give different answers, and that’s normal.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fedzjh4vcgn6oc5hflsht.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fedzjh4vcgn6oc5hflsht.png" alt="Two training stages: pre-training on raw text to predict the next token with no human labels, then tuning on examples and feedback to follow instructions, as in InstructGPT (2022)" width="800" height="477"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;12. Two training stages: read a lot, then learn to help.&lt;/strong&gt; Pre-training is self-supervised: the model reads raw text and learns to predict the next token, no human labelling needed. Then it’s tuned on examples and feedback so it follows instructions instead of just continuing text. InstructGPT (2022) was an early public example.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F0pn1b3jiurze36xl7n5i.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F0pn1b3jiurze36xl7n5i.png" alt="Every call starts from zero: on turn 2 the chat app resends turn 1 so the model can answer " width="799" height="487"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;13. Every call starts from zero.&lt;/strong&gt; The model doesn’t remember your last message. Chat apps feel continuous because they resend the whole conversation with each request. (That’s the stateless API from #01: memory is the app’s job, not the model’s.)&lt;/p&gt;




&lt;h3&gt;
  
  
  Try it (10 minutes, no code)
&lt;/h3&gt;

&lt;p&gt;In any chatbot, ask the same open question three times in fresh chats (”Give me a name for a bakery”) and compare the answers. Then ask something obscure and specific, such as a small-town council member’s birthday, and notice how confident the answer sounds. You’ve just seen points 11 and 7.&lt;/p&gt;

&lt;h3&gt;
  
  
  Common beginner mistakes
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Treating “AI”, “ML” and “LLM” as synonyms. They’re nested, not the same.&lt;/li&gt;
&lt;li&gt;Assuming the model looks facts up. By default it predicts; it doesn’t retrieve.&lt;/li&gt;
&lt;li&gt;Thinking the chatbot remembers you. The app resends history.&lt;/li&gt;
&lt;li&gt;Counting words instead of tokens when estimating limits or cost.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Takeaway
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;An LLM is a next-token predictor, trained on a lot of text and then tuned to be helpful. It writes one token at a time with a bit of chosen randomness, and it remembers nothing between calls.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Where this fits in my roadmap:&lt;/strong&gt; this is on-ramp material, not part of my current study block. I already work with these ideas as a TypeScript engineer, so I’m writing it for readers starting from zero. It also gives later issues shared vocabulary. The deeper versions (tokenizers, context windows, prefill and decode, sampling, how training works) come in Section 6, once my roadmap gets there.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Over to you:&lt;/strong&gt; which AI term did you nod along to for longest before you really knew what it meant?&lt;/p&gt;




&lt;h3&gt;
  
  
  Sources
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;OECD.AI: Updates to the OECD’s definition of an AI system explained (2023). &lt;a href="https://oecd.ai/en/wonk/ai-system-definition-update" rel="noopener noreferrer"&gt;https://oecd.ai/en/wonk/ai-system-definition-update&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Google ML Crash Course: What is machine learning? (training a model on data; supervised, unsupervised, reinforcement, generative AI). &lt;a href="https://developers.google.com/machine-learning/intro-to-ml/what-is-ml" rel="noopener noreferrer"&gt;https://developers.google.com/machine-learning/intro-to-ml/what-is-ml&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Bommasani et al., On the Opportunities and Risks of Foundation Models (Stanford CRFM, 2021): defines “foundation model”; history of deep learning. &lt;a href="https://arxiv.org/abs/2108.07258" rel="noopener noreferrer"&gt;https://arxiv.org/abs/2108.07258&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Hugging Face LLM Course, Ch. 1: How do Transformers work? (self-supervised pre-training on raw text; causal language modelling; fine-tuning; InstructGPT, Jan 2022). &lt;a href="https://huggingface.co/learn/llm-course/chapter1/4" rel="noopener noreferrer"&gt;https://huggingface.co/learn/llm-course/chapter1/4&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Hugging Face LLM Course, Ch. 1: Deep dive into text generation inference (one token at a time; temperature, top-p, top-k; stop conditions). &lt;a href="https://huggingface.co/learn/llm-course/chapter1/8" rel="noopener noreferrer"&gt;https://huggingface.co/learn/llm-course/chapter1/8&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Hugging Face LLM Course, Ch. 2: Tokenizers (”token” + “ization”). &lt;a href="https://huggingface.co/learn/llm-course/chapter2/4" rel="noopener noreferrer"&gt;https://huggingface.co/learn/llm-course/chapter2/4&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;OpenAI: Why language models hallucinate (Sep 5, 2025). &lt;a href="https://openai.com/index/why-language-models-hallucinate/" rel="noopener noreferrer"&gt;https://openai.com/index/why-language-models-hallucinate/&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Anthropic: Working with the Messages API (stateless; resend the conversation). &lt;a href="https://platform.claude.com/docs/en/build-with-claude/working-with-messages" rel="noopener noreferrer"&gt;https://platform.claude.com/docs/en/build-with-claude/working-with-messages&lt;/a&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;em&gt;Sources checked Oct 18, 2026.&lt;/em&gt;&lt;/p&gt;




&lt;p&gt;Free: &lt;a href="https://dhanushkumarsivaji.substack.com/p/the-path-to-ai-fde-the-free-roadmap" rel="noopener noreferrer"&gt;the 5-page roadmap from Novice to AI FDE&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;If this was useful, &lt;a href="https://dhanushkumarsivaji.substack.com/subscribe" rel="noopener noreferrer"&gt;subscribe to The Path to AI FDE&lt;/a&gt; for the next issue.&lt;/p&gt;

</description>
      <category>ai</category>
      <category>llm</category>
      <category>machinelearning</category>
      <category>programming</category>
    </item>
    <item>
      <title>The path to AI FDE #04: Many calls at once, and a FastAPI service you can lean on</title>
      <dc:creator>Dhanush Kumar Sivaji</dc:creator>
      <pubDate>Thu, 22 Oct 2026 17:14:51 +0000</pubDate>
      <link>https://dev.to/dhanushkumarsivaji/the-path-to-ai-fde-04-many-calls-at-once-and-a-fastapi-service-you-can-lean-on-22l9</link>
      <guid>https://dev.to/dhanushkumarsivaji/the-path-to-ai-fde-04-many-calls-at-once-and-a-fastapi-service-you-can-lean-on-22l9</guid>
      <description>&lt;p&gt;&lt;em&gt;Originally published on my newsletter, The Path to AI FDE. &lt;a href="https://dhanushkumarsivaji.substack.com/subscribe" rel="noopener noreferrer"&gt;Subscribe free&lt;/a&gt; to get each issue by email.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Issue #03 ended with tasks: the way async work actually overlaps. Real AI backends fan out, calling a model several times or fetching a few sources in parallel. So this issue starts with how to do that without losing errors or hanging forever. Then it turns to the FastAPI features that move an endpoint past hello-world. As always, every example is a toy one (a notes app), not my roadmap exercises.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F14l7frqyjv1dhqiujmcu.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F14l7frqyjv1dhqiujmcu.png" alt="Two panels. Part A, many calls at once: six cards on gather, TaskGroup, timeouts, semaphores and cancellation. Part B, FastAPI properly: six cards on request and response models, HTTPException, dependencies, def versus async def, and settings" width="800" height="1118"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  Part A · Many calls at once
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F41v148xpxsngtj1ul9b6.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F41v148xpxsngtj1ul9b6.png" alt="gather: three fetches finish in a different order than they were started, but gather returns results in argument order; by default the first error is raised and the others keep running, while return_exceptions=True puts errors in the list" width="800" height="676"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1.&lt;/strong&gt; &lt;code&gt;gather&lt;/code&gt; &lt;strong&gt;returns results in the order you asked.&lt;/strong&gt; &lt;code&gt;a, b = await asyncio.gather(fetch(1), fetch(2))&lt;/code&gt; runs both concurrently, and the result list matches the order of the arguments, not the order the calls finished in. It’s the closest thing to &lt;code&gt;Promise.all&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Know what&lt;/strong&gt; &lt;code&gt;gather&lt;/code&gt; &lt;strong&gt;does with an error.&lt;/strong&gt; By default, the first exception is raised straight to you, and the other calls are &lt;em&gt;not&lt;/em&gt; cancelled: they keep running in the background. With &lt;code&gt;return_exceptions=True&lt;/code&gt;, errors come back as items in the result list instead, which suits best-effort work.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Faon0vs0x7yd69lxl5ynr.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Faon0vs0x7yd69lxl5ynr.png" alt="TaskGroup: when one of three tasks fails the other two are cancelled, and the failures are raised together as an ExceptionGroup handled with except-star" width="800" height="553"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3.&lt;/strong&gt; &lt;code&gt;TaskGroup&lt;/code&gt; &lt;strong&gt;is all-or-nothing.&lt;/strong&gt; Inside &lt;code&gt;async with asyncio.TaskGroup() as tg:&lt;/code&gt;, you start work with &lt;code&gt;tg.create_task(...)&lt;/code&gt;. The first failure cancels the rest, and when the block exits the failures are raised together as an &lt;code&gt;ExceptionGroup&lt;/code&gt;, which you handle with &lt;code&gt;except* SomeError:&lt;/code&gt;. Use it when partial results are useless. It also keeps task references for you (#03, point 11).&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F5epbw834sctebnw3p7ey.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F5epbw834sctebnw3p7ey.png" alt="Every network wait needs a deadline: a slow call is cancelled at 10 seconds and TimeoutError is raised; catch it outside the async with asyncio.timeout block, not inside" width="800" height="647"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;4. Every network wait needs a deadline.&lt;/strong&gt; &lt;code&gt;async with asyncio.timeout(10):&lt;/code&gt; cancels whatever is inside after 10 seconds and raises &lt;code&gt;TimeoutError&lt;/code&gt;, which you can only catch &lt;em&gt;outside&lt;/em&gt; the block. For a single awaitable, &lt;code&gt;await asyncio.wait_for(coro, timeout=10)&lt;/code&gt; does the same job. Without a deadline, one slow provider call can hold a request open indefinitely.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fme3d746o05vbpyqydc11.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fme3d746o05vbpyqydc11.png" alt="A semaphore caps how many run at once: items wait in a queue while at most five calls are in flight in Semaphore(5)'s slots" width="800" height="552"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;5. A semaphore caps how many run at once.&lt;/strong&gt; &lt;code&gt;sem = asyncio.Semaphore(5)&lt;/code&gt;, then &lt;code&gt;async with sem:&lt;/code&gt; around each call, lets at most five run concurrently while the rest wait their turn. That’s how you fan out over 200 items while keeping concurrency low enough to stay under a provider’s rate limit (the 429s from #01).&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F3i0ai1rswix3w0sl3mig.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F3i0ai1rswix3w0sl3mig.png" alt="Don't swallow cancellation: timeout and TaskGroup cancel a task, CancelledError must travel up; catching BaseException and passing hides it, while catching specific errors with try/finally lets it through" width="800" height="608"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;6. Don’t swallow cancellation.&lt;/strong&gt; &lt;code&gt;TaskGroup&lt;/code&gt; and &lt;code&gt;timeout()&lt;/code&gt; work by cancelling tasks, and the asyncio docs warn that they can misbehave if your code catches and hides &lt;code&gt;asyncio.CancelledError&lt;/code&gt;. A bare &lt;code&gt;except:&lt;/code&gt;, an &lt;code&gt;except BaseException:&lt;/code&gt; or a re-raise you forgot quietly breaks your deadlines. (&lt;code&gt;except Exception:&lt;/code&gt; doesn’t catch it: since Python 3.8, &lt;code&gt;CancelledError&lt;/code&gt; is a &lt;code&gt;BaseException&lt;/code&gt;.) Catch specific errors (#02, point 4).&lt;/p&gt;

&lt;h2&gt;
  
  
  Part B · FastAPI properly
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fsoz9710gp3x32oy6ioyf.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fsoz9710gp3x32oy6ioyf.png" alt="FastAPI validates both directions: a toy notes app request passes NoteIn validation (invalid gives 422), the handler, and a NoteOut response model that drops owner_id; HTTPException returns a 404 for a missing note" width="800" height="559"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;7. Request models give you 422s for free.&lt;/strong&gt; Declare a body parameter as a Pydantic model (&lt;code&gt;note: NoteIn&lt;/code&gt;), and FastAPI validates the request, answering &lt;code&gt;422&lt;/code&gt; with a list of what’s wrong before your function even runs.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;8. Response models validate and filter what goes out.&lt;/strong&gt; Set a return type or &lt;code&gt;response_model=NoteOut&lt;/code&gt;, and FastAPI checks your output and drops any field the model doesn’t declare. That’s the docs’ security point: an internal field (an owner ID, a password hash) can’t leak just because it was on the object you returned. If you set both, &lt;code&gt;response_model&lt;/code&gt; takes priority.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;9.&lt;/strong&gt; &lt;code&gt;HTTPException&lt;/code&gt; &lt;strong&gt;for errors you mean.&lt;/strong&gt; &lt;code&gt;raise HTTPException(status_code=404, detail="Note not found")&lt;/code&gt; stops the handler and returns that status with a JSON body. Raise it for expected failures: a missing item, a bad state, an upstream provider that’s down.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F5oc2t692zoaw5zcvagng.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F5oc2t692zoaw5zcvagng.png" alt="Dependencies: get_db, get_current_user and get_settings feed an endpoint through an Annotated Depends alias; settings read from environment variables are validated by BaseSettings, cached with lru_cache and overridden in tests" width="800" height="700"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;10. Dependencies hold the shared plumbing.&lt;/strong&gt; A dependency is a function FastAPI calls for you before your endpoint runs, declared as a parameter with &lt;code&gt;Depends(get_db)&lt;/code&gt;, usually through an &lt;code&gt;Annotated&lt;/code&gt; alias so it’s written once. Shared logic, database sessions and auth live there instead of in every handler. Dependencies can be &lt;code&gt;async def&lt;/code&gt; or plain &lt;code&gt;def&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fy60guuf4hagwtui6z63q.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fy60guuf4hagwtui6z63q.png" alt="def vs async def endpoints: async def runs on the shared event loop and suits async clients; plain def runs in an external threadpool and suits synchronous libraries; avoid blocking calls inside async def" width="799" height="527"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;11.&lt;/strong&gt; &lt;code&gt;def&lt;/code&gt; &lt;strong&gt;versus&lt;/strong&gt; &lt;code&gt;async def&lt;/code&gt; &lt;strong&gt;endpoints.&lt;/strong&gt; An &lt;code&gt;async def&lt;/code&gt; endpoint runs on the event loop, so anything blocking inside it stalls every request (#03, point 12). A plain &lt;code&gt;def&lt;/code&gt; endpoint runs in a threadpool instead, so blocking calls there are survivable. Rule of thumb: &lt;code&gt;async def&lt;/code&gt; with async clients, plain &lt;code&gt;def&lt;/code&gt; when your libraries are synchronous.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;12. Settings come from the environment, validated.&lt;/strong&gt; A &lt;code&gt;pydantic-settings&lt;/code&gt; &lt;code&gt;BaseSettings&lt;/code&gt; class reads environment variables (case-insensitively) and validates their types when it’s created. A missing API key or &lt;code&gt;TIMEOUT_S=abc&lt;/code&gt; fails right there, not halfway through a request that uses it: at startup if you create the settings at import time, or on first use if you serve them the way the FastAPI docs do, from an &lt;code&gt;@lru_cache&lt;/code&gt;‘d &lt;code&gt;get_settings()&lt;/code&gt; dependency. That dependency also lets tests swap settings with &lt;code&gt;app.dependency_overrides&lt;/code&gt;.&lt;/p&gt;




&lt;h3&gt;
  
  
  Try it (20 minutes, toy example)
&lt;/h3&gt;

&lt;p&gt;Make &lt;code&gt;async def fetch(i)&lt;/code&gt; that sleeps for a random 0–2 seconds and sometimes raises. Run 20 of them three ways: &lt;code&gt;gather&lt;/code&gt;, &lt;code&gt;gather(return_exceptions=True)&lt;/code&gt; and a &lt;code&gt;TaskGroup&lt;/code&gt;. Then add &lt;code&gt;Semaphore(5)&lt;/code&gt; and a 1-second &lt;code&gt;timeout&lt;/code&gt;, and compare what you get back each time. For the FastAPI half, give a toy notes app a &lt;code&gt;NoteOut&lt;/code&gt; model without an internal &lt;code&gt;owner_id&lt;/code&gt; field, return an object that has one, and check that it doesn’t appear in the response.&lt;/p&gt;

&lt;h3&gt;
  
  
  Common beginner mistakes
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Assuming &lt;code&gt;gather&lt;/code&gt; stops the other calls when one fails.&lt;/li&gt;
&lt;li&gt;Writing &lt;code&gt;try/except TimeoutError&lt;/code&gt; &lt;em&gt;inside&lt;/em&gt; &lt;code&gt;async with asyncio.timeout()&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Fanning out with no concurrency limit and getting rate-limited.&lt;/li&gt;
&lt;li&gt;Returning a database object without a response model, and leaking fields.&lt;/li&gt;
&lt;li&gt;Doing blocking calls in &lt;code&gt;async def&lt;/code&gt; endpoints.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Takeaway
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Fan out with a limit and a deadline. Let FastAPI validate both directions, and keep shared plumbing in dependencies.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Where this fits in my roadmap:&lt;/strong&gt; this is the second half of my foundations block (async in practice, plus FastAPI and Pydantic). In my own study, I’m building that block’s small LLM endpoint myself, with real timeouts and error handling. So this post sticks to the concepts and toy examples, not my solution. Next comes testing (pytest, plus mocking the provider), and then structured outputs, where the Pydantic schema from #03 becomes the contract the model must follow.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Over to you:&lt;/strong&gt; &lt;code&gt;gather(return_exceptions=True)&lt;/code&gt; or &lt;code&gt;TaskGroup&lt;/code&gt;: which do you reach for by default, and why?&lt;/p&gt;




&lt;h3&gt;
  
  
  Sources
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;Python docs: Coroutines and Tasks (&lt;code&gt;gather&lt;/code&gt; order, errors and &lt;code&gt;return_exceptions&lt;/code&gt;; &lt;code&gt;TaskGroup&lt;/code&gt; cancellation and &lt;code&gt;ExceptionGroup&lt;/code&gt;; &lt;code&gt;timeout()&lt;/code&gt; raising &lt;code&gt;TimeoutError&lt;/code&gt; catchable only outside; &lt;code&gt;wait_for&lt;/code&gt;; the warning against swallowing &lt;code&gt;CancelledError&lt;/code&gt;). &lt;a href="https://docs.python.org/3/library/asyncio-task.html" rel="noopener noreferrer"&gt;https://docs.python.org/3/library/asyncio-task.html&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Python tutorial 8.9: Raising and handling multiple unrelated exceptions (&lt;code&gt;ExceptionGroup&lt;/code&gt;, &lt;code&gt;except*&lt;/code&gt;). &lt;a href="https://docs.python.org/3/tutorial/errors.html" rel="noopener noreferrer"&gt;https://docs.python.org/3/tutorial/errors.html&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Python docs: Synchronization primitives (&lt;code&gt;Semaphore&lt;/code&gt;). &lt;a href="https://docs.python.org/3/library/asyncio-sync.html" rel="noopener noreferrer"&gt;https://docs.python.org/3/library/asyncio-sync.html&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;FastAPI: Request Body (Pydantic models; invalid data returns an error). &lt;a href="https://fastapi.tiangolo.com/tutorial/body/" rel="noopener noreferrer"&gt;https://fastapi.tiangolo.com/tutorial/body/&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;FastAPI: Response Model (validates returned data; filters output to the declared type for security; &lt;code&gt;response_model&lt;/code&gt; priority). &lt;a href="https://fastapi.tiangolo.com/tutorial/response-model/" rel="noopener noreferrer"&gt;https://fastapi.tiangolo.com/tutorial/response-model/&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;FastAPI: Handling Errors (&lt;code&gt;HTTPException&lt;/code&gt;; &lt;code&gt;RequestValidationError&lt;/code&gt; and 422). &lt;a href="https://fastapi.tiangolo.com/tutorial/handling-errors/" rel="noopener noreferrer"&gt;https://fastapi.tiangolo.com/tutorial/handling-errors/&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;FastAPI: Dependencies (&lt;code&gt;Depends&lt;/code&gt;, shared logic, DB connections, auth; &lt;code&gt;Annotated&lt;/code&gt; aliases; &lt;code&gt;async def&lt;/code&gt; or &lt;code&gt;def&lt;/code&gt;). &lt;a href="https://fastapi.tiangolo.com/tutorial/dependencies/" rel="noopener noreferrer"&gt;https://fastapi.tiangolo.com/tutorial/dependencies/&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;FastAPI: Concurrency and async/await (plain &lt;code&gt;def&lt;/code&gt; path operations run in an external threadpool). &lt;a href="https://fastapi.tiangolo.com/async/" rel="noopener noreferrer"&gt;https://fastapi.tiangolo.com/async/&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;FastAPI: Settings and Environment Variables (&lt;code&gt;BaseSettings&lt;/code&gt;, case-insensitive env vars, &lt;code&gt;lru_cache&lt;/code&gt;, &lt;code&gt;dependency_overrides&lt;/code&gt;, &lt;code&gt;.env&lt;/code&gt;). &lt;a href="https://fastapi.tiangolo.com/advanced/settings/" rel="noopener noreferrer"&gt;https://fastapi.tiangolo.com/advanced/settings/&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Python docs: asyncio Exceptions (&lt;code&gt;CancelledError&lt;/code&gt; is a &lt;code&gt;BaseException&lt;/code&gt; since 3.8; must almost always be re-raised). &lt;a href="https://docs.python.org/3/library/asyncio-exceptions.html" rel="noopener noreferrer"&gt;https://docs.python.org/3/library/asyncio-exceptions.html&lt;/a&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;em&gt;Sources checked Oct 18, 2026.&lt;/em&gt;&lt;/p&gt;




&lt;p&gt;&lt;em&gt;Originally published on &lt;a href="https://dhanushkumarsivaji.substack.com/p/the-path-to-ai-fde-04-many-calls" rel="noopener noreferrer"&gt;The Path to AI FDE&lt;/a&gt; on Substack. Subscribe for the next issue: &lt;a href="https://dhanushkumarsivaji.substack.com/subscribe" rel="noopener noreferrer"&gt;https://dhanushkumarsivaji.substack.com/subscribe&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;If this was useful, &lt;a href="https://dhanushkumarsivaji.substack.com/subscribe" rel="noopener noreferrer"&gt;subscribe to The Path to AI FDE&lt;/a&gt; for the next issue.&lt;/p&gt;

</description>
      <category>ai</category>
      <category>python</category>
      <category>fastapi</category>
      <category>programming</category>
    </item>
    <item>
      <title>The path to AI FDE #03: Python types you can trust, and async waiting done well</title>
      <dc:creator>Dhanush Kumar Sivaji</dc:creator>
      <pubDate>Wed, 21 Oct 2026 17:16:57 +0000</pubDate>
      <link>https://dev.to/dhanushkumarsivaji/the-path-to-ai-fde-03-python-types-you-can-trust-and-async-waiting-done-well-52h0</link>
      <guid>https://dev.to/dhanushkumarsivaji/the-path-to-ai-fde-03-python-types-you-can-trust-and-async-waiting-done-well-52h0</guid>
      <description>&lt;p&gt;&lt;em&gt;Originally published on my newsletter, The Path to AI FDE. &lt;a href="https://dhanushkumarsivaji.substack.com/subscribe" rel="noopener noreferrer"&gt;Subscribe free&lt;/a&gt; to get each issue by email.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Issue #02 was the quick TypeScript-to-Python map. This issue goes one level deeper on the two ideas every AI backend leans on: &lt;strong&gt;types&lt;/strong&gt; (what data is allowed in) and &lt;strong&gt;async&lt;/strong&gt; (how one process waits on many slow network calls). Twelve short points, each with the trap I’d fall into first.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fwljnms3ee5tlqmmysd74.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fwljnms3ee5tlqmmysd74.png" alt="Two panels. Part A, types you can trust: six cards from type hints to Pydantic errors and JSON Schema. Part B, waiting done well: six cards from the event loop to not blocking it" width="800" height="1110"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  Part A · Types you can trust
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F3cv974k2ez77cjxm8zde.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F3cv974k2ez77cjxm8zde.png" alt="Type hints: the parts of def count_words(text: str) -&gt; int, collection hints like list[str], str | None as the Python 3.10 spelling of Optional[str], and count_words(42) running anyway unless mypy or Pyright flags it" width="800" height="510"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Hints describe intent.&lt;/strong&gt; &lt;code&gt;def count_words(text: str) -&amp;gt; int&lt;/code&gt; tells readers, editors and type checkers what goes in and what comes out. Collections take their item types in brackets: &lt;code&gt;list[str]&lt;/code&gt;, &lt;code&gt;dict[str, int]&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. “Maybe missing” is spelled&lt;/strong&gt; &lt;code&gt;X | None&lt;/code&gt;&lt;strong&gt;.&lt;/strong&gt; Since Python 3.10 (PEP 604) you write &lt;code&gt;str | None&lt;/code&gt; instead of &lt;code&gt;Optional[str]&lt;/code&gt;. Trap: in Pydantic v2, &lt;code&gt;subtitle: "str | None&lt;/code&gt; with no default is still a &lt;em&gt;required&lt;/em&gt; field. Add &lt;code&gt;= None&lt;/code&gt; if callers may leave it out."&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. Checked before running, not while running.&lt;/strong&gt; As covered in #02, Python ignores hints at runtime, so &lt;code&gt;count_words(42)&lt;/code&gt; runs anyway and only mypy or Pyright flags it. Run one of them in CI.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fwyu4ny6jxh491evjos2w.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fwyu4ny6jxh491evjos2w.png" alt="Pydantic models check data when it arrives: incoming data passes through a toy Book model with Field constraints and becomes a Book or a ValidationError; a table shows str | None without a default is still required" width="800" height="576"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;4. Pydantic models check data when it arrives.&lt;/strong&gt; A model is a class that inherits from &lt;code&gt;BaseModel&lt;/code&gt;, with typed fields, and creating an instance runs validation. &lt;code&gt;Field()&lt;/code&gt; adds constraints such as &lt;code&gt;gt=0&lt;/code&gt; or &lt;code&gt;max_length=200&lt;/code&gt;. If no error is raised, the fields are guaranteed to match their types.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F9r1fllrrr87xnkczcjzo.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F9r1fllrrr87xnkczcjzo.png" alt="Lax by default: the same input with pages as the string " width="800" height="530"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;5. Lax by default: know what it lets through.&lt;/strong&gt; Pydantic coerces when it can (&lt;code&gt;pages="412"&lt;/code&gt; becomes the integer &lt;code&gt;412&lt;/code&gt;) and silently ignores extra keys. That’s handy for query strings and environment variables, but risky for data from a model or another service. For those, opt into &lt;code&gt;strict=True&lt;/code&gt; and &lt;code&gt;extra='forbid'&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fy65814zvf4y3cpwwjd9h.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fy65814zvf4y3cpwwjd9h.png" alt="Errors that list everything: one ValidationError reports title, pages and tags.2 at once; model_json_schema exports the model as a JSON Schema with exclusiveMinimum for gt=0" width="800" height="529"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;6. One error lists every problem, and a model can describe itself.&lt;/strong&gt; A &lt;code&gt;ValidationError&lt;/code&gt; reports &lt;em&gt;all&lt;/em&gt; failing fields with their locations (such as &lt;code&gt;tags.2&lt;/code&gt;), not just the first. &lt;code&gt;Book.model_validate_json(raw)&lt;/code&gt; validates a JSON string directly, and &lt;code&gt;Book.model_json_schema()&lt;/code&gt; exports a JSON Schema, which is how structured outputs get their contract (coming later in the series).&lt;/p&gt;

&lt;h2&gt;
  
  
  Part B · Waiting done well
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fhpb8dxhgx4worwwkxy3p.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fhpb8dxhgx4worwwkxy3p.png" alt="Waiting, overlapped: one LLM call is mostly waiting on the provider; an event loop runs tasks A, B and C one at a time, switching whenever a task awaits a reply" width="800" height="674"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;7. AI backends mostly wait.&lt;/strong&gt; An LLM call spends most of its time waiting on someone else’s server, not computing on yours. Async lets one process overlap those waits instead of standing idle through each one.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;8. The event loop runs one task at a time.&lt;/strong&gt; asyncio uses cooperative scheduling: whenever the running task hits an &lt;code&gt;await&lt;/code&gt; on something not yet ready, the loop switches to another. Nothing is truly simultaneous; the overlap comes only from the waiting.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fst9qfs2j409ghhzhusrr.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fst9qfs2j409ghhzhusrr.png" alt="await waits, tasks overlap: the asyncio docs' say_after example takes 3 seconds with two back-to-back awaits and about 2 seconds with two tasks" width="800" height="768"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;9.&lt;/strong&gt; &lt;code&gt;async def&lt;/code&gt; &lt;strong&gt;makes a coroutine, and&lt;/strong&gt; &lt;code&gt;asyncio.run()&lt;/code&gt; &lt;strong&gt;starts the loop.&lt;/strong&gt; &lt;code&gt;asyncio.run(main())&lt;/code&gt; is the usual entry point in a script. Calling &lt;code&gt;main()&lt;/code&gt; on its own only creates a coroutine object, which does nothing until awaited (#02, point 6). In FastAPI, the framework runs the loop for you.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;10. Back-to-back awaits are still sequential.&lt;/strong&gt; This is the trap I’d hit first. In the asyncio docs’ example, &lt;code&gt;await say_after(1, ...)&lt;/code&gt; then &lt;code&gt;await say_after(2, ...)&lt;/code&gt; takes 3 seconds: async syntax alone doesn’t make anything concurrent.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;11. Tasks are how work overlaps.&lt;/strong&gt; &lt;code&gt;asyncio.create_task(coro)&lt;/code&gt; schedules the coroutine to run soon, alongside the current one, which brings the same example down to about 2 seconds. Keep a reference to every task: the loop holds tasks only weakly, so an unreferenced task can be garbage-collected before it finishes. &lt;code&gt;TaskGroup&lt;/code&gt; handles that for you (next issue).&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Foyjee3x68xhrpsrc96o4.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Foyjee3x68xhrpsrc96o4.png" alt="One blocking call stalls everyone: two tasks finish in 2 seconds with await asyncio.sleep but take 3 seconds with time.sleep; asyncio.to_thread moves unavoidable blocking I/O off the loop" width="799" height="577"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;12. One blocking call stalls everyone.&lt;/strong&gt; &lt;code&gt;time.sleep(1)&lt;/code&gt; or a synchronous HTTP client inside &lt;code&gt;async def&lt;/code&gt; freezes the whole loop, while &lt;code&gt;await asyncio.sleep(1)&lt;/code&gt; always suspends just the current task. For blocking I/O you can’t avoid, &lt;code&gt;await asyncio.to_thread(fn)&lt;/code&gt; moves it off the loop.&lt;/p&gt;




&lt;h3&gt;
  
  
  Try it (15 minutes, toy example)
&lt;/h3&gt;

&lt;p&gt;Write &lt;code&gt;async def nap(n)&lt;/code&gt; that does &lt;code&gt;await asyncio.sleep(n)&lt;/code&gt;. Time &lt;code&gt;await nap(1); await nap(2)&lt;/code&gt;, then the same two calls wrapped in &lt;code&gt;create_task&lt;/code&gt;. Then swap in &lt;code&gt;time.sleep&lt;/code&gt; and watch the overlap vanish. Separately, define a &lt;code&gt;Book&lt;/code&gt; model with &lt;code&gt;title: str&lt;/code&gt; and &lt;code&gt;pages: int = Field(gt=0)&lt;/code&gt;, and feed it one good dict and one bad dict.&lt;/p&gt;

&lt;h3&gt;
  
  
  Common beginner mistakes
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Assuming hints validate input. Only Pydantic (or your own checks) does that.&lt;/li&gt;
&lt;li&gt;Writing &lt;code&gt;x: str | None&lt;/code&gt; and expecting it to be optional in Pydantic v2. It needs &lt;code&gt;= None&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Thinking &lt;code&gt;async def&lt;/code&gt; plus &lt;code&gt;await&lt;/code&gt; equals parallel. It doesn’t without tasks.&lt;/li&gt;
&lt;li&gt;Creating tasks and dropping the reference.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Takeaway
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Hints describe, Pydantic enforces.&lt;/strong&gt; &lt;code&gt;await&lt;/code&gt; &lt;strong&gt;waits; tasks overlap.&lt;/strong&gt; That’s the whole issue in two lines.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Where this fits in my roadmap:&lt;/strong&gt; these are the concepts behind the foundations block of my roadmap (Python typing, errors and async; FastAPI and Pydantic models). That block’s exercises (a typed document loader, a small validated LLM endpoint and its tests) are mine to build, so nothing above is that code; the examples are deliberately toy ones. Next issue: running many calls at once safely (&lt;code&gt;gather&lt;/code&gt;, &lt;code&gt;TaskGroup&lt;/code&gt;, timeouts) and FastAPI beyond hello-world.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Over to you:&lt;/strong&gt; which bit you first: a missing &lt;code&gt;await&lt;/code&gt;, or an &lt;code&gt;await&lt;/code&gt; that should have been a task?&lt;/p&gt;




&lt;h3&gt;
  
  
  Sources
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;Python docs: &lt;code&gt;typing&lt;/code&gt; (annotations aren’t enforced at runtime). &lt;a href="https://docs.python.org/3/library/typing.html" rel="noopener noreferrer"&gt;https://docs.python.org/3/library/typing.html&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;PEP 604: Allow writing union types as &lt;code&gt;X | Y&lt;/code&gt; (Python 3.10). &lt;a href="https://peps.python.org/pep-0604/" rel="noopener noreferrer"&gt;https://peps.python.org/pep-0604/&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;mypy documentation. &lt;a href="https://mypy.readthedocs.io/en/stable/" rel="noopener noreferrer"&gt;https://mypy.readthedocs.io/en/stable/&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Pyright. &lt;a href="https://github.com/microsoft/pyright" rel="noopener noreferrer"&gt;https://github.com/microsoft/pyright&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Pydantic: Models (validation on instantiation, guarantees, coercion, extra data ignored by default, &lt;code&gt;ValidationError&lt;/code&gt; lists all errors, &lt;code&gt;model_validate_json&lt;/code&gt;, &lt;code&gt;model_json_schema&lt;/code&gt;). &lt;a href="https://pydantic.dev/docs/validation/latest/concepts/models/" rel="noopener noreferrer"&gt;https://pydantic.dev/docs/validation/latest/concepts/models/&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Pydantic: Fields (&lt;code&gt;Field()&lt;/code&gt; constraints such as &lt;code&gt;gt&lt;/code&gt; and &lt;code&gt;max_length&lt;/code&gt;; v2 no longer gives &lt;code&gt;Optional&lt;/code&gt; an implicit &lt;code&gt;None&lt;/code&gt; default). &lt;a href="https://pydantic.dev/docs/validation/latest/concepts/fields/" rel="noopener noreferrer"&gt;https://pydantic.dev/docs/validation/latest/concepts/fields/&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Pydantic: Strict Mode (default coercion of &lt;code&gt;'123'&lt;/code&gt; to &lt;code&gt;123&lt;/code&gt;; enabling strict mode). &lt;a href="https://pydantic.dev/docs/validation/latest/concepts/strict_mode/" rel="noopener noreferrer"&gt;https://pydantic.dev/docs/validation/latest/concepts/strict_mode/&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Python docs: Coroutines and Tasks (calling a coroutine doesn’t schedule it; &lt;code&gt;asyncio.run&lt;/code&gt;; the 3-second vs 2-second example; &lt;code&gt;create_task&lt;/code&gt;; keep task references; &lt;code&gt;sleep&lt;/code&gt; always suspends; &lt;code&gt;to_thread&lt;/code&gt;; cooperative scheduling). &lt;a href="https://docs.python.org/3/library/asyncio-task.html" rel="noopener noreferrer"&gt;https://docs.python.org/3/library/asyncio-task.html&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Python docs: Developing with asyncio (”Running Blocking Code”). &lt;a href="https://docs.python.org/3/library/asyncio-dev.html" rel="noopener noreferrer"&gt;https://docs.python.org/3/library/asyncio-dev.html&lt;/a&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;em&gt;Sources checked Oct 18, 2026.&lt;/em&gt;&lt;/p&gt;




&lt;p&gt;&lt;em&gt;Originally published on &lt;a href="https://dhanushkumarsivaji.substack.com/p/the-path-to-ai-fde-03-python-types" rel="noopener noreferrer"&gt;The Path to AI FDE&lt;/a&gt; on Substack. Subscribe for the next issue: &lt;a href="https://dhanushkumarsivaji.substack.com/subscribe" rel="noopener noreferrer"&gt;https://dhanushkumarsivaji.substack.com/subscribe&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;If this was useful, &lt;a href="https://dhanushkumarsivaji.substack.com/subscribe" rel="noopener noreferrer"&gt;subscribe to The Path to AI FDE&lt;/a&gt; for the next issue.&lt;/p&gt;

</description>
      <category>ai</category>
      <category>python</category>
      <category>beginners</category>
      <category>programming</category>
    </item>
    <item>
      <title>The path to AI FDE #02: Python for AI backends: a TypeScript engineer's refresher</title>
      <dc:creator>Dhanush Kumar Sivaji</dc:creator>
      <pubDate>Wed, 21 Oct 2026 17:16:38 +0000</pubDate>
      <link>https://dev.to/dhanushkumarsivaji/the-path-to-ai-fde-02-python-for-ai-backends-a-typescript-engineers-refresher-238p</link>
      <guid>https://dev.to/dhanushkumarsivaji/the-path-to-ai-fde-02-python-for-ai-backends-a-typescript-engineers-refresher-238p</guid>
      <description>&lt;p&gt;&lt;em&gt;Originally published on my newsletter, The Path to AI FDE. &lt;a href="https://dhanushkumarsivaji.substack.com/subscribe" rel="noopener noreferrer"&gt;Subscribe free&lt;/a&gt; to get each issue by email.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Most AI engineering tutorials assume Python. I’ve written TypeScript for years and have working, not deep, Python. My roadmap starts with a short Python + FastAPI refresher rather than a full course, and this post is the map I’m following through it: eight concepts AI backends lean on, each mapped to TypeScript I already know, plus the spot where my TS instincts are most likely to mislead me.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F3wv8kfhbkpx9bm6zypol.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F3wv8kfhbkpx9bm6zypol.png" alt="Python for AI backends: eight TypeScript-to-Python comparisons, each with a gotcha" width="800" height="1170"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;p&gt;Each concept gets its own figure first, then the short version in words.&lt;/p&gt;

&lt;h2&gt;
  
  
  Setup and types: concepts 1–3
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F55rjckjdiggspakymdxf.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F55rjckjdiggspakymdxf.png" alt="One environment per project: two project folders each with their own .venv and different versions of the same library; create, activate, install; warnings about skipping activation and PEP 668 externally managed Pythons" width="800" height="723"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Isolated dependencies:&lt;/strong&gt; &lt;code&gt;node_modules&lt;/code&gt; &lt;strong&gt;↔ virtual environments.&lt;/strong&gt; A &lt;em&gt;virtual environment&lt;/em&gt; is a self-contained directory with its own interpreter and packages, so two projects can pin different versions of the same library. Create it with &lt;code&gt;python -m venv .venv&lt;/code&gt;, then activate it: activation changes your shell so &lt;code&gt;python&lt;/code&gt; points into that environment. The TS instinct that misleads: there’s no automatic per-folder install. Forget to activate, and &lt;code&gt;pip&lt;/code&gt; targets whichever Python comes first on your PATH. On Pythons marked “externally managed” (PEP 668), as some OS-provided ones are, pip refuses to install outside a virtual environment and exits with an error.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F50vjlcbtx7c82plkuujg.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F50vjlcbtx7c82plkuujg.png" alt="Types vanish at runtime in both languages: TypeScript types are checked by tsc then erased; Python annotations are checked by mypy or Pyright but not enforced, so f(" width="800" height="600"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Type hints are for tools, just like TS types.&lt;/strong&gt; The TypeScript handbook shows types being &lt;em&gt;erased&lt;/em&gt; when &lt;code&gt;tsc&lt;/code&gt; compiles to JavaScript. Python’s &lt;code&gt;typing&lt;/code&gt; docs say the runtime &lt;em&gt;does not enforce&lt;/em&gt; annotations; they exist for type checkers, IDEs and linters. So &lt;code&gt;def f(x: float) -&amp;gt; str&lt;/code&gt; happily accepts a string at runtime. Run mypy or Pyright in CI, the way you’d run &lt;code&gt;tsc --noEmit&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fj2mlulutrwsebbk0btl8.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fj2mlulutrwsebbk0btl8.png" alt="Pydantic guards the edges: HTTP request bodies and LLM output pass through a Pydantic model before becoming typed objects; the OpenAI Python SDK turns the model class into a JSON Schema and parses the reply back" width="800" height="646"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. Runtime validation: Zod ↔ Pydantic.&lt;/strong&gt; Since annotations aren’t enforced, untrusted data needs a validator. Zod describes itself as TypeScript-first schema validation with static type inference. Pydantic plays the same role in Python: validation is driven by type annotations, and once data passes, the fields are guaranteed to match the declared types. For LLM work, FastAPI uses it to validate requests and responses, and OpenAI’s Python SDK accepts a Pydantic class directly (&lt;code&gt;client.responses.parse(..., text_format=MyModel)&lt;/code&gt;): it converts the class to a JSON Schema, sends it and parses the reply back into the model. Only the subset of JSON Schema that structured outputs supports will work.&lt;/p&gt;

&lt;h2&gt;
  
  
  Errors and cleanup: concepts 4–5
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fyk7wuq4ap5y70renjszw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fyk7wuq4ap5y70renjszw.png" alt="Errors in Python: which of try, except, else and finally run with no error, a matching error or another error; FastAPI's HTTPException is swallowed by a broad except Exception" width="800" height="587"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;4. Errors:&lt;/strong&gt; &lt;code&gt;throw&lt;/code&gt;&lt;strong&gt;/&lt;/strong&gt;&lt;code&gt;catch&lt;/code&gt; &lt;strong&gt;↔&lt;/strong&gt; &lt;code&gt;raise&lt;/code&gt;&lt;strong&gt;/&lt;/strong&gt;&lt;code&gt;except&lt;/code&gt;&lt;strong&gt;.&lt;/strong&gt; The shape maps closely, plus one extra: &lt;code&gt;else&lt;/code&gt;, which runs only if the &lt;code&gt;try&lt;/code&gt; block raised nothing. Idiomatic Python catches &lt;em&gt;specific&lt;/em&gt; exception classes. In FastAPI, &lt;code&gt;raise HTTPException(...)&lt;/code&gt; returns an HTTP error and ends the request, even from deep inside a helper. But FastAPI’s docs call &lt;code&gt;HTTPException&lt;/code&gt; a normal Python exception, so a broad &lt;code&gt;except Exception:&lt;/code&gt; between the raise and FastAPI swallows it. One more reason to catch narrowly.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fse7m4hc20vgpzuvd4sxy.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fse7m4hc20vgpzuvd4sxy.png" alt="Cleanup that always runs: acquire, then whether the block finishes or raises, cleanup runs; TypeScript using with Symbol.dispose next to Python with and async with" width="800" height="545"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;5. Guaranteed cleanup:&lt;/strong&gt; &lt;code&gt;using&lt;/code&gt; &lt;strong&gt;↔&lt;/strong&gt; &lt;code&gt;with&lt;/code&gt;&lt;strong&gt;.&lt;/strong&gt; TypeScript 5.2 added &lt;code&gt;using&lt;/code&gt; declarations (explicit resource management). Python has had the &lt;code&gt;with&lt;/code&gt; statement for a long time: the cleanup step runs whether the block finishes normally or raises, and &lt;code&gt;async with&lt;/code&gt; is the asynchronous version. In AI backends, that’s the home for HTTP clients, open files and database sessions.&lt;/p&gt;

&lt;h2&gt;
  
  
  Async: concepts 6–8
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F78m7iivy8ylg7kr21sxe.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F78m7iivy8ylg7kr21sxe.png" alt="Starting async work: in TypeScript calling an async function starts it immediately; in Python calling an async def only creates a coroutine until it is awaited; a forgotten await in Python means the work never runs and asyncio warns" width="800" height="640"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;6. Starting async work: the subtle one.&lt;/strong&gt; The syntax looks the same; what happens at call time doesn’t. MDN: an &lt;code&gt;async&lt;/code&gt; function runs synchronously up to its first &lt;code&gt;await&lt;/code&gt;, so calling &lt;code&gt;fetchDoc()&lt;/code&gt; starts the work immediately. Python’s asyncio docs: &lt;em&gt;simply calling a coroutine will not schedule it&lt;/em&gt;. Nothing runs until you &lt;code&gt;await&lt;/code&gt; it or wrap it in a task, so a forgotten &lt;code&gt;await&lt;/code&gt; means the work never happens. asyncio emits a &lt;code&gt;RuntimeWarning&lt;/code&gt; (”coroutine ... was never awaited”); treat it as a bug.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F444ocedggn2ovrrcvx5k.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F444ocedggn2ovrrcvx5k.png" alt="One blocking call stalls everything: a timeline where time.sleep(1) on the event loop delays three ready requests; fixes for blocking I/O, CPU-bound work and FastAPI" width="800" height="702"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;7. Blocking the event loop: same trap, both runtimes.&lt;/strong&gt; Node’s docs warn against blocking the event loop. Python’s asyncio docs say a CPU-intensive calculation that takes 1 second delays &lt;em&gt;every&lt;/em&gt; concurrent task by 1 second, and blocking I/O (&lt;code&gt;time.sleep()&lt;/code&gt;, a synchronous HTTP client inside &lt;code&gt;async def&lt;/code&gt;) does the same. The fix depends on the work: for blocking I/O, an awaitable client or &lt;code&gt;asyncio.to_thread()&lt;/code&gt;, which the docs say is mainly for I/O-bound work because the GIL usually stops threads speeding up CPU-bound Python; for CPU-bound work, a process pool via &lt;code&gt;loop.run_in_executor(ProcessPoolExecutor(), fn)&lt;/code&gt;; in FastAPI, a plain &lt;code&gt;def&lt;/code&gt; endpoint runs in a threadpool instead of on the loop.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F9lq0yz50m3exzy5fajmk.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F9lq0yz50m3exzy5fajmk.png" alt="Fan-out when one call fails: Promise.all and asyncio.gather let the other calls keep running, gather with return_exceptions returns results and errors like Promise.allSettled, and TaskGroup cancels the rest" width="800" height="559"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;8. Fan-out:&lt;/strong&gt; &lt;code&gt;Promise.all&lt;/code&gt; &lt;strong&gt;↔&lt;/strong&gt; &lt;code&gt;asyncio.gather&lt;/code&gt; &lt;strong&gt;/&lt;/strong&gt; &lt;code&gt;TaskGroup&lt;/code&gt;&lt;strong&gt;.&lt;/strong&gt; You’ll want this for parallel calls, like embedding several chunks or querying two retrievers. &lt;code&gt;Promise.all&lt;/code&gt; rejects with the first rejection but doesn’t stop the other operations: MDN notes promises have no built-in cancellation (you’d reach for &lt;code&gt;AbortController&lt;/code&gt;). &lt;code&gt;asyncio.gather&lt;/code&gt; behaves the same by default, and with &lt;code&gt;return_exceptions=True&lt;/code&gt; it collects every result and error, much like &lt;code&gt;Promise.allSettled&lt;/code&gt;. &lt;code&gt;asyncio.TaskGroup&lt;/code&gt; (Python 3.11+) is the real difference: when one task fails, the rest of the group is cancelled, and the failures are raised together as an &lt;code&gt;ExceptionGroup&lt;/code&gt;. That’s usually what you want when partial results are useless.&lt;/p&gt;




&lt;h3&gt;
  
  
  Takeaway
&lt;/h3&gt;

&lt;p&gt;Coming from TypeScript, the biggest shift isn’t syntax. It’s &lt;strong&gt;where the guarantees live&lt;/strong&gt;. In both languages, types vanish at runtime. Real safety comes from validating at the edges (Pydantic, the way Zod does on the front end), closing resources deterministically (&lt;code&gt;with&lt;/code&gt;) and respecting the event loop. Points 6 and 8 are the two I expect to trip over most, so they go on my checklist.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Where this fits in my roadmap:&lt;/strong&gt; the foundations block (Python typing, errors, environments and async, plus the FastAPI tutorial’s request/response models, errors, dependencies and testing), building toward a small typed LLM API. Next post: structured outputs, from “please return JSON” to contracts.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Over to you:&lt;/strong&gt; if you moved from TypeScript to Python, which habit took longest to unlearn?&lt;/p&gt;




&lt;h3&gt;
  
  
  Sources
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;Python Tutorial: Virtual Environments and Packages. &lt;a href="https://docs.python.org/3/tutorial/venv.html" rel="noopener noreferrer"&gt;https://docs.python.org/3/tutorial/venv.html&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;PEP 668: Marking Python base environments as “externally managed”. &lt;a href="https://peps.python.org/pep-0668/" rel="noopener noreferrer"&gt;https://peps.python.org/pep-0668/&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;TypeScript Handbook: The Basics, “Erased Types”. &lt;a href="https://www.typescriptlang.org/docs/handbook/2/basic-types.html" rel="noopener noreferrer"&gt;https://www.typescriptlang.org/docs/handbook/2/basic-types.html&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Python docs: &lt;code&gt;typing&lt;/code&gt; (”The Python runtime does not enforce function and variable type annotations”). &lt;a href="https://docs.python.org/3/library/typing.html" rel="noopener noreferrer"&gt;https://docs.python.org/3/library/typing.html&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;mypy documentation (”a static type checker for Python”). &lt;a href="https://mypy.readthedocs.io/en/stable/" rel="noopener noreferrer"&gt;https://mypy.readthedocs.io/en/stable/&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Pyright (”a full-featured, standards-based static type checker for Python”). &lt;a href="https://github.com/microsoft/pyright" rel="noopener noreferrer"&gt;https://github.com/microsoft/pyright&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Zod documentation (TypeScript-first schema validation).&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;a href="https://zod.dev/" rel="noopener noreferrer"&gt;https://zod.dev/&lt;/a&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Pydantic: Why use Pydantic (type-hint-driven validation, JSON Schema). &lt;a href="https://pydantic.dev/docs/validation/latest/get-started/why/" rel="noopener noreferrer"&gt;https://pydantic.dev/docs/validation/latest/get-started/why/&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Pydantic: Models (post-validation guarantees). &lt;a href="https://pydantic.dev/docs/validation/latest/concepts/models/" rel="noopener noreferrer"&gt;https://pydantic.dev/docs/validation/latest/concepts/models/&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;OpenAI: Structured model outputs (&lt;code&gt;pydantic.BaseModel&lt;/code&gt; schemas, &lt;code&gt;text_format&lt;/code&gt;, supported JSON Schema subset). &lt;a href="https://developers.openai.com/api/docs/guides/structured-outputs" rel="noopener noreferrer"&gt;https://developers.openai.com/api/docs/guides/structured-outputs&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;openai-python &lt;code&gt;helpers.md&lt;/code&gt; (&lt;code&gt;.parse()&lt;/code&gt; converts a Pydantic model to JSON Schema and parses the reply; &lt;code&gt;output_parsed&lt;/code&gt;). &lt;a href="https://github.com/openai/openai-python/blob/main/helpers.md" rel="noopener noreferrer"&gt;https://github.com/openai/openai-python/blob/main/helpers.md&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Python Tutorial: Errors and Exceptions (&lt;code&gt;else&lt;/code&gt;, &lt;code&gt;finally&lt;/code&gt;). &lt;a href="https://docs.python.org/3/tutorial/errors.html" rel="noopener noreferrer"&gt;https://docs.python.org/3/tutorial/errors.html&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;FastAPI: Handling Errors (&lt;code&gt;HTTPException&lt;/code&gt; is a normal Python exception; raising it from a helper ends the request). &lt;a href="https://fastapi.tiangolo.com/tutorial/handling-errors/" rel="noopener noreferrer"&gt;https://fastapi.tiangolo.com/tutorial/handling-errors/&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;TypeScript 5.2 release notes: &lt;code&gt;using&lt;/code&gt; declarations and explicit resource management. &lt;a href="https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-2.html" rel="noopener noreferrer"&gt;https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-2.html&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Python Language Reference: the &lt;code&gt;with&lt;/code&gt; statement. &lt;a href="https://docs.python.org/3/reference/compound_stmts.html#the-with-statement" rel="noopener noreferrer"&gt;https://docs.python.org/3/reference/compound_stmts.html#the-with-statement&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;MDN: &lt;code&gt;async function&lt;/code&gt; (runs synchronously up to the first &lt;code&gt;await&lt;/code&gt;). &lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function" rel="noopener noreferrer"&gt;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Python docs: Coroutines and Tasks (calling a coroutine doesn’t schedule it; &lt;code&gt;create_task&lt;/code&gt;; &lt;code&gt;gather&lt;/code&gt;; &lt;code&gt;TaskGroup&lt;/code&gt; and &lt;code&gt;ExceptionGroup&lt;/code&gt;; &lt;code&gt;to_thread&lt;/code&gt; and the GIL). &lt;a href="https://docs.python.org/3/library/asyncio-task.html" rel="noopener noreferrer"&gt;https://docs.python.org/3/library/asyncio-task.html&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Python docs: Developing with asyncio (”Running Blocking Code”; “Detect never-awaited coroutines”). &lt;a href="https://docs.python.org/3/library/asyncio-dev.html" rel="noopener noreferrer"&gt;https://docs.python.org/3/library/asyncio-dev.html&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Python docs: Event loop, &lt;code&gt;run_in_executor&lt;/code&gt; with &lt;code&gt;ProcessPoolExecutor&lt;/code&gt;. &lt;a href="https://docs.python.org/3/library/asyncio-eventloop.html" rel="noopener noreferrer"&gt;https://docs.python.org/3/library/asyncio-eventloop.html&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Node.js: Don’t Block the Event Loop (or the Worker Pool). &lt;a href="https://nodejs.org/learn/asynchronous-work/dont-block-the-event-loop" rel="noopener noreferrer"&gt;https://nodejs.org/learn/asynchronous-work/dont-block-the-event-loop&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;FastAPI: Concurrency and async / await (plain &lt;code&gt;def&lt;/code&gt; path operations run in a threadpool). &lt;a href="https://fastapi.tiangolo.com/async/" rel="noopener noreferrer"&gt;https://fastapi.tiangolo.com/async/&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;MDN: &lt;code&gt;Promise.all()&lt;/code&gt;. &lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all" rel="noopener noreferrer"&gt;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;MDN: &lt;code&gt;Promise&lt;/code&gt; (no first-class cancellation; use &lt;code&gt;AbortController&lt;/code&gt;). &lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" rel="noopener noreferrer"&gt;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;MDN: &lt;code&gt;Promise.allSettled()&lt;/code&gt;. &lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/allSettled" rel="noopener noreferrer"&gt;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/allSettled&lt;/a&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;em&gt;Sources checked Oct 18, 2026.&lt;/em&gt;&lt;/p&gt;




&lt;p&gt;&lt;em&gt;Originally published on &lt;a href="https://dhanushkumarsivaji.substack.com/p/the-path-to-ai-fde-02-python-for" rel="noopener noreferrer"&gt;The Path to AI FDE&lt;/a&gt; on Substack. Subscribe for the next issue: &lt;a href="https://dhanushkumarsivaji.substack.com/subscribe" rel="noopener noreferrer"&gt;https://dhanushkumarsivaji.substack.com/subscribe&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;If this was useful, &lt;a href="https://dhanushkumarsivaji.substack.com/subscribe" rel="noopener noreferrer"&gt;subscribe to The Path to AI FDE&lt;/a&gt; for the next issue.&lt;/p&gt;

</description>
      <category>ai</category>
      <category>python</category>
      <category>typescript</category>
      <category>beginners</category>
    </item>
    <item>
      <title>The path to AI FDE #01: Anatomy of an LLM app request</title>
      <dc:creator>Dhanush Kumar Sivaji</dc:creator>
      <pubDate>Mon, 19 Oct 2026 19:22:12 +0000</pubDate>
      <link>https://dev.to/dhanushkumarsivaji/the-path-to-ai-fde-01-anatomy-of-an-llm-app-request-3c3e</link>
      <guid>https://dev.to/dhanushkumarsivaji/the-path-to-ai-fde-01-anatomy-of-an-llm-app-request-3c3e</guid>
      <description>&lt;p&gt;&lt;em&gt;Originally published on my newsletter, The Path to AI FDE. &lt;a href="https://dhanushkumarsivaji.substack.com/subscribe" rel="noopener noreferrer"&gt;Subscribe free&lt;/a&gt; to get each issue by email.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;I've spent 8+ years building React/TypeScript front ends. Now I'm learning applied AI in public, working toward AI Engineer, then AI Solution Architect, and (I hope) AI Forward Deployed Engineer. Before tokens, RAG or agents, I wanted one map: what actually happens when a user clicks "Summarize"?&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fvgaljigdwufjph6j4a4e.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fvgaljigdwufjph6j4a4e.png" alt="Anatomy of an LLM app request: a nine-step flow from client to logging, with steps 5 and 6 (prefill and decode) inside the model provider" width="800" height="1135"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;p&gt;Each step below gets its own figure first, then the short version in words.&lt;/p&gt;

&lt;h2&gt;
  
  
  Before the call: steps 1–4
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F196de03z1hvndk6192z2.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F196de03z1hvndk6192z2.png" alt="Where each piece runs: the browser posts to your FastAPI backend, which holds the API key and calls the model provider; inside the backend a Pydantic model either lets a valid body through or FastAPI returns a 422 before any tokens are spent" width="800" height="642"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. The client sends a request.&lt;/strong&gt; From the browser's side, an LLM feature is just an HTTP call to &lt;em&gt;your&lt;/em&gt; backend: &lt;code&gt;POST /summarize&lt;/code&gt; with the user's text, plus a conversation id if it's a chat. OpenAI's docs say never to expose an API key in client-side code, so the key lives on your server and only the server talks to the provider.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Your API validates the input.&lt;/strong&gt; FastAPI checks the body against a Pydantic model. Invalid data never reaches your handler: FastAPI raises a &lt;code&gt;RequestValidationError&lt;/code&gt;, and its default handler returns HTTP 422. Once validation passes, Pydantic guarantees the fields match their declared types. It's the cheapest place to stop bad input.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F5z54bra8cdbhuf1oduyf.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F5z54bra8cdbhuf1oduyf.png" alt="Each request stands alone: three successive requests resend the system prompt and the whole history, so input grows each turn; optional server-side state still bills earlier input tokens" width="800" height="565"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. You assemble the prompt.&lt;/strong&gt; The model sees only what you send. Anthropic's Messages API is stateless, so you resend the full history every time. OpenAI also calls each request independent and stateless, and offers optional server-side conversation state, but notes that earlier input tokens in the chain are still billed on each turn. Later in this series, retrieved documents (RAG) join the prompt here.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fzw722jhphulijer3xn7g.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fzw722jhphulijer3xn7g.png" alt="Tokens and the context window: " width="800" height="559"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;4. Count tokens and check the budget.&lt;/strong&gt; Models read &lt;em&gt;tokens&lt;/em&gt;, not characters, and tokenizers are tied to the model, so counts differ between models. System prompt, tool definitions, history and the output all share the context window. If the input alone is over the limit, the request fails (Anthropic returns a 400, "prompt is too long"). Estimate tokens before sending and set a maximum output length.&lt;/p&gt;

&lt;h2&gt;
  
  
  Inside the model: steps 5–6
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Ff84nmt1qsd889unweti4.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Ff84nmt1qsd889unweti4.png" alt="Prefill vs decode: a timeline from request sent through network and queue, a prefill block, the first token, then one decode step per token until a stop condition; TTFT and time per output token are marked" width="799" height="549"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;5. Prefill: the model reads all the input at once.&lt;/strong&gt; Inference has two phases. In &lt;em&gt;prefill&lt;/em&gt;, the model processes every input token in parallel. It's compute-heavy, and it's the main model-side driver of &lt;strong&gt;time to first token (TTFT)&lt;/strong&gt;. Network time and provider queueing add to that pause.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;6. Decode: one token at a time.&lt;/strong&gt; Then the model generates &lt;em&gt;autoregressively&lt;/em&gt;: score every token in the vocabulary, pick one, append it, repeat. A KV cache keeps earlier work so each step doesn't start over, and the per-step pace is the time per output token. It stops at an end-of-sequence token, a stop sequence or the token limit.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fp5qz4f0b143uqrsdv5v4.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fp5qz4f0b143uqrsdv5v4.png" alt="How the next token gets picked: a toy probability distribution for " width="800" height="808"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;How&lt;/em&gt; it picks is a sampling setting: greedy, or sampled with temperature, top-k or top-p. Don't assume those settings exist on every model: Anthropic's docs say Claude 4.7 and later return a 400 if you set them to non-default values.&lt;/p&gt;

&lt;h2&gt;
  
  
  After the call: steps 7–9
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F6er5qlw29t6rjwdamfd8.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F6er5qlw29t6rjwdamfd8.png" alt="Streaming with server-sent events: a sequence diagram where the provider sends token deltas to your server, which relays them to the browser; the stream ends with a final event or with an error event after a 200" width="800" height="795"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;7. Stream the tokens back.&lt;/strong&gt; OpenAI and Anthropic both stream tokens as server-sent events (SSE) while decoding is still running, so steps 6 and 7 overlap. Two catches from the docs: an error can arrive &lt;em&gt;mid-stream&lt;/em&gt;, after a 200 status, and partial output is harder to moderate than a finished response.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fvan47uh0xiof3z9s15mz.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fvan47uh0xiof3z9s15mz.png" alt="Validating the model's output: a decision flow that checks for a refusal, a response cut off at the token limit, and whether the output parses into the Pydantic model, before FastAPI's response_model check returns typed JSON" width="800" height="664"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;8. Validate the output too.&lt;/strong&gt; Structured outputs constrain the model to a JSON Schema you supply (OpenAI supports a subset), but OpenAI's guide says they can still contain mistakes, and documents two cases to handle: refusals and responses cut off at the token limit. If you stream, validate once the stream completes. FastAPI's &lt;code&gt;response_model&lt;/code&gt; is a second check: a mismatch becomes a server error, not wrong data. A valid shape isn't a correct answer; evals cover correctness later in this series.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fjsmrrxnhslc4y3i24yeg.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fjsmrrxnhslc4y3i24yeg.png" alt="Retry or not: a decision tree that sends rate limits, overloads and connection errors to limited retries, quota, billing and spend-cap errors to no retry, and bad requests or credentials to fix-first" width="800" height="670"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;9. Retry safely, then record.&lt;/strong&gt; The same status can mean different things: a 429 can be a rate limit, but Anthropic also uses it when you hit your monthly spend cap, so read the error body before retrying. Never retry quota or billing errors. For transient errors, honor &lt;code&gt;Retry-After&lt;/code&gt; when present, otherwise use exponential backoff with jitter, and cap attempts and total time. Official SDKs already retry some errors (Anthropic's twice by default), so count that in your limits rather than nesting loops. Then log input/output token usage, latency and the provider's request id. Those records feed debugging, cost tracking and, eventually, evaluation.&lt;/p&gt;




&lt;h3&gt;
  
  
  Takeaway
&lt;/h3&gt;

&lt;p&gt;As a front-end engineer, I found this oddly familiar: it's a request lifecycle with an unusual backend in the middle. Two of the nine steps are the model. The other seven are contracts, budgets, streams and failure handling, the parts an engineer owns. My working rule from here on: &lt;strong&gt;treat the model as an unreliable, metered, remote dependency, and put validation on both sides of it.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Where this fits in my roadmap:&lt;/strong&gt; this post is the map I'm following into the foundations block: Python typing and async, FastAPI and Pydantic, and LLM mechanics (tokens, context, inference). Next post: Python for AI backends: a TypeScript engineer's refresher.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Over to you:&lt;/strong&gt; which of these nine steps broke first in the first LLM feature you built?&lt;/p&gt;




&lt;h3&gt;
  
  
  Sources
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;OpenAI API reference: Authentication (don't expose API keys in client-side code). &lt;a href="https://developers.openai.com/api/reference/overview" rel="noopener noreferrer"&gt;https://developers.openai.com/api/reference/overview&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;FastAPI: Handling Errors (&lt;code&gt;RequestValidationError&lt;/code&gt; and its default handler). &lt;a href="https://fastapi.tiangolo.com/tutorial/handling-errors/" rel="noopener noreferrer"&gt;https://fastapi.tiangolo.com/tutorial/handling-errors/&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;FastAPI source: &lt;code&gt;exception_handlers.py&lt;/code&gt; (default validation handler returns 422). &lt;a href="https://github.com/fastapi/fastapi/blob/master/fastapi/exception_handlers.py" rel="noopener noreferrer"&gt;https://github.com/fastapi/fastapi/blob/master/fastapi/exception_handlers.py&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Pydantic: Models (post-validation type guarantees). &lt;a href="https://pydantic.dev/docs/validation/latest/concepts/models/" rel="noopener noreferrer"&gt;https://pydantic.dev/docs/validation/latest/concepts/models/&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Anthropic: Working with the Messages API (stateless, resend full history; sampling parameters on Claude 4.7+). &lt;a href="https://platform.claude.com/docs/en/build-with-claude/working-with-messages" rel="noopener noreferrer"&gt;https://platform.claude.com/docs/en/build-with-claude/working-with-messages&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;OpenAI: Conversation state (requests independent and stateless; optional state management; earlier input tokens still billed). &lt;a href="https://developers.openai.com/api/docs/guides/conversation-state" rel="noopener noreferrer"&gt;https://developers.openai.com/api/docs/guides/conversation-state&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Hugging Face LLM Course, Ch. 2: Tokenizers (subword tokenization, "token" + "ization"). &lt;a href="https://huggingface.co/learn/llm-course/chapter2/4" rel="noopener noreferrer"&gt;https://huggingface.co/learn/llm-course/chapter2/4&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Anthropic: Context windows (what counts toward the window; oversize input returns 400; token counting). &lt;a href="https://platform.claude.com/docs/en/build-with-claude/context-windows" rel="noopener noreferrer"&gt;https://platform.claude.com/docs/en/build-with-claude/context-windows&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Hugging Face LLM Course, Ch. 1: Deep dive into text generation inference (prefill/decode, TTFT, TPOT, KV cache, sampling, stop conditions). &lt;a href="https://huggingface.co/learn/llm-course/chapter1/8" rel="noopener noreferrer"&gt;https://huggingface.co/learn/llm-course/chapter1/8&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Vaswani et al., "Attention Is All You Need" (2017), the transformer/attention paper. &lt;a href="https://arxiv.org/abs/1706.03762" rel="noopener noreferrer"&gt;https://arxiv.org/abs/1706.03762&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;OpenAI: Streaming API responses (SSE, moderation risk for partial output). &lt;a href="https://developers.openai.com/api/docs/guides/streaming-responses" rel="noopener noreferrer"&gt;https://developers.openai.com/api/docs/guides/streaming-responses&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Anthropic: Streaming Messages (SSE). &lt;a href="https://platform.claude.com/docs/en/build-with-claude/streaming" rel="noopener noreferrer"&gt;https://platform.claude.com/docs/en/build-with-claude/streaming&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;OpenAI: Structured model outputs (schema adherence, supported subset, refusals, incomplete responses, mistakes still possible). &lt;a href="https://developers.openai.com/api/docs/guides/structured-outputs" rel="noopener noreferrer"&gt;https://developers.openai.com/api/docs/guides/structured-outputs&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;FastAPI: Response Model (server error instead of invalid returned data). &lt;a href="https://fastapi.tiangolo.com/tutorial/response-model/" rel="noopener noreferrer"&gt;https://fastapi.tiangolo.com/tutorial/response-model/&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Anthropic: Errors (429 incl. spend caps, 402 billing, 400 spend limit, 529 overloaded, SDK retries, mid-stream errors after a 200, request ids). &lt;a href="https://platform.claude.com/docs/en/api/errors" rel="noopener noreferrer"&gt;https://platform.claude.com/docs/en/api/errors&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;OpenAI: Rate limits (429/503, &lt;code&gt;Retry-After&lt;/code&gt;, backoff with jitter, cap retries, nested SDK retries, don't retry quota/billing errors). &lt;a href="https://developers.openai.com/api/docs/guides/rate-limits" rel="noopener noreferrer"&gt;https://developers.openai.com/api/docs/guides/rate-limits&lt;/a&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;em&gt;Sources checked Oct 18, 2026. Provider APIs change quickly. Re-check model-specific details (status codes, sampling support) right before publishing.&lt;/em&gt;&lt;/p&gt;




&lt;p&gt;&lt;em&gt;Originally published on The Path to AI FDE on Substack. Subscribe for one diagram-led post every weekday: &lt;a href="https://dhanushkumarsivaji.substack.com/p/the-path-to-ai-fde-01-anatomy-of" rel="noopener noreferrer"&gt;https://dhanushkumarsivaji.substack.com/p/the-path-to-ai-fde-01-anatomy-of&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;If this was useful, &lt;a href="https://dhanushkumarsivaji.substack.com/subscribe" rel="noopener noreferrer"&gt;subscribe to The Path to AI FDE&lt;/a&gt; for the next issue.&lt;/p&gt;

</description>
      <category>ai</category>
      <category>llm</category>
      <category>beginners</category>
      <category>python</category>
    </item>
  </channel>
</rss>
