<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by WeddyNkatha265 on Medium]]></title>
        <description><![CDATA[Stories by WeddyNkatha265 on Medium]]></description>
        <link>https://medium.com/@weddynkatha265?source=rss-16477706e78b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*drO2oAKuZZ0Gd6RLQniBtA.jpeg</url>
            <title>Stories by WeddyNkatha265 on Medium</title>
            <link>https://medium.com/@weddynkatha265?source=rss-16477706e78b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 13:59:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@weddynkatha265/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[TCP connection and how to see the 3-way handshake with tcpdump.]]></title>
            <link>https://medium.com/@weddynkatha265/tcp-connection-and-how-to-see-the-3-way-handshake-with-tcpdump-011d5cd0c85e?source=rss-16477706e78b------2</link>
            <guid isPermaLink="false">https://medium.com/p/011d5cd0c85e</guid>
            <dc:creator><![CDATA[WeddyNkatha265]]></dc:creator>
            <pubDate>Tue, 02 Sep 2025 12:11:43 GMT</pubDate>
            <atom:updated>2025-09-02T12:11:43.730Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*7ZpZlcfDsQVEcB-LaDDQtw.png" /></figure><p><strong>TCP connection</strong> and how to <strong>see the 3-way handshake with </strong><strong>tcpdump</strong>.</p><h3>What Really Happens When You Enter a Domain Name (Step by Step) [example.com]</h3><blockquote>Most of us type a URL and hit <em>Enter</em>. Under the hood, your <strong>client (browser)</strong> and the <strong>server</strong> perform a precise sequence — ending with a tiny but critical ritual: the <strong><em>TCP 3-way handshake.</em></strong></blockquote><p><strong>Step 1: DNS Lookup</strong><br> Your client asks DNS: <em>“What’s the IP of </em><em>example.com?”</em><br> It checks local cache, then your configured resolver, and finally the domain’s authoritative DNS. You get back an IP.</p><p><strong>Step 2: </strong>Connection to Server<strong> TCP Connection (3-Way Handshake)</strong></p><ul><li>The browser opens a TCP connection to that IP on <strong>port 80</strong> (because you didn’t type <a href="https://)./">https://).</a> In the case of apache or nginx</li><li>Before any data flows, client and server establish a <strong>reliable TCP connection</strong>:</li></ul><ol><li><strong>SYN</strong> → Client: “I want to connect.”</li><li><strong>SYN-ACK</strong> → Server: “I’m here; let’s sync.”</li><li><strong>ACK</strong> → Client: “Confirmed.”<br> Now the connection state is <strong>ESTABLISHED</strong> (tracked by the kernel), sequence numbers are set, and both sides can exchange bytes reliably.</li></ol><p><strong>Step 3: TLS Handshake (if HTTPS)</strong><br> Client and server authenticate (certificates) and agree on keys. From here, the TCP connection carries <strong>encrypted</strong> traffic.</p><p><strong>Step 4: HTTP Request</strong><br> Client sends:</p><pre>GET / HTTP/1.1<br>Host: dev.directcore.com</pre><p><strong>Step 5: Server Response</strong><br> Server returns HTML/JSON/etc. Rendering begins. Additional assets (CSS/JS/images) reuse the same TCP connection (HTTP/1.1 keep-alive) or multiplex over one connection (HTTP/2).</p><p><strong>Step 6: More Requests, Same Pipe</strong><br> Subsequent requests typically ride the existing TCP session until it’s closed, reducing extra handshakes.</p><h3>See the TCP Handshake Live with tcpdump (60-second lab)</h3><p>On the <strong>server</strong> (Linux):</p><pre># Install if needed<br>sudo apt-get install tcpdump -y</pre><pre># Watch only handshake flags on port 80 (HTTP)<br>sudo tcpdump -i any -nn &quot;tcp port 80 and (tcp[tcpflags] &amp; (tcp-syn|tcp-ack) != 0)&quot;</pre><p>From another terminal (client or the same box):</p><pre>curl -v http://example.com</pre><p>You’ll see lines like:</p><pre>... Flags [S]      ...   # SYN  (client → server)<br>... Flags [S.]     ...   # SYN-ACK (server → client)<br>... Flags [.]      ...   # ACK  (client → server)</pre><p>For HTTPS, just switch to port <strong>443</strong>:</p><pre>sudo tcpdump -i any -nn &quot;tcp port 443 and (tcp[tcpflags] &amp; (tcp-syn|tcp-ack) != 0)&quot;<br>curl -vk https://dev.directcore.com</pre><blockquote><em>That three-line burst is the </em><strong><em>3-way handshake</em></strong><em>. Only after it completes will you see HTTP or TLS messages.</em></blockquote><h3>Why this matters</h3><ul><li><strong>Reliability &amp; Ordering:</strong> TCP guarantees in-order, loss-recovered delivery — vital for web, SSH, databases.</li><li><strong>Performance:</strong> Each handshake adds a round-trip; keeping connections open (keep-alive, HTTP/2) cuts latency.</li><li><strong>Security &amp; Ops:</strong> Understanding handshakes helps diagnose timeouts, SYN floods, firewall state issues, and odd “stuck” connections.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=011d5cd0c85e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Your Quick Reference: Iterating Over Arrays]]></title>
            <link>https://medium.com/@weddynkatha265/your-quick-reference-iterating-over-arrays-d6bc81b780e6?source=rss-16477706e78b------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6bc81b780e6</guid>
            <dc:creator><![CDATA[WeddyNkatha265]]></dc:creator>
            <pubDate>Mon, 25 Aug 2025 09:16:45 GMT</pubDate>
            <atom:updated>2025-08-25T09:18:42.434Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/889/1*XB2dnZ25wl6-CsDOqnpCXg.jpeg" /></figure><p>If you’re heading into a tech interview whether you are a DevOps engineer or Software developer, chances are you’ll get a question on data structures.</p><p>Among their favorite asks? 👉 Iterating over an array.</p><h4>✅ In JavaScript</h4><pre>const arr = [1, 2, 3];<br><br>// Basic for loop<br>for (let i = 0; i &lt; arr.length; i++) {<br>  console.log(arr[i]);<br>}<br><br>// for...of loop<br>for (const item of arr) {<br>  console.log(item);<br>}<br><br>// forEach method<br>arr.forEach(item =&gt; {<br>  console.log(item);<br>});<br></pre><h4>✅ In Python</h4><pre>arr = [1, 2, 3]<br># Basic for loop<br>for item in arr:<br>    print(item)<br></pre><h4>✅ In Java</h4><pre>int[] arr = {1, 2, 3};<br><br>// Traditional for loop<br>for (int i = 0; i &lt; arr.length; i++) {<br>    System.out.println(arr[i]);<br>}<br>// Enhanced for loop<br>for (int item : arr) {<br>    System.out.println(item);<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6bc81b780e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ “I got into an interview and one of the questions I got was to define SSL vs TLS!!”]]></title>
            <link>https://medium.com/@weddynkatha265/i-got-into-an-interview-and-one-of-the-questions-i-got-was-to-define-ssl-vs-tls-755a77d61fb1?source=rss-16477706e78b------2</link>
            <guid isPermaLink="false">https://medium.com/p/755a77d61fb1</guid>
            <dc:creator><![CDATA[WeddyNkatha265]]></dc:creator>
            <pubDate>Mon, 25 Aug 2025 07:54:49 GMT</pubDate>
            <atom:updated>2025-08-25T07:54:49.577Z</atom:updated>
            <content:encoded><![CDATA[<p>🔐 <strong>So What is SSL vs TLS?</strong></p><p>SSL (Secure Sockets Layer) and TLS (Transport Layer Security) are both protocols that provide secure communication over a network. TLS is the successor to SSL, offering enhanced security and features. While the term “SSL” is still widely used, it generally refers to the underlying technology of TLS.</p><p>Here’s a breakdown:</p><p>SSL (Secure Sockets Layer):</p><ul><li><strong>Outdated:</strong> SSL versions (1.0, 2.0, and 3.0) are considered insecure and are deprecated.</li><li><strong>Vulnerabilities:</strong> Older versions of SSL have known security flaws that can be exploited.</li></ul><p>TLS (Transport Layer Security):</p><p><strong>Successor to SSL:</strong></p><ul><li>TLS is the modern and secure version of SSL, offering improvements in security and performance.</li></ul><p><strong>Widely Used:</strong></p><ul><li>TLS is the protocol used for securing web traffic and other network communications today.</li></ul><p><strong>Versions:</strong></p><ul><li>TLS has evolved with newer versions (1.0, 1.1, 1.2, and 1.3), with each version addressing vulnerabilities and improving security.</li></ul><p><strong>Still called SSL:</strong></p><ul><li>Despite the shift to TLS, the term “SSL” is still commonly used, sometimes interchangeably with TLS, or in the combined term “SSL/TLS”.</li></ul><p>Key Differences:</p><p><strong>Security:</strong></p><ul><li>TLS offers stronger encryption and more robust security features compared to SSL.</li></ul><p><strong>Handshake:</strong></p><ul><li>TLS has a more efficient handshake process than SSL, resulting in faster connection times.</li></ul><p><strong>Hashing:</strong></p><ul><li>TLS uses stronger hashing algorithms like SHA-256, while older SSL versions used algorithms like MD5 and SHA-1.</li></ul><p><strong>Encryption:</strong></p><ul><li>TLS uses more modern and secure encryption algorithms like AES, whereas SSL might use older algorithms like DES and RC4.</li></ul><p>In essence, when you see “SSL” today, it’s often referring to the underlying technology of TLS. TLS is the secure protocol actively used for securing internet connections.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=755a77d61fb1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A DevSecOps Guide to Keys & Certificates]]></title>
            <link>https://medium.com/@weddynkatha265/a-devsecops-guide-to-keys-certificates-d4bbdd35c320?source=rss-16477706e78b------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4bbdd35c320</guid>
            <dc:creator><![CDATA[WeddyNkatha265]]></dc:creator>
            <pubDate>Mon, 25 Aug 2025 07:10:25 GMT</pubDate>
            <atom:updated>2025-08-25T07:10:25.844Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. The Core Concepts: Keys and Certificates</h3><h4>What are Cryptographic Keys?</h4><p>At its core, cryptography uses keys — long strings of bits — to lock (encrypt) and unlock (decrypt) data. There are two main types:</p><p>Private Key: This is your secret. It must be kept absolutely confidential. It is used to:</p><ul><li>Decrypt data that was encrypted with its corresponding public key.</li><li>Create a digital signature to prove you are the sender of a message.</li></ul><p>Public Key: This is meant to be shared publicly. It is used to:</p><ul><li>Encrypt data that can only be decrypted by its corresponding private key.</li><li>Verify a digital signature created by the corresponding private key.</li></ul><p>This pair of keys is what’s known as Public Key Infrastructure (PKI).</p><h4>What is a Certificate?</h4><p>A certificate (or digital certificate) is a digital document that binds a public key to an identity (a person, website, company, etc.).</p><p>Think of it like a digital driver’s license:</p><ul><li>Your public key is your photo and physical description.</li><li>Your identity (e.g., “<a href="http://www.example.com/">www.example.com</a>&quot;) is your name and address.</li><li>The signature from a Certificate Authority (CA) is the government’s official seal that makes the license trustworthy.</li></ul><p>A certificate contains information like:</p><ul><li>The subject’s public key.</li><li>The subject’s identity (e.g., domain name).</li><li>The issuance and expiration dates.</li><li>The digital signature of the issuing Certificate Authority (CA).</li></ul><p>Your web browser or operating system trusts a pre-installed list of major CAs (like DigiCert, Let’s Encrypt, Google Trust Services). When you connect to https://www.google.com, its server presents its certificate. Your browser checks if a trusted CA signed it. If yes, the browser knows it&#39;s <em>really</em> talking to Google and not an impostor. It then uses the public key inside that certificate to establish a secure TLS/SSL connection.</p><h3>2. The File Formats: PEM vs. OpenSSH</h3><p>This is where the confusion often lies. PEM and the id_rsa format are different ways to <em>encode and store</em> the keys and certificates we just discussed.</p><h4>What is a PEM file?</h4><p>.pem (Privacy-Enhanced Mail) is a container format. It&#39;s not a type of key itself; it&#39;s a way to wrap and encode data (like keys and certificates) in text.</p><ul><li>Structure: A PEM file is plain text. It has a -----BEGIN SOMETHING----- header and a -----END SOMETHING----- footer. The &quot;SOMETHING&quot; tells you what&#39;s inside (e.g., CERTIFICATE, PRIVATE KEY, PUBLIC KEY, RSA PRIVATE KEY).</li><li>Encoding: The data between the headers is a Base64-encoded version of the binary data (usually in ASN.1 format).</li><li>Flexibility: As you correctly stated, a .pem file can contain almost anything: a private key, a public key, a certificate, or a combination of them (e.g., a certificate chain). You must open it to know what&#39;s inside.</li></ul><p>Example of a PEM private key:</p><pre>-----BEGIN PRIVATE KEY-----<br>MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC6...<br>... many more lines of base64 ...<br>-----END PRIVATE KEY-----</pre><p>Example of a PEM certificate:</p><pre>-----BEGIN CERTIFICATE-----<br>MIIFSTCCBDGgAwIBAgISA7hnhVV2+Gs7m3GFj1jFkX4nMA0GCSqGSIb3DQEBCwUA...<br>... many more lines of base64 ...<br>-----END CERTIFICATE-----</pre><h4>What are id_rsa and id_rsa.pub files?</h4><p>These are the default filenames for the private and public keys used by the OpenSSH tool suite, which is the standard for SSH authentication.</p><ul><li>id_rsa: This is an SSH private key in the OpenSSH format. It is functionally equivalent to a private key inside a .pem file but uses a different, more compact format.</li><li>id_rsa.pub: This is the corresponding SSH public key in OpenSSH format. It&#39;s a single line, typically starting with ssh-rsa AAAAB3....</li></ul><p>While the default format for OpenSSH keys is its own, OpenSSH can also read keys in the PEM format.</p><h3>The Key Difference: id_rsa vs. .pem</h3><p>Featureid_rsa (OpenSSH Format).pem (PEM Format)Primary Use CaseExclusively for SSH authentication. Logging into remote servers securely.A generic container. Used for TLS/SSL certificates (websites), email certificates (S/MIME), and can also store keys for SSH.What it ContainsAlmost always an SSH private key.A private key, a public key, a certificate, or a combination.FormatA specific, non-PEM format (though a PEM-like header is sometimes used).A defined text-based format with specific headers/footers and Base64 encoding.FlexibilityLow. Designed for one purpose: SSH keys.Very High. A universal container for various cryptographic objects.InteroperabilityMainly used by OpenSSH. Other tools might not understand it natively.The universal standard for TLS/SSL and many other cryptographic systems.</p><h3>How They Relate: Conversion</h3><p>You can often convert between these formats because, at their core, they represent the same underlying mathematical key pairs.</p><ul><li>Converting OpenSSH id_rsa to a PEM private key:<br>This is a very common task to make an SSH key usable with tools that only understand PEM (e.g., some AWS services).</li></ul><pre>ssh-keygen -p -m PEM -f ~/.ssh/id_rsa</pre><ul><li>This command will change your id_rsa file in-place to the PEM format. You can now use it as a .pem file.</li><li>Extracting the public key from a PEM private key for SSH:<br>If you have a private key in mykey.pem, you can generate the OpenSSH-format public key for it:</li></ul><pre>ssh-keygen -y -f mykey.pem &gt; mykey_public.pub</pre><ul><li>You can then add the contents of mykey_public.pub to a server&#39;s ~/.ssh/authorized_keys file.</li></ul><h3>Summary</h3><p>ConceptDescriptionAnalogyPrivate/Public KeyA matched pair for encryption and identity. The private key is secret, the public key is shared.A physical key (private) and a lock that anyone can use (public).CertificateA digital “driver’s license” that uses a CA’s signature to prove an identity (e.g., a website) owns a public key.A government-issued ID card that binds your photo to your name.PEMA flexible text-based file format (container) for storing keys and certificates.A standard manila folder. It can hold a passport, a birth certificate, or a will.id_rsaA specific SSH private key in the OpenSSH format, used primarily for logging into servers.A specific, branded keycard used only to enter your office building.</p><p>In a nutshell: id_rsa is a specific <em>type of key</em> for a specific <em>purpose</em> (SSH). .pem is a general-purpose <em>file format</em> that can hold that key, along with many other types of keys and certificates.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4bbdd35c320" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Install Clipboard Indicator on Ubuntu in 2 minutess!]]></title>
            <link>https://medium.com/@weddynkatha265/how-to-install-clipboard-indicator-on-ubuntu-in-2-minutess-659de6e0badd?source=rss-16477706e78b------2</link>
            <guid isPermaLink="false">https://medium.com/p/659de6e0badd</guid>
            <dc:creator><![CDATA[WeddyNkatha265]]></dc:creator>
            <pubDate>Thu, 26 Jun 2025 11:41:09 GMT</pubDate>
            <atom:updated>2025-06-26T11:41:09.334Z</atom:updated>
            <content:encoded><![CDATA[<iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FHC75FVqBAEo%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DHC75FVqBAEo&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FHC75FVqBAEo%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/e9b0cc4787865548141c0126b5aebc82/href">https://medium.com/media/e9b0cc4787865548141c0126b5aebc82/href</a></iframe><p><em>Never lose your copied items again! This works.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=659de6e0badd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Studying Python my second programming language after JavaScript]]></title>
            <link>https://medium.com/@weddynkatha265/studying-python-my-second-programming-language-after-javascript-3dd5d9f01e46?source=rss-16477706e78b------2</link>
            <guid isPermaLink="false">https://medium.com/p/3dd5d9f01e46</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[python-programming]]></category>
            <dc:creator><![CDATA[WeddyNkatha265]]></dc:creator>
            <pubDate>Sun, 01 Sep 2024 18:47:28 GMT</pubDate>
            <atom:updated>2024-09-01T18:47:28.366Z</atom:updated>
            <content:encoded><![CDATA[<h3>This is my first week</h3><p>PYTHON &amp;&amp; JS SIMILARITIES</p><p>— — Just like in JavaScript, Python has several common built-in data types for representing different kinds of information in our applications.</p><ul><li>Like JavaScript, Python lets you define strings with either single quotes or double quotes:</li><li>Like JavaScript, Python will convert an Integer to a Float when performing math operations. As you can see, the following calculations are equivalent:</li></ul><pre>4 / 3<br># 1.3333333333333333<br>4 / 3.0<br># 1.3333333333333333<br>float(4 / 3)<br># 1.3333333333333333</pre><ul><li>Like in JavaScript, you must use the return keyword to retrieve an output value from a function in PythoN</li></ul><h3>Function Scope in Python</h3><p>Just as in Python’s global scope, JavaScript’s outer scope rules would allow us to use a variable in the outer scope in our function:</p><ul><li>Just like JavaScript, Python has several ways we can control the flow of execution in our programs:</li><li>We can use conditional statements like if/else and try/except</li><li>We can use looping constructs like for and while</li></ul><p>Python &amp;&amp; JavaScript differences</p><ul><li>- print() is a built-in Python function that will output a string of text to the terminal. It&#39;s the Python equivalent of console.log() in JavaScript.</li><li>The line above print() is a Python comment. In Python, any line that starts with a # won&#39;t be executed by the interpreter. This is the Python equivalent of // in JavaScript.</li><li>In Python, it’s convention to use underscores ( _ ) to separate words in variables. This is referred to as <strong>snake case</strong> (as opposed to <strong>camel case</strong>, which is the convention in JavaScript).</li><li>If you want to use string interpolation in Python, use an f-String like so:</li></ul><pre># Python<br>dog_name = &quot;Lucy&quot;<br>print(f&quot;Say hello to my dog {dog_name}&quot;)<br># =&gt; Say hello to my dog Lucy</pre><p>This would be the equivalent of the following JavaScript code:</p><pre>// JavaScript<br>const dogName = &quot;Lucy&quot;;<br>console.log(`Say hello to my dog ${dogName}`);</pre><blockquote><em>NOTE: Backticks in Python are not valid characters, so </em><strong><em>don’t use backticks ( ` ) for strings in Python</em></strong><em>.</em></blockquote><p>You can also use f-Strings to do more advanced formatting. Say you want to display all prices with two decimal places:</p><pre>price_1 = 3<br>price_2 = 2.5</pre><pre>print(f&quot;Item 1 costs ${price_1:.2f}&quot;)<br># =&gt; Item 1 costs $3.00<br>print(f&quot;Item 2 costs ${price_2:.2f}&quot;)<br># =&gt; Item 2 costs $2.50</pre><ul><li>In Python, unlike JavaScript, there are two types of numbers: Integers and Floats.</li><li><strong>Integers</strong> are whole numbers, like 7. int()</li><li><strong>Floats</strong> are decimal numbers, like 7.3. float() class constructor functions:</li><li>Dictionaries are Python’s equivalent of a plain old JavaScript object.</li><li>Unlike JavaScript, you cannot use the dot notation to access keys on dictionaries — only the bracket notation will work: my_dict = { &quot;key1&quot;: &quot;value1&quot;, &quot;key2&quot;: &quot;value2&quot; }<br>my_dict.key2<br># =&gt; AttributeError: &#39;dict&#39; object has no attribute &#39;key2&#39;</li></ul><h3>None</h3><p>In Python, there is one special value that represents the <strong>absence</strong> of a value, None.</p><p>In JavaScript, there are two different data types for representing the absence of value: null and undefined:</p><pre>let noValue;<br>console.log(noValue);<br>// =&gt; undefined<br>noValue = null;<br>console.log(noValue);<br>// =&gt; null</pre><p>undefined in JavaScript generally comes up in a few places: when a variable has been created, but hasn&#39;t been assigned a value, and when a function doesn&#39;t have any return value. null, on the other hand, is used to explicitly signify the absence of any value.</p><p>Unlike JavaScript, Python won’t let you create a variable without assigning a value. You must explicitly assign a value of None if you want an &quot;empty&quot; variable:</p><pre>no_value<br># =&gt; NameError: name &#39;no_value&#39; is not defined</pre><pre>no_value = None<br>print(no_value)<br># =&gt; None</pre><h3>Booleans</h3><p>There are only two values of the Boolean data type: True and False. We can confirm this by inspecting True and False with the type() function.</p><pre>type(True)<br># =&gt; &lt;class &#39;bool&#39;&gt;<br>type(False)<br># =&gt; &lt;class &#39;bool&#39;&gt;</pre><p>Python, like JavaScript, has the concept of “truthy” and “falsy” values as well:</p><ul><li>NOTE: not is the operator that reverses the truth value of a value, variable, or statement. ! still plays a role in Python, but it is only used in the != operator that asserts that two values are not equal.</li></ul><h3>Functions</h3><p>JavaScript function</p><pre>function myFunction(param) {<br>  console.log(&quot;Running myFunction&quot;);<br>  return param + 1;<br>}</pre><p>As a quick recap of the syntax here:</p><ul><li>The <strong>function keyword</strong> identifies this code as a function.</li><li>myFunction is a <strong>variable name</strong> we can use to refer to the function from elsewhere in our code, written in camel case by convention.</li><li>The parentheses () after the function name give a space where we can define <strong>parameters</strong> for our function.</li><li>param is the variable name given to our function&#39;s parameter; it will be assigned a value when the function is invoked and passed an argument.</li><li>To define the body of the function, we use curly brackets ({ }).</li><li>console.log is a method that will output information to the terminal; remember, this is <em>different</em> from a function&#39;s <strong>return value</strong>.</li><li>The return keyword is needed when we want our function to return a value when it is called; in this case, it will return a value of whatever the param variable is plus one.</li></ul><p>To actually run the code inside the function, we must invoke it:</p><pre>const myFunctionReturnValue = myFunction(1);<br>// =&gt; &quot;Running myFunction&quot;<br>console.log(myFunctionReturnValue);<br>// =&gt; 2</pre><p>Here, we&#39;re calling the function myFunction with an <strong>argument</strong> of 1. We are then assigning the <strong>return value</strong> of myFunction to a new variable, myFunctionReturnValue.</p><p>If we wanted to write a method in Python with similar functionality, here&#39;s how it would look:</p><pre>def my_function(param):<br>    print(&quot;Running my_function&quot;)<br>    return param + 1<br><br># New code goes here!</pre><p>There are a few key differences in the syntax here:</p><ul><li>Use the def keyword to identify this code as a function.</li><li>Write the name of the method in snake case (by convention).</li><li>Parameters are still defined in parentheses, after the method name.</li><li>Instead of curly brackets, begin with a colon after the parentheses.</li><li>In Python, we must indent all code that is meant to be executed in my_function. The <a href="https://peps.python.org/pep-0008/">PEP-8 standardsLinks to an external site.</a> for writing Python code state that each indentation should be composed of four spaces (though the interpreter is less picky).</li><li>return statements in Python work very similarly to those in JavaScript, but no semicolon is needed after the return value.</li><li>Rather than closing with a curly bracket, any new code can be written at the original indentation level.</li></ul><p>Run the Python shell and copy/paste the function definition above into your session. Then, run the function:</p><pre>my_function_return_value = my_function(1)<br># =&gt; Running my_function<br># =&gt; 2<br>my_function_return_value<br># =&gt; 2</pre><p>When the my_function() function is called, you&#39;ll see the output from the print() function in the terminal, followed by the return value. The return value, 2, is then saved to the variable my_function_return_value.</p><blockquote><em>You might see some functions referred to as </em><strong><em>methods</em></strong><em>. Methods are a special type of function that belong to </em><strong><em>objects</em></strong><em>. They often act upon those objects when called- remember </em><em>list.sort() and </em><em>dict.get()?</em></blockquote><h3>Arguments</h3><p>JavaScript allows you to define functions that expect a certain number of arguments, but will still run your code even if you don’t pass in the expected number when you invoke the function. This can lead to some unexpected behavior in your JavaScript applications.</p><p>Consider the following:</p><pre>function sayHi(name) {<br>  console.log(`Hi there, ${name}!`);<br>}</pre><pre>sayHi();</pre><p>What do you think will happen when this code runs? Will it throw an error? Print something to the console? If so, what? Try running it in the browser to find out.</p><p>Unfortunately for JavaScript developers, bugs like these are hard to identify because they can only be found by testing our code and looking for unexpected behavior.</p><p>In Python, thankfully, when we run a method without passing in the required arguments it will give us an error message:</p><pre>def say_hi(name):<br>    print(f&quot;Hi there, {name}!&quot;)</pre><pre>say_hi()<br># =&gt; TypeError: say_hi() missing 1 required positional argument: &#39;name&#39;</pre><p>Error messages like this are a <strong>good thing</strong> for us as developers, because it ensures that we are using methods as they are intending to be used, rather than trying to “fail gracefully” like JavaScript does.</p><p>Note that this mistake resulted in a TypeError. What <em>type</em> of input did we provide? What <em>type</em> did say_hi() expect?</p><h3>Default Arguments</h3><p>We can fix the behavior of our JavaScript function above by providing a default argument: a value that will be used if we don’t explicitly provide one.</p><pre>function sayHi(name = &quot;friend&quot;) {<br>  console.log(`Hi there, ${name}!`);<br>}</pre><pre>sayHi();<br>// =&gt; &quot;Hi there, friend!&quot;<br>sayHi(&quot;Sunny&quot;);<br>// =&gt; &quot;Hi there, Sunny!&quot;</pre><p>Python also lets us provide default arguments:</p><pre>def say_hi(name=&quot;Engineer&quot;):<br>    print(f&quot;Hi there, {name}!&quot;)</pre><pre>say_hi()<br># =&gt; &quot;Hi there, Engineer!&quot;</pre><pre>say_hi(&quot;Sunny&quot;)<br># =&gt; &quot;Hi there, Sunny!&quot;</pre><h3>Variable Names and Scope</h3><p>Let’s take a look at the following example:</p><pre>name = &quot;Joe&quot;</pre><pre>def greeting():<br>    print(f&quot;Hello, {name}&quot;)</pre><p>In this code snippet, we have a variable, name, set equal to a string, &quot;Joe&quot;. Then we define a function, greeting(), that takes no arguments and prints out the value of the name variable. Let&#39;s fire up the Python shell, cross our fingers, and give it a go:</p><pre>&gt; greeting()<br># Hello, Joe</pre><p>As we can see, the value of our <em>global</em> variable was accessible inside of our greeting() function. Let&#39;s try another example:</p><pre>name = &quot;Joe&quot;</pre><pre>def greeting(name):<br>    print(f&quot;Hello, {name}&quot;)</pre><p>In this code snippet, we have a variable, name, set equal to a string, &quot;Joe&quot;. Then we define a function, greeting(), that takes in an argument of name. Are the name variable that is set equal to &quot;Joe&quot; and the name variable we are using as a parameter (or argument) for our greeting() function definition the same? Let&#39;s see.</p><p>If we call our greeting function in the following way:</p><pre>greeting(&quot;Sophie&quot;)</pre><h3>Function Scope in Python</h3><p>Just as in Python’s global scope, JavaScript’s outer scope rules would allow us to use a variable in the outer scope in our function:</p><pre>const evilMonster = &quot;Bowser&quot;;</pre><pre>function princessPeachsCastle() {<br>  console.log(`${evilMonster} is trying to kidnap Princess Peach!`);<br>}</pre><p>And in Python:</p><pre>evil_monster = &quot;Bowser&quot;</pre><pre>def princess_peachs_castle():<br>    print(f&quot;{evil_monster} is trying to kidnap Princess Peach!&quot;)</pre><p>So far, we’ve been looking from the <em>global</em> scope inward to the <em>local</em> scope. Let’s take a look in the other direction:</p><p>If we define the following function to include a local variable:</p><pre>def practicing_function_scope():<br>  im_trapped_in_the_function = &quot;You can&#39;t access me outside this function!&quot;</pre><p>Trying to access that variable elsewhere in our program, <em>outside of this function</em>, will raise the following error:</p><pre>&gt; print(im_trapped_in_the_function)<br># NameError: name &#39;im_trapped_in_the_function&#39; is not defined</pre><h3>The global Keyword</h3><p>Earlier, we accessed some <em>global</em> variables, name and evil_monster, from inside of functions. What do you think would happen if we tried to change a <em>global</em> value from a <em>local</em> scope?</p><pre>change_the_world = &quot;change yourself&quot;</pre><pre>def change_yourself():<br>    change_the_world = &quot;world changed&quot;</pre><p>When we enter this code in the Python shell and try to run change_yourself(), we don&#39;t see the change we&#39;re seeking:</p><pre>&gt; change_yourself()<br>&gt; print(change_the_world)<br># change yourself</pre><p>To change the value of a <em>global</em> variable from a <em>local</em> scope, we need to use the global keyword:</p><pre>change_the_world = &quot;change yourself&quot;</pre><pre>def change_yourself():<br>    global change_the_world<br>    change_the_world = &quot;world changed&quot;</pre><p>Now when we run our function again, we should see the desired output:</p><pre>&gt; change_yourself()<br>&gt; print(change_the_world)<br># world changed</pre><blockquote><em>NOTE: It is </em><strong><em>very rare</em></strong><em> that you will use the </em><em>global keyword in your code; Python&#39;s scope rules help provide predictable behavior and easier paths to follow backward to find bugs. Only override those rules when absolutely necessary!</em></blockquote><h3>Conclusion</h3><p>Remember: A local variable defined inside a function can’t leave that function. It is not available to your program outside of the function. A global variable defined outside of a function is accessible inside the function, just as in JavaScript. Global variables can only be <em>modified</em> from the global scope or by using the global keyword.</p><ul><li>Unlike in JavaScript, the == function in Python <strong>will not coerce strings to numbers</strong> before comparing them, or perform some of the other type coercions that JavaScript does. For example, in JavaScript, using the == operator can lead to some strange behavior:</li></ul><pre>&quot;1&quot; == 1<br>// =&gt; true<br>0 == []<br>// =&gt; true<br>[] == ![]<br>// =&gt; true 🤔</pre><p>In Python, the == function checks if the objects on both sides are considered the equivalent values:</p><pre>&quot;1&quot; == 1<br># False<br>1 == 1<br># True</pre><p>There are some differences between Python’s == and JavaScript&#39;s === though. In JavaScript, the === operator checks if both objects have the same identity, i.e. refer to the same space in memory. For example, in JavaScript, this example returns false because the two arrays are unique objects in memory:</p><pre>[1, 2, 3] === [1, 2, 3];<br>// =&gt; false</pre><p>In Python, this example returns True because Python considers these to have equivalent values:</p><pre>[1, 2, 3] == [1, 2, 3]<br># True</pre><p>Python will also check if an Integer has the equivalent value to a Float, even though they’re technically different data types:</p><pre>1.0 == 1<br># True</pre><blockquote><strong><em>Note</em></strong><em>: While Python does have an operator, </em><em>is, that is similar to JavaScript&#39;s </em><em>===, </em><strong><em>it is not used the same way as it is in JavaScript</em></strong><em>. There are very few scenarios when you want to use the </em><em>is operator in Python; in general, for comparing data, you want to use the </em><em>==. </em><a href="https://stackoverflow.com/questions/21774629/python-is-vs-javascript"><em>See here for examplesLinks to an external site.</em></a><em> if you&#39;re curious about what this operator does.</em></blockquote><h3>if/else Statements</h3><p>Python has slightly different syntax for writing conditional statements using if/else than JavaScript. Here&#39;s a relatively complex if/else statement in JavaScript:</p><pre>// JavaScript<br>let dog = &quot;cuddly&quot;;<br>let owner;</pre><pre>if (dog === &quot;hungry&quot;) {<br>  owner = &quot;Refilling food bowl.&quot;;<br>} else if (dog === &quot;thirsty&quot;) {<br>  owner = &quot;Refilling water bowl.&quot;;<br>} else if (dog === &quot;playful&quot;) {<br>  owner = &quot;Playing tug-of-war.&quot;;<br>} else if (dog === &quot;cuddly&quot;) {<br>  owner = &quot;Snuggling.&quot;;<br>} else {<br>  owner = &quot;Reading newspaper.&quot;;<br>}</pre><p>Here’s how we can write the equivalent statement in Python:</p><pre># Python<br>dog = &quot;cuddly&quot;</pre><pre>if dog == &quot;hungry&quot;:<br>    owner = &quot;Refilling food bowl.&quot;<br>elif dog == &quot;thirsty&quot;:<br>    owner = &quot;Refilling water bowl.&quot;<br>elif dog == &quot;playful&quot;:<br>    owner = &quot;Playing tug-of-war.&quot;<br>elif dog == &quot;cuddly&quot;:<br>    owner = &quot;Snuggling.&quot;<br>else:<br>    owner = &quot;Reading newspaper.&quot;</pre><p>Notice that the owner variable here was not defined above like it would be in JavaScript. This is because Python does not require the variable to be declared or initialized prior to the conditional. In Python, a variable can be in scope for the entire class or function. Therefore, we can use the owner variable for the rest of the class since it is in <strong>local scope</strong>.</p><h3>Basic Loops in Python</h3><p>In JavaScript, there are a few common approaches to control flow that will allow us to run the same lines of code over and over again. The most basic tool is the while loop, which works like this in JavaScript:</p><pre>let i = 0;<br>while (i &lt; 5) {<br>  console.log(&quot;Looping!&quot;);<br>  i++;<br>}</pre><p>Python has a while construct too, which works in much the same way:</p><pre>i = 0<br>while i &lt; 5:<br>  print(&quot;Looping!&quot;)<br>  i += 1</pre><h3>Looping with for</h3><p>JavaScript has a for loop, which is commonly used to run some condition a set number of times:</p><pre>for (let i = 0; i &lt; 10; i++) {<br>  console.log(`Looping!`);<br>  console.log(`i is: ${i}`);<br>}</pre><p>Python also has a for loop (with slightly simpler syntax!):</p><pre>for i in range(10):<br>    print(&quot;Looping!&quot;)<br>    print(f&quot;i is: {i}&quot;)</pre><p>When writing a for loop in Python, the loop can proceed through any iterable object type. These include list, tuple, set, and dict objects, as well as str and range objects. range objects are especially useful in the for construct because they generate an ordered sequence of ints from 0 through a number of your choosing (like 10, above).</p><p>A for loop in Python automatically proceeds to the next element of the iterable object in its constructor; there is no need to specify that the loop is stopping at a certain point or increasing after each iteration.</p><h3>Introduction</h3><p>A <em>sequence</em> is a simple data structure that is present in all programming languages in which data is stored in a specified order. The elements of a sequence can be accessed by their <em>index</em>. Just as in JavaScript, indices of a sequence begin at 0 and increase by 1 with each step down the sequence:</p><pre>// JavaScript<br>const my_list = [1, 2, 3, 4];<br>console.log(my_list[0]);<br>// 1</pre><pre># Python<br>my_list = [1, 2, 3, 4]<br>print(my_list[0])<br># =&gt; 1</pre><p>list and tuple objects can store any type of data. range objects store only integers, and str objects can only store unicode characters.</p><p><em>PYTHON</em></p><h3>Key Vocab</h3><ul><li><strong>Interpreter</strong>: a program that executes other programs. Python programs require the Python interpreter to be installed on your computer so that they can be run.</li><li><strong>Python Shell</strong>: an interactive interpreter that can be accessed from the command line.</li><li><strong>Data Type</strong>: a specific kind of data. The Python interpreter uses these types to determine which actions can be performed on different data items.</li><li><strong>Exception</strong>: a type of error that can be predicted and handled without causing a program to crash.</li><li><strong>Code Block</strong>: a collection of code that is interpreted together. Python groups code blocks by indentation level.</li><li><strong>Function</strong>: a named code block that performs a sequence of actions when it is called.</li><li><strong>Scope</strong>: the area in your program where a specific variable can be called.</li></ul><p>Python, on the other hand, <strong>can’t</strong> run in the browser.</p><ul><li>You can check which version of Python you’re using with this command:</li></ul><pre>$ python --version<br>Python 3.8.13</pre><p>To run the application, enter the command python filename.py, where filename.py is the relative path to the file you&#39;d like to run:</p><pre>$ python lib/app.py<br>Hello world!</pre><p>Congrats on running your first Python application! 🎉</p><p>Let’s say you’re writing a full paragraph and don’t need a newline character after every sentence. print() can accommodate that through its optional end parameter. Try modifying your print() statements as follows:</p><pre># lib/app.py<br>print(&quot;Hello world!&quot;, end=&quot; &quot;)<br>print(&quot;Hello sun!&quot;, end=&quot;!! &quot;)<br>print(&quot;Hello sky!&quot;, end=&quot;!!!\n&quot;)</pre><p>What do you see when you execute lib/app.py from the command line with these new end strings?</p><pre>$ python lib/app.py<br># =&gt; Hello world! Hello sun!!! Hello sky!!!!</pre><p>end can be a string of any length, including characters like the newline \n.</p><p><strong>Python comes with a command line interpreter (often called the “Python shell”) for running a Python REPL (read-evaluate-print-loop) in the terminal, which provides similar functionality to the browser console that you’re familiar with from JavaScript.</strong> Using the Python shell is a great way to quickly test out some code, or check your syntax, without needing to run an entire application.</p><p>To use the Python shell, go into the terminal and enter python:</p><pre>$ python<br>Python 3.8.13 (default, Jun  2 2022, 15:59:12)<br>[Clang 13.1.6 (clang-1316.0.21.2.5)] on darwin<br>Type &quot;help&quot;, &quot;copyright&quot;, &quot;credits&quot; or &quot;license&quot; for more information.<br>&gt;&gt;&gt;</pre><p>Try running a few more expressions in the Python Shell:</p><pre>&gt;&gt;&gt; first_number = 7<br>&gt;&gt;&gt; print(first_number)<br># =&gt; 7</pre><p>In the code above, we’ve declared a <strong>local variable</strong> called first_number and assigned it a value of 7. When we tell the Python shell to print(first_number), we see our local variable&#39;s value on the next line.</p><blockquote><em>In Python, it’s convention to use underscores ( _ ) to separate words in variables. This is referred to as </em><strong><em>snake case</em></strong><em> (as opposed to </em><strong><em>camel case</em></strong><em>, which is the convention in JavaScript).</em></blockquote><p>You can exit the Python shell by typing exit(), or pressing ctrl + d.</p><p>To install pytest and any other required libraries, simply navigate to a folder with a Pipfile and enter pipenv install:Now that your pipenv virtual environment is ready to use, enter pipenv shell to start working:</p><p>You can also use the -x flag to tell pytest to stop running after the first failing test. This technique is helpful for focusing your attention on one problem at a time:</p><pre>$ pytest -x</pre><p>You can also create a new string by using the built-in str() constructor function (though it&#39;s not common you&#39;d need to):</p><pre>str(&quot;I&#39;m a string&quot;)</pre><ul><li>You’ll often hear it said that <strong>“in Python, everything is an object”</strong>. All of the methods that we called on strings above are available because the string literal “hello” is an <strong>instance</strong> of the String class. Thanks to Python&#39;s <a href="https://www.geeksforgeeks.org/python-type-function/">type()Links to an external site.</a> function, you can see for yourself:</li></ul><pre>type(&quot;hello&quot;)<br># =&gt; &lt;class &#39;str&#39;&gt;</pre><p>Using the dir() function on any Python object will display a list of all the methods that object responds to (you&#39;ll see upper, lower, capitalize and more in that list):</p><pre>dir(&quot;hello&quot;)<br># =&gt; [&#39;__add__&#39;, &#39;__class__&#39;, &#39;__contains__&#39;, &#39;__delattr__&#39;, &#39;__dir__&#39;, ..</pre><ul><li>NOTE: Methods that are preceded and followed by double underscores are called <strong>magic methods</strong> or <strong>dunder methods</strong> (<strong>d</strong>ouble <strong>under</strong>score). Magic methods run automatically under certain conditions- we’ll learn more about them when we cover object-oriented programming.</li></ul><p>Sequence Types</p><ul><li>[1, 3, 400, 7] is a list of integers. Just typing list() will create an empty list ([]):</li></ul><pre>list()<br># =&gt; []<br>list_abc = [&#39;a&#39;,&#39;b&#39;,&#39;c&#39;]<br>list_abc[0]<br># =&gt; &#39;a&#39;<br>list_abc[1]<br># =&gt; &#39;b&#39;<br>list_abc[2]<br># =&gt; &#39;c&#39;<br>len([1, 3, 400, 7])<br># 4<br>sorted([5, 100, 234, 7, 2])<br># [2, 5, 7, 100, 234]<br>list_123 = [1, 2, 3]<br>list_123.pop()<br># 3<br>list_123.remove(1)<br>print(list_123)<br># [2]</pre><h3>Tuples</h3><p>Tuples are nearly identical to lists, with two key differences:</p><p>First, tuples are created with open and close parentheses (in place of square brackets). The tuple() class constructor function can also be used to cast lists and other iterable data types to tuples.</p><pre>(1, 2, 3)<br># =&gt; (1, 2, 3)<br>tuple([1, 2, 3])<br># =&gt; (1, 2, 3)</pre><p>Second, tuples are <strong>immutable</strong>. This means that once a tuple has been created, the tuple itself cannot be changed .While tuples are less flexible than lists, this can prove advantageous in certain situations</p><ul><li><strong>NOTE: Parentheses can also be used for order of operations and grouping statements. To let Python know that it’s looking at a tuple, there has to be at least one comma- even in tuples with only one element: </strong><strong>(1,).</strong></li></ul><h3>Sets</h3><p>A <a href="https://docs.python.org/3/library/stdtypes.html#set">setLinks to an external site.</a> is unindexed, unordered, and unchangeable. It can be initiated with curly brackets or the set() class constructor. The set() class constructor takes a list or tuple as its only argument (remember those brackets and parentheses!) The elements of a set are unique:</p><pre>set()<br># =&gt; {}</pre><pre>set(3, 2, 3, &#39;a&#39;, &#39;b&#39;, &#39;a&#39;)<br># =&gt; TypeError: set expected at most 1 argument, got 6</pre><pre>set([3, 2, 3, &#39;a&#39;, &#39;b&#39;, &#39;a&#39;])<br># =&gt; {2, 3, &#39;a&#39;, &#39;b&#39;}</pre><p><strong>Unindexed</strong> means that we cannot access elements of the set using square brackets as we do in lists and tuples.</p><p><strong>Unordered</strong> means that the contents of the set are in a random order.</p><p><strong>Unchangeable</strong> means that the individual elements of a set cannot be changed.</p><blockquote><em>NOTE: </em>Immutable<em> and </em>unchangeable<em> mean different things when we’re talking about data types in Python. A set is not immutable because its overall structure can be changed; it can be made shorter or longer. It is unchangeable because an element cannot be changed into something else.</em></blockquote><p>Sets have many of the same methods as lists:</p><pre>s = {1, 2, 3}<br>s.pop()<br># =&gt; 1<br>s.remove(3)<br># =&gt; {2}</pre><h3>Dictionaries</h3><pre>my_dict = { &quot;key1&quot;: 1, &quot;key2&quot;: 2 }<br>my_dict[&quot;key2&quot;]<br># =&gt; 2</pre><p>You can also use the built-in <a href="https://www.w3schools.com/python/ref_dictionary_get.asp">.get() methodLinks to an external site.</a> to retrieve the value for a key. This is a useful method for times when you&#39;re unsure if a key exists, as it returns None instead of an error if no matching key exists:</p><pre>my_dict = { &quot;key1&quot;: &quot;value1&quot;, &quot;key2&quot;: &quot;value2&quot; }<br>print(my_dict[&quot;key3&quot;])<br># =&gt; KeyError: &#39;key3&#39;</pre><pre>print(my_dict.get(&quot;key3&quot;))<br># =&gt; None</pre><p>You can also create dictionaries using the <a href="https://docs.python.org/3/tutorial/datastructures.html#dictionaries">dict() class constructorLinks to an external site.</a>.</p><pre>dict(x = 1, y = 2)<br># =&gt; {&#39;x&#39;: 1, &#39;y&#39;: 2}</pre><h3>None</h3><h3>Booleans</h3><p>There are only two values of the Boolean data type: True and False. We can confirm this by inspecting True and False with the type() function.</p><pre>type(True)<br># =&gt; &lt;class &#39;bool&#39;&gt;<br>type(False)<br># =&gt; &lt;class &#39;bool&#39;&gt;</pre><h3>Truthy/Falsy Values</h3><p>In order to use control flow effectively, it’s important to know what values Python treats as “truthy” and “falsy”.</p><p>As we saw in the lesson on data types, there are many values Python considers falsy:</p><ul><li>Empty lists []</li><li>Empty tuples ()</li><li>Empty dictionaries {}</li><li>Empty sets set()</li><li>Empty strings &#39;&#39; or &quot;&quot;</li><li>Zero of any numeric type (0, 0.0)</li><li>None</li><li>And, of course, False</li></ul><p>Using those values in control flow means the condition will be False:</p><pre>def control_flow(value):<br>    if value:<br>        # if the value is truthy<br>        print(&quot;yep!&quot;)<br>    else:<br>        # if the value is falsy<br>        print(&quot;nope!&quot;)</pre><pre>control_flow(False)<br># &quot;nope!&quot;<br>control_flow(None)<br># &quot;nope!&quot;<br>control_flow(True)<br># &quot;yep!&quot;<br>control_flow(&quot;&quot;)<br># &quot;nope!&quot;<br>control_flow(0)<br># &quot;nope!&quot;<br>control_flow(&quot;0&quot;)<br># &quot;yep!&quot;</pre><h3>Conditional Expressions</h3><p>Python also allows us to use <strong>conditional expressions</strong> (or <strong>ternary operators</strong>) to evaluate the truthiness of complex statements in a single line.</p><pre>age = 1</pre><pre>is_baby = &#39;baby&#39; if age &lt; 2 else &#39;not a baby&#39;</pre><p>This is the equivalent of the following if/else statement:</p><pre>age = 1<br>if age &lt; 2:<br>  is_baby = &#39;baby&#39;<br>else:<br>  is_baby = &#39;not a baby&#39;</pre><p>Conditional expressions in Python are always of the format:</p><pre>value_if_true if condition else value_if_false</pre><p>Python requires a default value (preceded by the else keyword) in every conditional statement. It may seem like a pain at first, but it helps to prevent unexpected exceptions and Nones as you continue to build your application.</p><h3>Reading Python Error Messages</h3><h3>Three Common Error Types</h3><h3>Syntax Errors</h3><p>Syntax errors are pretty self-explanatory: they’re the result of incorrect syntax. Thankfully, they’re usually followed by a guess about the location of the error. For instance:</p><pre>2 * #</pre><p>Will result in:</p><pre>File &quot;&lt;stdin&gt;&quot;, line 1<br>    2 * #<br>        ^<br>SyntaxError: invalid syntax</pre><h3>Logic Errors</h3><pre>count = 1<br>while count &lt; 100:<br>    print(&quot;%i&quot; % count)</pre><p>Will produce the following output:</p><pre>1<br>1<br>1<br>1<br>1<br>1<br>1<br>...</pre><p>The programmer here forgot to increase the count during each iteration of the while loop. This is perfectly valid Python code, so the interpreter will not throw an error, but the loop will continue forever until it is manually stopped by the user. (The easiest way to do this in the terminal is ctrl + c)</p><h3>Exceptions</h3><p><a href="https://docs.python.org/3/library/exceptions.html">ExceptionsLinks to an external site.</a> cover a wide variety of errors that you may see when running Python code. Our NameError from earlier is one example of a Python exception.</p><p>There are many types of exceptions in Python; here are a few of the most common:</p><h4>AssertionError</h4><p>An assert() statement tells the interpreter that the code inside of it must proceed without error or exception. If an assertion fails, an AssertionError is raised.</p><pre>assert(1 == 2)<br>Traceback (most recent call last):<br>  File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;<br>AssertionError</pre><h4>IndexError and KeyError</h4><p>IndexErrors arise when you try to access an element at an index past the end of a list. Key errors relate to dict objects in Python (similar to JSON objects). If a key is referenced but does not exist, this exception is thrown.</p><pre>&gt; list = [0, 1, 2, 3, 4]<br>&gt; dict = {&#39;a&#39;:1, &#39;b&#39;:2, &#39;c&#39;:3}</pre><pre>&gt; list[10]<br>Traceback (most recent call last):<br>  File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;<br>IndexError: list index out of range</pre><pre>&gt; dict[&#39;d&#39;]<br>Traceback (most recent call last):<br>  File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;<br>KeyError: &#39;d&#39;</pre><h4>NameError</h4><p>A NameError arises when a name is referenced before it has been defined.</p><pre>&gt; flatiron_school<br>Traceback (most recent call last):<br>  File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;<br>NameError: name &#39;flatiron_school&#39; is not defined</pre><h4>TypeError</h4><p>TypeErrors arise when an operation or function is applied to an object of the wrong type.</p><pre>&gt; wrong_type = &#39;abc&#39; + 123<br>Traceback (most recent call last):<br>  File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;<br>TypeError: can only concatenate str (not &quot;int&quot;) to str</pre><h3>pass</h3><p>There will be times when you’re writing out your code and know that you will need a function later, but you don’t quite know what to put in there yet. A good practice in Python development is to make use of the pass keyword in empty functions until they are ready to be fleshed out.</p><pre>def my_future_function():<br>    pass</pre><p>Because Python uses indentation to determine when a code block starts and ends, it is necessary to put <em>something</em> inside of an empty function- comments, sadly, do not count.</p><p>Python developers typically opt for pass over return None because it is a statement rather than an expression. It does not terminate the function like a return statement would do. You can even put code after your pass and it will be executed! A pass statement reminds you that there is work to be done without interfering with your development.</p><h3>Debugging with ipdb</h3><h3>What Is a REPL?</h3><p>You’ve already been introduced to REPLs through using the Python Shell. REPL stands for <em>Read, Evaluate, Print, Loop</em>. It is an interactive programming environment that takes a user’s input, evaluates it and returns the result to the user.</p><p>Python installs with its own REPL, which is the Python shell that you’ve already been using. Every time you type python into your terminal, you&#39;re entering into a REPL.</p><h3>Using ipdb.set_trace()</h3><p>First, let’s make sure we have installed the packages from our Pipfile, including ipdb.</p><pre>&gt; pipenv install<br>&gt; pipenv shell</pre><blockquote><em>NOTE: This will only install </em><em>ipdb in your </em><strong><em>virtual environment</em></strong><em>. If you want to install </em><em>ipdb system-wide, you must exit your virtual environment and run the following command in your local environment:</em></blockquote><blockquote><em>&gt; pip install ipdb</em></blockquote><p>Look at the code in lib/ipdb_is_awesome.py. You should see the following code:</p><pre>import ipdb</pre><pre>def tracing_the_function():<br>    inside_the_function = &quot;We&#39;re inside the function&quot;<br>    print(inside_the_function)<br>    print(&quot;We&#39;re about to stop because of ipdb!&quot;)<br>    ipdb.set_trace()<br>    this_variable_hasnt_been_interpreted_yet = \<br>        &quot;The program froze before it could read me!&quot;<br>    print(this_variable_hasnt_been_interpreted_yet)</pre><pre>tracing_the_function()</pre><p>At the top of the file, import ipdb is a statement that loads the ipdb library in this file when our application runs, very similar to import statements in JavaScript.</p><blockquote><em>We will elaborate on Python </em><em>import statements later in Phase 3, but note now that Python </em><em>import statements </em><strong><em>do not</em></strong><em> use quotes or semicolons.</em></blockquote><p>After importing ipdb, <em>which you must do to use </em><em>ipdb</em>, we define a function, and then call that function.</p><p>In the directory of this repo, in your terminal, run the file by typing python lib/ipdb_is_awesome.py. Now, look at your terminal. You should see something like this:</p><pre>&gt; python lib/ipdb_is_awesome.py<br>We&#39;re inside the function<br>We&#39;re about to stop because of ipdb!<br>&gt; /lib/ipdb_is_awesome.py(11)tracing_the_function()<br>     10     this_variable_hasnt_been_interpreted_yet = \<br>---&gt; 11         &quot;The program froze before it could read me!&quot;<br>     12     print(this_variable_hasnt_been_interpreted_yet)</pre><pre>ipdb&gt;</pre><p>You have frozen your program <em>as it executes</em> and are now inside a REPL <em>inside your program</em>. You basically just stopped time! How cool is that?</p><p>In the terminal, in your ipdb console, type the variable name inside_the_function and hit enter. You should see a return value of &quot;We&#39;re inside the function&quot;.</p><pre>ipdb&gt; inside_the_function<br>&quot;We&#39;re inside the function!&quot;</pre><p>You are able to explore the data <em>inside</em> the function in which you’ve placed your binding. Any variables or functions that are available from the line you placed your ipdb.set_trace() will be available to you to explore from the terminal.</p><blockquote><em>NOTE: Any names that have been assigned to variables (or functions, methods classes, etc.) can be auto-completed by hitting </em><em>tab. If your name doesn&#39;t autocomplete, it hasn&#39;t been defined yet!</em></blockquote><p>Now, in the terminal, in your ipdb console, type the variable name this_variable_hasnt_been_interpreted_yet. You should see a NameError. That&#39;s because the binding you placed on line 7 actually froze the program on line 7 and the variable you just called hasn&#39;t been interpreted yet. Consequently, our REPL doesn&#39;t know about it.</p><p>Now, in the terminal, type c (for <strong>continue</strong>), and you&#39;ll leave your ipdb console and the program will continue to execute.</p><h3>Using ipdb to Debug</h3><p>In addition to <em>exploring</em> code inside ipdb, you can also manipulate variables and try code out. This is where ipdb really becomes helpful for debugging. If you have a function that isn&#39;t doing what it&#39;s supposed to do, instead of making changes in your text editor and running the tests over and over until you get it working, you can put a binding in your code and try things out. Once you&#39;ve figured out how to fix the problem, you then update the code in your text editor accordingly.</p><p>Let’s walk through an example together. In this repository, you’ll see a testing folder containing a file ipdb_debugging_test.py. This is a test for the file lib/ipdb_debugging.py.</p><p>In ipdb_debugging.py, we have a broken function. Run pytest to see the failing test. You should see the following:</p><pre>=== FAILURES ===<br>___ TestIpdbDebugging.test_adds_two ___</pre><pre>self = &lt;testing.ipdb_debugging_test.TestIpdbDebugging object at 0x105862fa0&gt;</pre><pre>    def test_adds_two(self):<br>        &#39;&#39;&#39;adds_two() adds 2 to input arg and returns sum&#39;&#39;&#39;<br>&gt;       assert(plus_two(3) == 5)<br>E       assert 3 == 5<br>E        +  where 3 = plus_two(3)</pre><pre>testing/ipdb_debugging_test.py:10: AssertionError<br>=== short test summary info ===<br>FAILED ipdb_debugging.py adds_two() adds 2 to input arg and returns sum - assert 3 == 5<br>=== 1 failed in 0.04s ===</pre><p>So what’s happening? In our FAILURES section, we can see that the test is calling the plus_two function and passing in 3 as an argument. Below that we can see that the test is expecting 5 to be returned, but that 3 is being returned instead. Let&#39;s take another look at the code in ipdb_debugging.py:</p><pre>def plus_two(num):<br>    num + 2<br>    return num</pre><p>So while our function is adding 2 to num in the first line of our function, it appears that it is not <em>updating</em> num. We have imported ipdb at the top of our testing/ipdb_debugging_test.py file so we can use it to verify this. Let&#39;s place an ipdb.set_trace() in our code, right after that line:</p><pre>def plus_two(num):<br>    num + 2<br>    ipdb.set_trace()<br>    return num</pre><p>Now, run <a href="https://docs.pytest.org/en/latest/how-to/capture-stdout-stderr.html#setting-capturing-methods-or-disabling-capturing">pytest -sLinks to an external site.</a> (the -s allows us to see and interact with our code&#39;s output during testing) and drop into your ipdb console. Your terminal should look like this:</p><pre>ipdb_debugging.py adds_two() adds 2 to input arg and returns sum &gt; /lib/ipdb_debugging.py(8)plus_two()<br>      6     num + 2<br>      7     ipdb.set_trace()<br>----&gt; 8     return num</pre><pre>ipdb&gt;</pre><p>Let’s check our current return value by typing num at the ipdb prompt. You should see something like this:</p><pre>ipdb&gt; num<br>3<br>ipdb&gt;</pre><p>By checking the value of the variable inside our ipdb console, we can confirm that num is still equal to 3 and, as a result, the function is returning 3.</p><p>How can we modify the code so that the function behaves in the expected way? We need to <em>update</em> the value of our num variable so that it&#39;s equal to the sum of itself and 2. Play around inside your ipdb console: try code that you think will update num as needed, then check the value of num to see if it worked. Once you figure it out you can type exit in your terminal to get out of ipdb, update the code in your text editor, and rerun the test to verify it&#39;s passing. Be sure to remove the ipdb.set_trace()!</p><p>It can take a little while to get the hang of using ipdb, so don&#39;t worry if it&#39;s still a little confusing. As you start working with more complex functions and data structures, you&#39;ll find it can be a very helpful tool.</p><p>pytest is primarily used for a task called <strong>unit testing</strong>. Unit testing is a process in which the smallest parts of an application- no matter how large the application- are looked at individually and tested to make sure they operate as intended. Testing is usually carried out by developers themselves, but sometimes by teams of quality assurance (QA) engineers as well.</p><p>Unit tests will typically run on many functions at once with many different types of input. The number of failures with their descriptions will be returned to the tester so that they can update any non-functional code. Tests can be run quickly and as many times as desired. They can also be run on code that doesn’t exist yet- this allows for a process called <strong>test-driven development</strong> (TDD), where failures are used to inform what code to write next.</p><h3>An Example of TDD</h3><p>Let’s say you want to write a function that interpolates into a string: given a name, it should return “Welcome, name!”</p><p>This is fairly simple to write, but even easier to test. Let’s start by writing an assertion that will raise an Exception if the return value of our function is incorrect. Open up the Python shell and enter the following:</p><pre>&gt;&gt;&gt; def interpolate_welcome(name):<br>...     pass<br>...<br>&gt;&gt;&gt; assert interpolate_welcome(&#39;Guido&#39;) == &#39;Welcome, Guido!&#39;</pre><p>You should see the following output:</p><pre># =&gt; Traceback (most recent call last):<br># =&gt;   File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;<br># =&gt; AssertionError</pre><p>This tells us that in the most recent block of code (the assertion), there was an error on the first line. As this is an assertion, the error is easy enough to parse out: interpolate_welcome() doesn&#39;t interpolate the name we pass in!</p><p>Let’s use that assertion to drive the development of some working code:</p><pre>&gt;&gt;&gt; def interpolate_welcome(name):<br>...     return f&#39;Welcome, {name}!&#39;<br>...<br>&gt;&gt;&gt; assert interpolate_welcome(&#39;Guido&#39;) == &#39;Welcome, Guido!&#39;</pre><p>You should see no output from this assertion- that means that it worked!</p><p>Simple assertions are <em>enough</em> for us to do TDD, but they don’t give us many details. We’ll see how pytest improves upon this process in just a bit.</p><h3>Specifying Tests to Run</h3><p>pytest provides a number of different options to specify which tests to run. We can run all tests, all tests in a directory, all tests in a file, all tests in a class, and only specified tests.</p><h4>Running All Tests</h4><p>As we saw before, running all tests just requires us to run pytest from the project root directory. If all tests are in a subdirectory (such as lib/ or testing/ in this repo), we can also run pytest from there.</p><h4>Running All Tests in a Directory</h4><p>An easier way to run all tests in a directory is to specify the directory after the pytest command:</p><pre>$ pytest lib/testing<br>(python-p3-pytest) python-p3-pytest % pytest lib/testing<br>====== test session starts ======<br>...<br>module in bool_functions, function &quot;return_true&quot; returns True. - assert False == True<br>====== 1 failed, 2 passed in 0.05s ======</pre><h4>Running All Tests in a File</h4><p>We can see above that only one test is failing: test_return_true(). This is contained in bool_test.py. We can specify to run the tests in this file with the same syntax as above, noting that bool_test.py is contained in a subdirectory of testing/: pytest lib/testing/subdirectory/bool_test.py.</p><pre>$ pytest lib/testing/subdirectory/bool_test.py<br>====== test session starts ======<br>...<br>====== short test summary info ======<br>FAILED module in bool_functions, function &quot;return_true&quot; returns True. - assert False == True<br>====== 1 failed in 0.04s ======</pre><h4>Running One Test in a File</h4><p>Getting bored of the same syntax? Good news! Navigating the contents of a file has nothing to do with Unix directory structure, so we won’t be adding any more forward slashes /.</p><p>pytest uses a double colon :: to navigate from the file itself down to classes and functions. Since we don&#39;t have any classes in our tests, we can run pytest lib/testing/bool_test.py::test_return_true to look into this error specifically.</p><pre>$ pytest lib/testing/subdirectory/bool_test.py::test_return_true<br>====== test session starts ======<br>...<br>====== short test summary info ======<br>FAILED module in bool_functions, function &quot;return_true&quot; returns True. - assert False == True<br>====== 1 failed in 0.04s ======</pre><p>Now that we can run the tests that we want, let’s start parsing useful information out of the results.</p><h3>Interpreting pytest Output</h3><p>Let’s go back and look at the <em>full</em> output from the pytest command:</p><pre>====== test session starts ======<br>platform darwin -- Python 3.8.13, pytest-7.2.1, pluggy-1.0.0<br>rootdir: python-p3-pytest, configfile: pytest.ini<br>collected 3 items</pre><pre>string_functions.py contains a function &quot;return_string()&quot; that returns a variable of type str. .                                 [ 33%]<br>string_functions.py contains a function &quot;interpolate_string()&quot; that takes a string and inserts it into another string. .         [ 66%]<br>string_functions.py contains a function &quot;return_true&quot; that returns True. F                                                       [100%]</pre><pre>====== FAILURES ======<br>______ test_return_true ______</pre><pre>    def test_return_true():<br>        &#39;&#39;&#39;in bool_functions, function &quot;return_true&quot; returns True.&#39;&#39;&#39;<br>&gt;       assert return_true() == True<br>E       assert False == True<br>E        +  where False = return_true()</pre><pre>lib/testing/subdirectory/bool_test.py:7: AssertionError</pre><pre>====== short test summary info ======<br>FAILED string_functions.py contains a function &quot;return_true&quot; that returns True. - assert False == True<br>====== 1 failed, 2 passed in 0.05s ======</pre><p>There’s a lot to look through here- let’s go line by line.</p><pre>====== test session starts ======<br>platform darwin -- Python 3.8.13, pytest-7.2.1, pluggy-1.0.0<br>rootdir: python-p3-pytest, configfile: pytest.ini<br>collected 3 items</pre><p>We begin with a message that the test session has started, with some equals signs = building a border. This is to help you find the test results if you need to scroll back at any point. The next two lines simply describe your configuration for your system and pytest- the Python version, the pytest version, the root directory, configuration file, and so on. &quot;collected 3 items&quot; tells us that pytest has found three tests.</p><pre>string_functions.py contains a function &quot;return_string()&quot; that returns a variable of type str. .                                 [ 33%]<br>string_functions.py contains a function &quot;interpolate_string()&quot; that takes a string and inserts it into another string. .         [ 66%]<br>string_functions.py contains a function &quot;return_true&quot; that returns True. F                                                       [100%]</pre><p>Next, pytest shows us the progress of testing and whether each test passed or failed. . after the test description denotes a pass, F denotes a failure. The percentages in brackets inform us of how far we have progressed in testing- this can be useful if certain functions in your application take a long time to run.</p><pre>====== FAILURES ======<br>______ test_return_true ______</pre><pre>    def test_return_true():<br>        &#39;&#39;&#39;in bool_functions, function &quot;return_true&quot; returns True.&#39;&#39;&#39;<br>&gt;       assert return_true() == True<br>E       assert False == True<br>E        +  where False = return_true()</pre><pre>lib/testing/subdirectory/bool_test.py:7: AssertionError</pre><p>After looking at an overview of the tests, we dig deeper into the failures. pytest begins with the name of the test that failed, then shows the code from which the error arose. Along the left, look for an arrow (greater than) symbol &gt;. This shows the specific line of code that produced an error when interpreted.</p><p>Underneath the line of code that produced the error, we see lines that begin with an “E”. The first “E” line will show the values of the interpreted line of code- here, we can see that False is being asserted to equal True. Naturally, this is cause for an error. The next line will show us where this erroneous value came from- False is the return value of return_true(). Finally, pytest provides the path to the line of the error from the location the test was run. lib/testing/subdirectory/bool_test.py on line 7 produced an AssertionError.</p><pre>====== short test summary info ======<br>FAILED string_functions.py contains a function &quot;return_true&quot; that returns True. - assert False == True<br>====== 1 failed, 2 passed in 0.05s ======</pre><p>At the end of every testing session, pytest provides an overview of the important takeaways for developers and QA engineers. Inside of this summary, the description of the test is included alongside a note that it failed and the interpreted code that caused the failure. We then get the number of failures, number of passed tests, and the amount of time it took to run all tests.</p><blockquote><strong><em>Note: While we won’t be looking at the times during our tests, these are going to be important to pay attention to when building larger applications. Slower applications mean fewer users- you don’t want that!</em></strong></blockquote><h3>Customizing pytest Output</h3><p>pytest has <em>many</em> flags, but we’re just going to focus on the few that will be most helpful to you.</p><ul><li>-x is pytest&#39;s &quot;exit&quot; flag. This executes tests until one fails, then stops executing tests. This is very helpful for test-driven development, as you&#39;ll want to focus on developing to one test at a time.</li><li>--pdb opens the Python debugger when a test fails. It does not open the prettier, improved ipdb, but its basic functions are very similar.</li><li>-s tells pytest to show the full output for failed tests (i.e. print() statements).</li><li>-q (for quiet) shortens pytest&#39;s output. Running with the -q flag will only show a single line for the summary of the testing session and details of the failures.</li><li>-h will help you figure out where to place arguments for the pytest command <em>and</em> provide a long list of flags and configurations for use with pytest.</li></ul><h3>Indentation in Python</h3><ul><li><strong>Code Block</strong>: a collection of code that is interpreted together. Python groups code blocks by indentation level.</li></ul><p>Indentation is a central concept of Python programming. New lines with indentations are required after certain statements. Without proper indentation, your code will be interrupted by an IndentationError.</p><h3>Where Are Indentations Necessary?</h3><p>Indentations are required on each new line inside of a code block. Code blocks can begin with a number of keywords or statements, but here are some of the most common:</p><ul><li>class Definitions</li><li>Function and Method Definitions (following the keyword def)</li><li>if, elif, and else</li><li>try, except, and finally</li><li>for and while</li></ul><h3>Spaces, not Tabs</h3><h3>Four Spaces Each Time</h3><p>Every indentation in Python code should consist of four spaces. This is long enough to distinguish between indentation levels but short enough to provide space for indentation levels in several nested code blocks.</p><h3>Indent Statements that Continue past One Line</h3><p>Some functions and methods take a lot of arguments. <strong><em>A lot</em></strong> of arguments. Take this one, for instance:</p><pre>def take_twenty_arguments(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20):<br>    &#39;&#39;&#39;Takes 20 arguments and does nothing.&#39;&#39;&#39;<br>    pass</pre><p>Our function definition here takes up <em>158 characters</em>. PEP 8 says that lines should be composed of 79 or fewer characters, so we’re way off here.</p><p>Python supports <em>implicit line joining</em> inside of parentheses and brackets, which means that we can add a new line anywhere in our list of arguments as long as it does not interrupt the name of an argument. Let’s break this function definition down a bit more:</p><pre>def take_twenty_arguments(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8,<br>    arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18,<br>    arg19, arg20):<br>    &#39;&#39;&#39;Takes 20 arguments and does nothing.&#39;&#39;&#39;<br>    pass</pre><p>This is much cleaner, but the casual reader might have some trouble telling where the arguments end and the code block begins. PEP 8 provides us two solid options for avoiding this ambiguity:</p><pre># Aligning arguments with the opening delimiter<br>def take_twenty_arguments(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8,<br>                          arg9, arg10, arg11, arg12, arg13, arg14, arg15,<br>                          arg16, arg17, arg18, arg19, arg20):<br>    &#39;&#39;&#39;Takes 20 arguments and does nothing.&#39;&#39;&#39;<br>    pass</pre><pre># OR</pre><pre># Hanging four-space indents with an added level<br>def take_twenty_arguments(<br>        arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11,<br>        arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20):<br>    &#39;&#39;&#39;Takes 20 arguments and does nothing.&#39;&#39;&#39;<br>    pass</pre><p>These options are not restricted to statements that extend past 79 characters; you should take the extra effort to write readable code using the PEP 8 style guide whenever possible.</p><pre># Creating a dict<br>my_dict = {<br>    &quot;word_1&quot;: &quot;definition 1&quot;,<br>    &quot;word_2&quot;: &quot;definition 2&quot;,<br>}</pre><pre># Creating a list<br>my_list = [<br>    &quot;item_1&quot;,<br>    &quot;item_2&quot;,<br>]</pre><h3><a href="https://peps.python.org/pep-0008/#a-foolish-consistency-is-the-hobgoblin-of-little-minds">A Foolish Consistency is the Hobgoblin of Little MindsLinks to an external site.</a></h3><p><a href="https://peps.python.org/pep-0008/">Python Enhancement Proposal 8 (<strong>PEP 8</strong>, for short)Links to an external site.</a> gives writing conventions for Python programmers. One of Guido van Rossum’s key observations that he kept in mind while developing Python was that <em>code is read much more often than it is written</em>. This means that readers need to be able to understand your code, so we need to adhere to certain standards while coding.</p><h3>Control Flow: Operators</h3><h3>Learning Goals</h3><ul><li>Use common comparison functions for control flow (==, !=, &gt;, &lt;).</li><li>Use common logical operators for control flow (and, or, not).</li></ul><h3>Comparison Operators</h3><p>In Python, many built-in classes have the following functions that can be used to compare two values:</p><ul><li>&gt;: greater than</li><li>&gt;=: greater than or equal to</li><li>&lt;: less than</li><li>&lt;=: less than or equal to</li><li>==: equal to</li><li>!=: not equal to</li></ul><h3>Logical Operators</h3><p>Python has the same logical operators you’ll find in many other languages, including JavaScript:</p><ul><li>and: <strong>and</strong>. Returns True if both statements are true.</li><li>or: <strong>or</strong>. Returns True if one of the two statements is true.</li><li>not: <strong>not</strong>. Coerces the data to its boolean equivalent, then reverses it (True becomes False, and vice versa).</li></ul><pre>True and True<br># True<br>False and False<br># False<br>False and True<br># False<br>True or True<br># True<br>False or False<br># False<br>False or True<br># True<br>not True<br># False<br>not not True<br># True</pre><h3>Control Flow: Conditional Statements</h3><h3>Learning Goals</h3><ul><li>Conditionally execute code with if/else statements.</li><li>Handle exceptions using try/except statements.</li><li>Use dictionary mapping to handle switch/case logic.</li></ul><h3>Conditional Expressions</h3><p>Python also allows us to use <strong>conditional expressions</strong> (or <strong>ternary operators</strong>) to evaluate the truthiness of complex statements in a single line.</p><pre>age = 1</pre><pre>is_baby = &#39;baby&#39; if age &lt; 2 else &#39;not a baby&#39;</pre><p>This is the equivalent of the following if/else statement:</p><pre>age = 1<br>if age &lt; 2:<br>  is_baby = &#39;baby&#39;<br>else:<br>  is_baby = &#39;not a baby&#39;</pre><p>Conditional expressions in Python are always of the format:</p><pre>value_if_true if condition else value_if_false</pre><p>Python requires a default value (preceded by the else keyword) in every conditional statement. It may seem like a pain at first, but it helps to prevent unexpected exceptions and Nones as you continue to build your application.</p><h3>try/except Statements</h3><p>Throughout our Python assignments so far, we have seen a number of different <strong>Exceptions</strong>. As we learned in our “Error Messages” lesson, Exceptions are a type of error that we can intercept so that our Python application can continue to run. try/except statements are the tool that allow us to perform these interceptions.</p><p>Let’s take a look at how we might handle a common mathematical exception. Copy the following code into the Python shell and try to run the divide() function with different arguments.</p><pre>def divide(num1, num2):<br>    try:<br>        quotient = num1 / num2<br>        print(quotient)<br>    except:<br>        print(&quot;An error occurred&quot;)</pre><p>Did you find any arguments that gave you trouble? The divide() function will fail to perform its primary task if num2 is 0 or either of the numbers is of a non-numerical type. Our try/except statement allowed our function to run to completion, but &quot;An error occurred&quot; is not a particularly helpful message.</p><p>Since we know the types of exceptions we might see, let’s rewrite our code to be a little more descriptive:</p><pre>def divide(num1, num2):<br>    try:<br>        quotient = num1 / num2<br>        print(quotient)<br>    except ZeroDivisionError:<br>        print(&quot;Error: num2 cannot be equal to 0&quot;)<br>    except TypeError:<br>        print(&quot;Error: input must be of type int or float&quot;)</pre><p>That’s looking much more descriptive now!</p><p>Finally, let’s take a look at finally. Copy and paste the following code into the Python shell and test divide() with a variety of different arguments:</p><pre>def divide(num1, num2):<br>    try:<br>        quotient = num1 / num2<br>        print(quotient)<br>    except ZeroDivisionError:<br>        print(&quot;Error: num2 cannot be equal to 0&quot;)<br>    except TypeError:<br>        print(&quot;Error: input must be of type int or float&quot;)<br>    finally:<br>        print(&quot;Isn&#39;t division fun?&quot;)</pre><p>Use of the finally keyword at the end of a try/except statement allows us to perform actions that we want to occur regardless of whether or not an exception has been thrown.</p><blockquote><em>NOTE: You might see some unhandled exceptions if you provide </em><em>divide() too many arguments or names that have not been defined. Since these technically occur before </em><em>divide() starts working, they cannot be handled with a </em><em>try/except statement inside of </em><em>divide().</em></blockquote><h3>Dictionary Mapping</h3><p>Unlike JavaScript, Python does not have switch/case statements. Python can handle switch/case logic in if/else statements, but for very long sets of conditions, it may be worthwhile to use <strong>dictionary mapping</strong> instead.</p><blockquote><em>NOTE: Python 3.10 has introduced </em><em>match/case statements which function very similarly to </em><em>switch/case statements in JavaScript. Though we are using an earlier version of Python in our curriculum, you can explore this new feature in the </em><a href="https://docs.python.org/3/whatsnew/3.10.html#pep-634-structural-pattern-matching"><em>Python 3.10 documentation.Links to an external site.</em></a></blockquote><p>Read through the following JavaScript code:</p><pre>// JavaScript<br>let dog = &quot;cuddly&quot;;<br>let owner;</pre><pre>switch (dog) {<br>  case &quot;hungry&quot;:<br>    owner = &quot;Refilling food bowl.&quot;;<br>    break;<br>  case &quot;thirsty&quot;:<br>    owner = &quot;Refilling water bowl.&quot;;<br>    break;<br>  case &quot;playful&quot;:<br>    owner = &quot;Playing tug-of-war.&quot;;<br>    break;<br>  case &quot;cuddly&quot;:<br>    owner = &quot;Snuggling.&quot;;<br>    break;<br>  default:<br>    owner = &quot;Reading newspaper.&quot;;<br>    break;<br>}</pre><p>This switch/case statement takes the status of the dog as a string and sets the state of the owner accordingly.</p><p>Let’s take a look at how we might do that with an if/elif/else statement in Python:</p><pre># Python<br>dog = &quot;cuddly&quot;</pre><pre>if dog == &quot;hungry&quot;:<br>    owner = &quot;Refilling food bowl.&quot;<br>elif dog == &quot;thirsty&quot;:<br>    owner = &quot;Refilling water bowl.&quot;<br>elif dog == &quot;playful&quot;:<br>    owner = &quot;Playing tug-of-war.&quot;<br>elif dog == &quot;cuddly&quot;:<br>    owner = &quot;Snuggling.&quot;<br>else:<br>    owner = &quot;Reading newspaper.&quot;</pre><p>As you can see, there is some repeated code in dog ==, but the code is still more concise than with a true switch/case statement in JavaScript.</p><p>Now let’s look at how we would handle this with dictionary mapping. Copy and paste the following code into the Python shell:</p><pre>dog = &quot;cuddly&quot;</pre><pre>dict_map = {<br>    &quot;hungry&quot;: &quot;Refilling food bowl.&quot;,<br>    &quot;thirsty&quot;: &quot;Refilling water bowl.&quot;,<br>    &quot;playful&quot;: &quot;Playing tug-of-war.&quot;,<br>    &quot;cuddly&quot;: &quot;Snuggling.&quot;,<br>}</pre><pre># Remember that a dictionary&#39;s .get() method lets us set a default value!<br>owner = dict_map.get(dog, &quot;Reading newspaper.&quot;)</pre><p>This approach is <em>very</em> concise, but the mapping dictionary itself is not so intuitive to read; as we can see, the keys describe the state of the dog while the values describe the state of the owner. Dictionary mapping is a valuable tool for long lists of conditions, but if/elif/else statements are typically the preferred method for handling switch/case logic in Python.</p><h3>Control Flow: Loops</h3><ul><li>Write basic loops with the for and while constructs.</li></ul><h3>List Comprehensions</h3><pre>player_heights = [0.008, 0.008, 0.008, 0.009, 0.008, 0.01, 0.009, 0.009, 0.01, 0.008, 0.009, 0.009, 0.008, 0.008, 0.008, 0.009, 0.008, 0.009, 0.01, 0.01]</pre><p>We could certainly write a for loop to handle this:</p><pre>inch_heights = list()<br>for height in player_heights:<br>    inch_height = height * 7920<br>    inch_heights.append(inch_height)</pre><p>...but now we&#39;ve written four lines of code when we only want to do a simple conversion.</p><p>List comprehensions allow us to transform sequences of data in a single line. Here&#39;s how we would accomplish the above task with a list comprehension:</p><pre>inch_heights = [height * 7920 for height in player_heights]</pre><p>That&#39;s it! Another benefit of list comprehensions is that you can easily reuse the name of your original sequence without worrying about conflicting names:</p><pre>player_heights = [height * 7920 for height in player_heights]</pre><p>Now it&#39;s almost like your mistake never happened at all.</p><pre>&gt; print(player_heights)<br># [63.36, 63.36, 63.36, 71.28, 63.36, 79.2, 71.28, 71.28, 79.2, 63.36, 71.28, 71.28, 63.36, 63.36, 63.36, 71.28, 63.36, 71.28, 79.2, 79.2]</pre><p>List comprehensions are a very powerful tool, but there are jobs that a for loop is better suited for. There are two main factors to keep in mind when choosing between the two:</p><ol><li>List comprehensions should only be used for loops where the output is an iterable object such as a list or set.</li><li>for loops separate steps into different lines, which is how human eyes expect to see instructions. List comprehensions are restricted to a single line and can be difficult for other humans to understand.</li></ol><h3>Decorators</h3><h3>Key Vocab</h3><ul><li><strong>Decorator</strong>: syntax that allows us to add functionality to an object without modifying its structure.</li></ul><h3>Functions Are First Class Objects they are objects too</h3><h3>Introduction</h3><p>Functions are reusable pieces of code that are called with a single expression. A function can be designed to accept arguments and return values, further increasing code reuse by adapting a computation based on actual values passed to arguments when a function is called.</p><p>A function follows an important software engineering principle of <strong>D</strong>on’t <strong>R</strong>epeat <strong>Y</strong>ourself. DRY is the principle of reducing repetition in our code by referencing a <strong>single source</strong> of reusable code whenever we need it.</p><p><strong>Decorators</strong> provide us yet another way to write DRY code through providing extra functionality to functions beyond arguments.</p><h3>Functions Are First Class Objects</h3><p>While we primarily think of functions as procedures, it’s important to remember that in Python, they are objects too. Just like any other object, they can be saved as variables, passed as arguments to other functions, and returned by functions:</p><pre>def hello(name):<br>    return &quot;Hello &quot; + name</pre><pre>print(hello(&quot;Guido&quot;))<br># Hello Guido</pre><pre>greeting = hello<br>print(greeting(&quot;Guido&quot;))<br># Hello Guido</pre><pre>def salutation(func):<br>    return func(&quot;Guido&quot;)</pre><pre>print(salutation(greeting))<br># Hello Guido.</pre><p>Furthermore, we can define functions inside of other functions, just as we could any other object. We call these <strong>inner functions</strong>:</p><pre>def hello(name):<br>    print(&quot;Hello from the hello() function.&quot;)</pre><pre>    def greet():<br>        print(&quot;Greetings from the greet() function.&quot;)</pre><pre>    return greet</pre><p>What do you think we’ll see if we print() the result of our hello() function?</p><pre>hello(&quot;Guido&quot;)<br># Hello from the hello() function.<br># &lt;function hello.&lt;locals&gt;.greet at 0x103287b80&gt;</pre><p>By returning greet() without parentheses, hello() is returning the function itself so that we can use it later on. When we&#39;re ready to invoke it later on, we can do so with parentheses as we would with any other function:</p><pre>hello(&quot;Guido&quot;)()<br># Hello from the hello() function.<br># Greetings from the greet() function.</pre><p>What would be the output of the code above if return greet were left out?</p><h3>Writing Your First Decorator</h3><p>To write your first <strong>decorator</strong>, you’ll need to tie all of these concepts together. You will need to write a function that…</p><ol><li>Takes a function as an argument.</li><li>Has an inner function defined inside of it.</li><li>Returns the inner function.</li></ol><p>Open up the Python shell and enter the following code:</p><pre>def decorator(func):<br>    def wrapper():<br>        print(&quot;I am the output that lets you know the function is about to be called.&quot;)<br>        func()<br>        print(&quot;I am the output that lets you know the function has been called.&quot;)<br>    return wrapper</pre><pre>def get_called():<br>    print(&quot;I am the function and I am being called.&quot;)</pre><p>We’ve created a decorator and we’ve created a function to pass in. All that’s left to do is put it all together:</p><pre>get_called = decorator(get_called)<br>get_called()<br># I am the output that lets you know the function is about to be called.<br># I am the function and I am being called.<br># I am the output that lets you know the function has been called.</pre><p>Python allows us to perform the decoration step in a more decorative fashion with the @ symbol. This is also called <em>&quot;pie syntax&quot;</em>.</p><pre>@decorator<br>def get_called():<br>    print(&quot;I am the function and I am being called.&quot;)</pre><pre>get_called()<br># I am the output that lets you know the function is about to be called.<br># I am the function and I am being called.<br># I am the output that lets you know the function has been called.</pre><h3>When To Use Decorators</h3><p>The primary function of decorators is reducing the amount of code that you need to write in your applications. If you find yourself reusing a lot of the same code in different functions, that’s a great opportunity to use decorators. If you’re only doing something once or twice, decorators might be overkill.</p><p>Let’s look at an example of when we <em>would</em> want to use decorators.</p><pre>def sweep_floors(time):<br>    if 1100 &lt; time &lt; 2100:<br>        print(&quot;Sweeping the floors...&quot;)<br>    else:<br>        print(&quot;I&#39;m off duty!&quot;)</pre><pre>def wash_dishes(time):<br>    if 1100 &lt; time &lt; 2100:<br>        print(&quot;Washing the dishes...&quot;)<br>    else:<br>        print(&quot;I&#39;m off duty!&quot;)</pre><pre>def chop_vegetables(time):<br>    if 1100 &lt; time &lt; 2100:<br>        print(&quot;Chopping the vegetables...&quot;)<br>    else:<br>        print(&quot;I&#39;m off duty!&quot;)</pre><p>There’s a pretty clear pattern here: our employees only work from 11 to 9! Including code in every single function to check if anyone’s working is not ideal. Let’s refactor this with a decorator:</p><pre>def check_working_hours(func):<br>    def wrapper(time):<br>        if 1100 &lt; time &lt; 2100:<br>            func(time)<br>        else:<br>            print(&quot;I&#39;m off duty!&quot;)<br>    return wrapper</pre><pre>@check_working_hours<br>def sweep_floors(time):<br>    print(&quot;Sweeping the floors...&quot;)</pre><pre>@check_working_hours<br>def wash_dishes(time):<br>    print(&quot;Washing the dishes...&quot;)</pre><pre>@check_working_hours<br>def chop_vegetables(time):<br>    print(&quot;Chopping the vegetables...&quot;)</pre><pre>sweep_floors(800)<br># I&#39;m off duty!<br>wash_dishes(1000)<br># I&#39;m off duty!<br>chop_vegetables(1200)<br># Chopping the vegetables...</pre><h3>Conclusion</h3><p>Functions are first-class objects in Python. This means that they can be passed as arguments to other functions, created inside of other functions (as <em>inner functions</em>), and returned by other functions. Decorators leverage these features to allow us to avoid repetitive code and are an important tool in any Python programmer’s toolbox.</p><h3>Intro to Data Structures</h3><h3>Key Vocab</h3><ul><li><strong>Sequence</strong>: a data structure in which data is stored and accessed in a specific order.</li><li><strong>Index</strong>: the location, represented by an integer, of an element in a sequence.</li><li><strong>Iterable</strong>: able to be broken down into smaller parts of equal size that can be processed in turn. You can loop through any iterable object.</li><li><strong>Slice</strong>: a group of neighboring elements in a sequence.</li><li><strong>Mutable</strong>: an object that can be changed.</li><li><strong>Immutable</strong>: an object that cannot be changed. (<em>Many immutable objects appear mutable because programmers reuse their names for new objects</em>.)</li><li><strong>List</strong>: a mutable data type in Python that can store many types of data. The most common data structure in Python.</li><li><strong>Tuple</strong>: an immutable data type in Python that can store many types of data.</li><li><strong>Range</strong>: a data type in Python that stores integers in a fixed pattern.</li><li><strong>String</strong>: an immutable data type in Python that stores unicode characters in a fixed pattern. Iterable and indexed, just like other sequences.</li></ul><h3>Why Don’t We Just Put Everything in a List?</h3><p>list objects are very useful for storing data in Python, but there are many situations where a computer would want data stored in a different way.</p><p>To provide some perspective, let’s compare a list with a set:</p><p>listset</p><p>There are a number of similarities here, and it’s clear that list objects are much more flexible than set objects. But if we&#39;re looking for <em>which</em> items exist rather than <em>how many</em>, a data structure with unique items that allows us to access them by <em>name</em> rather than <em>index</em> is more useful. Lucky for us, Python provides the set data structure out of the box!</p><h3>Types of Data Structures in Python</h3><p>Python gives us access to a number of different data structures to help us communicate with our computers. Some are built-in <strong>data types</strong> while others require a little more work to set up.</p><h3>Data Types that are Data Structures</h3><ul><li>Sequences:</li><li>list</li><li>tuple</li><li>str</li><li>Sets:</li><li>set</li><li><a href="https://docs.python.org/3/library/stdtypes.html#frozenset"><em>frozenset</em>*Links to an external site.</a></li><li>Maps:</li><li>dict (the only map type in Python!)</li></ul><p>* <em>We won’t be covering these in our curriculum, but they may be useful to you in advanced computing contexts</em></p><h3>Trees and Linked Lists</h3><p>Python does not come with <em>every</em> data structure built into its data types, but the standard library includes several modules and packages that help us build out more complex data structures. Trees and linked lists are two of the most common.</p><h3>When Are Sequences Used?</h3><p>Whenever values are logically connected to one another and it is important to keep them in order, you should store them in a sequence data structure.</p><pre># A dynamic sequence of values that allows duplicates<br>fibonacci_list = [0, 1, 1, 2, 3, 5, 8, 13, 21]</pre><pre># An immutable, ordered sequence of months<br>month_tuple = (<br>    &#39;January&#39;,<br>    &#39;February&#39;,<br>    &#39;March&#39;,<br>    &#39;April&#39;,<br>    &#39;May&#39;,<br>    &#39;June&#39;,<br>    &#39;July&#39;,<br>    &#39;August&#39;,<br>    &#39;September&#39;,<br>    &#39;October&#39;,<br>    &#39;November&#39;,<br>    &#39;December&#39;,<br>)</pre><pre># A simple pattern of numbers<br>even_numbers_up_to_100 = range(0, 101, 2)</pre><pre># A grammatical sentence<br>sentence_string = &quot;Strings are immutable sequences of Unicode code points.&quot;</pre><p>After being defined, sequences can be used as more complex data structures such as <em>queues</em> and <em>stacks</em>.</p><h3><a href="https://docs.python.org/3/library/stdtypes.html#common-sequence-operations">Common Sequence OperationsLinks to an external site.</a></h3><p>All sequence data types in Python support certain functions and operators and possess certain methods. For a sequence s:</p><ul><li>x in s returns True if x is equal to at least one element of s.</li><li>s + s2 returns a single sequence of the elements of s followed by the elements of s2.</li><li>s * n returns a single sequence of s repeated n times.</li><li>s[i]returns the ith element of s (starting at 0).</li></ul><blockquote><em>NOTE: Python also supports negative indices. </em><em>-1 represents the last element in a sequence.</em></blockquote><ul><li>s[i:j] returns a <em>slice</em> of s from index i up to (but not including!) index j.</li><li>s[i:j:k] returns a slice of s from i to j with steps of k in between.</li><li>len(s) returns the number of elements in s.</li><li>min(s) and max(s) return the minimum and maximum values in s, respectively. &gt; NOTE: this requires the elements of s to be of the same data type, either str or numerical.</li><li>s.index(x) returns the index of the first x in s.</li><li>s.count(x) returns the number of instances of x in s.</li></ul><p>Open up the Python shell and test each of these operations for yourself:</p><pre>s = [4, 6, 3, 9, 3, 5, 1, 2]<br>1 in s<br># =&gt; True<br>s + s<br># =&gt; [4, 6, 3, 9, 3, 5, 1, 2, 4, 6, 3, 9, 3, 5, 1, 2]<br>s * 2<br># =&gt; [4, 6, 3, 9, 3, 5, 1, 2, 4, 6, 3, 9, 3, 5, 1, 2]<br>s[1]<br># =&gt; 6<br>s[-1]<br># =&gt; 2<br>s[2:5]<br># =&gt; [3, 9, 3]<br>s[2:5:2]<br># =&gt; [3, 3]<br>len(s)<br># =&gt;  8<br>min(s)<br># =&gt; 1<br>max(s)<br># =&gt; 9<br>s.index(3)<br># =&gt; 2<br>s.count(9)<br># =&gt; 1</pre><h3>Lists</h3><p>We’ve encountered lists in several of our lessons so far. As lists are mutable and can store any types of data in the same list object, they have many use cases and many operations, functions, and methods that allow us to manipulate their contents.</p><h3>Sorting Lists</h3><p>Python provides two straightforward solutions for sorting lists: the list.sort() method and the sorted() function. Both of these solutions require that all elements of the list be of the same data type.</p><h4>list.sort() rearranges the elements of a list so that they are in order</h4><pre># if we sort numbers, they will be sorted in ascending order<br>my_list = [3, 6, 4, 2, 1, 5]<br>my_list.sort()<br>print(my_list)<br># [1, 2, 3, 4, 5, 6]</pre><pre># If we sort strings, they will be sorted in alphanumeric order<br>my_list = [&#39;Cabbage&#39;, &#39;Apple&#39;, &#39;Banana&#39;, &#39;Potato&#39;]<br>my_list.sort()<br>print(my_list)<br>#[&#39;Apple&#39;, &#39;Banana&#39;, &#39;Cabbage&#39;, &#39;Potato&#39;]</pre><p>There are some parameters we can pass into list.sort() which can make the the function more versatile.</p><p>The key parameter allows us to pass in a function which can serve as a key for the sort comparison:</p><pre>my_list = [&#39;This is a long sentence&#39;, &#39;Word&#39;, &#39;z&#39;]</pre><pre># What if we want to sort by the length of the string?<br># We can use the key attribute to tell the sort function to sort using the len function.</pre><pre>my_list.sort(key = len)<br>print(my_list)<br># =&gt; [&#39;z&#39;, &#39;Word&#39;, &#39;This is a long sentence&#39;]</pre><pre># If we want to sort in descending order we can pass in the reverse parameter into sort.<br>my_list = [&#39;This is a long sentence&#39;, &#39;Word&#39;, &#39;z&#39;]<br>my_list.sort(key = len, reverse=True)<br>print(my_list)<br># =&gt; [&#39;This is a long sentence&#39;, &#39;Word&#39;, &#39;z&#39;]</pre><p>We can sort complex data structures using sort key</p><p>Lets say we have a list of tuples we want to sort using the second key:</p><pre>my_list = [(&#39;John&#39;, 2), (&#39;Steve&#39;, 1), (&#39;Joe&#39;, 3)]</pre><pre># We can define a function for the list to sort by the second key</pre><pre>def sort_tuple(tuple_value):</pre><pre>    # return the key we want to sort by<br>    return tuple_value[1]</pre><pre>my_list.sort(key = sort_tuple)<br>print(my_list)<br># =&gt; [(&#39;Steve&#39;, 1), (&#39;John&#39;, 2), (&#39;Joe&#39;, 3)]</pre><h4>The sorted() function returns a sorted copy of the original list</h4><p>This function should be used when you want to preserve the integrity of your original list, but you need a sorted version for a separate task.</p><pre>my_list = [3, 6, 4, 2, 1, 5]<br>sorted_list = sorted(my_list)<br>print(my_list)<br># =&gt; [3, 6, 4, 2, 1, 5]<br>print(sorted_list)<br># =&gt; [1, 2, 3, 4, 5, 6]</pre><p>We can pass the key and reverse parameters into sorted() like we did for the sort method:</p><pre>my_list = [&#39;Loquacious&#39;, &#39;Chatty&#39;, &#39;Talkative&#39;]<br>sorted_list = sorted(my_list, key=len, reverse=True)<br># =&gt; [&#39;Loquacious&#39;, &#39;Talkative&#39;, &#39;Chatty&#39;]</pre><h3>Adding to Lists</h3><p>Python allows us to modify any of the elements of a list using their index:</p><pre>my_list = [0, 1, 2, 3]<br>my_list[0] = None<br>print(my_list)<br># =&gt; [None, 1, 2, 3]</pre><p>If we want to extend a list, we unfortunately cannot use the same approach:</p><pre>my_list = [0, 1, 2, 3]<br>my_list[4] = 4<br># =&gt; IndexError: list assignment index out of range</pre><p>Python does provide us with two options to extend lists: list.append() and list.insert().</p><p>list.append() does exactly what you might expect: it <em>appends</em> its parameter to the list.</p><pre>my_list = [0, 1, 2, 3]<br>my_list.append(4)<br>print(my_list)<br># =&gt; [0, 1, 2, 3, 4]</pre><p>list.insert() provides us a few extra options for extending our list. Where list.append() can only add to the end of a list, list.insert() can insert at any index.</p><p>list.insert() takes two arguments: an index and a value. If a value already exists at the index, the new value is inserted before it and everything after is moved up by 1. If no value exists at the index, the new value is added to the end of the existing list.</p><pre>my_list = [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;f&#39;]<br>my_list.insert(4, &#39;e&#39;)<br>print(my_list)<br># =&gt; [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;, &#39;f&#39;]<br>my_list.insert(1000, &#39;g&#39;)<br>print(my_list)<br># =&gt; [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;, &#39;f&#39;, &#39;g&#39;]</pre><p><em>Which method allows you to insert characters into the middle of a list?</em></p><h3>Removing from Lists</h3><p>Python provides us with four (4!!!) options for removing elements from a list.</p><ul><li>The del() function.</li><li>The list.pop() method.</li><li>The list.remove() method.</li><li>The list.clear() method.</li></ul><p>del() removes elements from a list, specified by an index or range of indices.</p><pre>my_list = [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;, &#39;f&#39;, &#39;g&#39;]<br>del(my_list[0])<br>print(my_list)<br># =&gt; [&#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;, &#39;f&#39;, &#39;g&#39;]<br>del(my_list[0:3])<br>print(my_list)<br># =&gt; [&#39;e&#39;, &#39;f&#39;, &#39;g&#39;]</pre><p>list.pop() removes and returns the element at the index passed in as an argument. When used without any arguments, it removes and returns the last element of the list.</p><p>list.remove() removes the element passed in as an argument. This is one of the few list methods that searches by value instead of index!</p><p>list.clear() erases all of the values of a list. This is usually not a very useful tool, but it&#39;s a fast way to free up memory on your device if you&#39;re working with a particularly large list in the Python shell.</p><pre>my_list = [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;, &#39;f&#39;, &#39;g&#39;]<br>my_list.pop()<br># =&gt; &#39;g&#39;<br>my_list.pop(0)<br># =&gt; &#39;a&#39;<br>my_list.remove(&#39;f&#39;)<br>print(my_list)<br># =&gt; [&#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;]<br>my_list.clear()<br>print(my_list)<br># =&gt; []</pre><h3>Tuples</h3><p>Tuples do not have any special exclusive methods like lists do. This is because tuples are <em>immutable</em>. The sequence that they are provided when they are created is maintained as long as the tuple object exists.</p><h3>Ranges</h3><p>Ranges are a very simple type of sequence that is most commonly used in for loops. Ranges can only contain integers in a fixed pattern. You can build a range using the range() constructor method and loop through it as if it were a standard list.</p><p>The range constructor only requires one argument: the end of the range. You may have noticed above that this top value is <strong>not</strong> included in the range itself. This is similar to how slicing works in lists.</p><pre>for n in range(4):<br>    print(n)</pre><pre># =&gt; 0<br># =&gt; 1<br># =&gt; 2<br># =&gt; 3</pre><p>There are two optional arguments that you can include when creating a range: a start value and a step size.</p><ul><li>range(4) gives us 0, 1, 2, 3</li><li>range(1, 4) gives us 1, 2, 3</li><li>range(0, 4, 2) gives us 0, 2</li></ul><p>While ranges are very similar to lists, a range is a different data type and they exhibit some unique behaviors.</p><p>For instance, when we print() a list, we can see its contents:</p><pre>my_list = [0, 1, 2, 3]<br>print(my_list)<br># =&gt; [0, 1, 2, 3]</pre><p>When we print a range containing the same elements, here’s what we see:</p><pre>my_range = range(4)<br>print(my_range)<br># =&gt; range(0, 4)</pre><p><em>What would </em><em>range(2, 10, 2) produce?</em></p><h3>Strings</h3><p>Python strings have <em>many</em> methods that allow you to access and manipulate their individual elements. It’s very important to remember while working with strings that they are iterable objects (they can be looped through!) and they are indexed.</p><pre>my_string = &#39;Hello world!&#39;<br>for char in my_string:<br>    print(char)</pre><pre># =&gt; H<br># =&gt; e<br># =&gt; l<br># =&gt; l<br># =&gt; o<br># =&gt; <br># =&gt; w<br># =&gt; o<br># =&gt; r<br># =&gt; l<br># =&gt; d<br># =&gt; !<br></pre><pre>my_string[0]<br># =&gt; &#39;H&#39;</pre><h3>Changing Case</h3><p>Strings can be formatted for case using three methods:</p><ul><li>str.upper() returns an uppercase version of the original string.</li><li>str.lower() returns a lowercase version of the original string.</li><li>str.title() returns the original string in titlecase (with the first letter of each new word capitalized.)</li></ul><h3><a href="https://www.w3schools.com/python/python_ref_string.asp">Other String MethodsLinks to an external site.</a></h3><p>There are many other string methods that will allow you to accomplish most simple reformatting and conversion operations that you’ll want to do. There are so many, in fact, that we’re providing a <a href="https://www.w3schools.com/python/python_ref_string.asp">link to a comprehensive listLinks to an external site.</a> instead of going in-depth on each one.</p><p>The important thing to remember when working with strings is that they are <strong>immutable</strong>. All string methods return a new object; they do not replace the original.</p><pre>my_string = &#39;hello world!&#39;<br>my_string.upper()<br># =&gt; HELLO WORLD!<br>print(my_string)<br># =&gt; hello world!</pre><h3>List Comprehensions and Generator Expressions</h3><h3>List Comprehensions</h3><p>Certain lists are very straightforward to create- some are even passed into your code as parameters and don’t require any work at all. Others take a bit more effort:</p><pre>squared_minus_one = list()</pre><pre>for n in range(1, 11):<br>    squared_minus_one.append((n ** 2) - 1)</pre><pre>print(squared_minus_one)<br># [0, 3, 8, 15, 24, 35, 48, 63, 80, 99]</pre><p>A list comprehension allows us to skip certain steps when we generate squared_minus_one:</p><pre>squared_minus_one = [(n **2) - 1 for n in range(1, 11)]</pre><pre>print(squared_minus_one)<br># [0, 3, 8, 15, 24, 35, 48, 63, 80, 99]</pre><p>A list comprehension allows us to instantiate a list object and perform a for loop to populate its values in a single line. Because the contents of our original for loop are straightforward, we can rewrite them on a single line without making our code hard to read.</p><p>Additionally, because list comprehensions are executed as a single line of code, we do not need to define squared_minus_one beforehand. Using a list comprehension instead of a traditional for loop, we can create our new list and assign its values in one line instead of three.</p><p><em>Which data type does a list comprehension return?</em></p><p>The syntax of a list comprehension is as follows:</p><pre>new_list = [optional_operation(item) for item in old_list if optional_condition == True]</pre><p>You do not need to perform an operation on the items in your original list or include any conditions in your list comprehension. These options allow you to eliminate even more bulk from your code!</p><h3>Generator Expressions</h3><p>Generator expressions are very similar to list comprehensions. They use almost identical syntax to produce iterable objects in a single line:</p><pre>one_to_three = range(1,4)</pre><pre># A list comprehension uses square brackets<br>squared_lc = [n ** 2 for n in one_to_three]</pre><pre># A generator expression uses parentheses<br>squared_ge = (n ** 2 for n in one_to_three)</pre><pre># Looping through each shows identical values...<br>for n in squared_lc:<br>    print(n)</pre><pre># 1<br># 4<br># 9</pre><pre>for n in squared_ge:<br>    print(n)</pre><pre># 1<br># 4<br># 9</pre><pre># But the objects are NOT identical<br>print(squared_lc)<br># [1, 4, 9]<br>print(squared_ge)<br># &lt;generator object &lt;genexpr&gt;&gt;</pre><p>Generator expressions produce generator objects instead of lists. In most code that you will write, list comprehensions are preferable.</p><p>The key difference between list comprehensions and generator expressions is that <strong>list comprehensions create new, complete lists</strong> while <strong>generator expressions save the code to create new, complete lists</strong>.</p><p>Because list comprehensions create the lists as soon as they are read by the interpreter, their data is easily accessible. A list is much faster to use than a generator.</p><p>That being said, you might not always want a full list hanging around in memory. Let’s check the size of the two objects in the Python shell:</p><pre># sys allows us to look into system memory, among other things<br>import sys</pre><pre>list_comprehension = [n for n in range(100000)]<br>generator_expression = (n for n in range(100000))</pre><pre># Returns the size of an object in bytes<br>sys.getsizeof(list_comprehension)<br># 824456<br>sys.getsizeof(generator_expression)<br># 112</pre><p>When writing code for yourself, you will almost always use list comprehensions. If you’re ever working with big datasets in your career, remember that generator expressions will use less memory and keep your servers happy.</p><p>We will explore generator expressions in greater depth when we introduce <strong>file input/output</strong> and <strong>database queries</strong> later</p><p><strong>Resources</strong></p><ul><li><a href="https://www.geeksforgeeks.org/python-list-comprehension/">Python — List ComprehensionLinks to an external site.</a></li><li><a href="https://realpython.com/list-comprehension-python/">When to Use a List Comprehension in PythonLinks to an external site.</a></li><li><a href="https://peps.python.org/pep-0289/">PEP 289 — Generator ExpressionsLinks to an external site.</a></li><li><a href="https://www.geeksforgeeks.org/generator-expressions/">Python | Generator ExpressionsLinks to an external site.</a></li></ul><h3>Dictionaries</h3><p>In a Python dictionary, an immutable <em>key</em> is mapped to an arbitrary <em>value</em>. The result is a data type nearly identical to JSON:</p><pre>my_dict = {<br>    &quot;key 1&quot;: &quot;value 1&quot;,<br>    2.0: &quot;value 2&quot;,<br>}</pre><p>Keys can be composed of any immutable data type. The immutable types that we have discussed so far are:</p><ul><li>int</li><li>float</li><li>str</li><li>bool</li><li>tuple</li><li>range</li></ul><h3>When Are Dictionaries Used?</h3><p>Dictionaries are best used when there is a fixed name or value that we want to associate with a piece of data. An excellent analogy for a Python dictionary is…a dictionary!</p><p>We’ve introduced some new vocabulary in this lesson, so let’s organize it into a dictionary:</p><pre>key_vocab = {<br>    &quot;Mapping&quot;: &quot;a data structure in which data is stored in random order \<br>        and accessed using immutable keys.&quot;,<br>    &quot;Arbitrary&quot;: &quot;describes data whose value is unimportant to the data type \<br>        or structure in which it is contained.&quot;<br>}</pre><pre>key_vocab[&quot;Mapping&quot;]<br># &quot;a data structure in which data is stored in random order and accessed using immutable keys.&quot;<br>key_vocab[&quot;Arbitrary&quot;]<br># &quot;describes data whose value is unimportant to the data type or structure in which it is contained.&quot;</pre><p>Definitions are data that we need to access when we hear certain words. Using those words as keys makes it easy for us to access their definitions when we need to, without parsing through every other piece of data in the data structure. It is important that the keys themselves are of an immutable type (str) so definitions are always connected to the correct word.</p><p>Dictionaries can also be used to store many types of data that would describe the dictionary object itself. This is the use case most similar to JSON and allows for easy communication between Python and JavaScript. We’ll look more into this in Phase 4.</p><pre>software_engineer = {<br>    &quot;languages&quot;: [&quot;JavaScript&quot;, &quot;Python&quot;],<br>    &quot;certifications&quot;: [&quot;Flatiron School Certificate of Completion&quot;],<br>    &quot;experience&quot;: &quot;3 months and counting!&quot;,<br>}</pre><p>We can also use dictionaries as a replacement for switch/case statements, as we saw in the lesson on conditional statements. We call this approach <strong>dictionary mapping</strong>.</p><pre>size_to_ounce_map = {<br>    &quot;tall&quot;: 12,<br>    &quot;grande&quot;: 16,<br>    &quot;venti&quot;: 20,<br>}</pre><p>Now if we wanted to train a machine to pour the correct amount of coffee for each cup size, we could wrap this dictionary in a function where we enter our cup size and receive a volume in return:</p><pre>def pour_coffee(size):<br>    size_to_ounce_map = {<br>        &quot;tall&quot;: 12,<br>        &quot;grande&quot;: 16,<br>        &quot;venti&quot;: 20,<br>    }<br>    return size_to_ounce_map[size]</pre><blockquote><em>NOTE: If you choose to use dictionary mapping instead of an </em><em>if/elif/else statement, make sure you&#39;re using it to write shorter, clearer code.</em></blockquote><h3>Dictionary Methods</h3><h3>Getting Data</h3><p>The most important dictionary method is dict.get(). Open up the Python shell and enter our code from the pour_coffee() function above:</p><pre>def pour_coffee(size):<br>    size_to_ounce_map = {<br>        &quot;tall&quot;: 12,<br>        &quot;grande&quot;: 16,<br>        &quot;venti&quot;: 20,<br>    }<br>    return size_to_ounce_map[size]</pre><p>In the above example, we’re using simple bracket notation — [] - to access key value pairs within our size_to_ounce_map.</p><p>Now let’s test some different values for size:</p><pre>pour_coffee(&quot;tall&quot;)<br># 12<br>pour_coffee(&quot;grande&quot;)<br># 16<br>pour_coffee(&quot;venti&quot;)<br># 20<br>pour_coffee(&quot;jumbo&quot;)<br># KeyError: &#39;jumbo&#39;</pre><p>This error helps us, but it doesn’t help our poor coffee machine pour coffee. dict.get() gives us some tools to avoid KeyErrors. Let&#39;s change our return statement to use dict.get():</p><pre>def ...<br>    return size_to_ounce_map.get(size)</pre><pre>pour_coffee(&quot;jumbo&quot;)<br># None</pre><p>We’ve managed to avoid a KeyError, but None might not be very helpful either. Let&#39;s make one last change:</p><pre>def ...<br>    return size_to_ounce_map.get(size, &quot;Please enter a valid cup size.&quot;)</pre><pre>pour_coffee(&quot;jumbo&quot;)<br># &#39;Please enter a valid cup size.&#39;</pre><p>dict.get() takes two arguments. The first is required- this is the key that you&#39;re searching for in your dictionary. The second optional argument is a default value for your search (if you don&#39;t enter a second argument, Python uses None as a default value). dict.get() is the best way to retrieve values from a Python dictionary if you need to avoid KeyError exceptions.</p><h3>Setting Data</h3><p>In addition to getting data from a dictionary, we can add new data to a dictionary and update existing data within a dictionary.</p><p>As with getting data, there are a variety of ways to set data.</p><p>The simplest way is to just use bracket notation — [] - and the assignment operator, much like JavaScript:</p><pre>my_dict = {<br>    &quot;key_one&quot;: &quot;value one&quot;,<br>    &quot;key_two&quot;: &quot;value two&quot;,<br>}</pre><pre># update an existing key-value pair:<br>my_dict[&quot;key_one&quot;] = &quot;I&#39;ve changed!&quot;</pre><pre># set a new key-value pair:<br>my_dict[&quot;key_three&quot;] = &quot;value three&quot;</pre><pre>print(my_dict)<br># prints { &quot;key_one&quot;: &quot;I&#39;ve changed!&quot;, &quot;key_two&quot;: &quot;value two&quot;, &quot;key_three&quot;: &quot;value three&quot;}</pre><p>However, Python also offers us a powerful method — the update method - that can be used to set large amounts of data within an dictionary.</p><p>The update method can be used to add multiple new key-value pairs at the same time, update multiple fields at the same time, or do both:</p><pre>my_dict = {<br>    &quot;key_one&quot;: &quot;value one&quot;,<br>    &quot;key_two&quot;: &quot;value two&quot;,<br>}</pre><pre># update multiple fields:<br>my_dict.update({&quot;key_one&quot;: &quot;new value one&quot;, &quot;key_two&quot;: &quot;new value two&quot;})</pre><pre># add multiple fields:<br>my_dict.update({&quot;key_three&quot;: &quot;value three&quot;, &quot;key_four&quot;: &quot;value four&quot;})</pre><pre># add and update fields simultaneously:<br>my_dict.update({&quot;key_three&quot;: &quot;new value three&quot;, &quot;key_four&quot;: &quot;new value four&quot;, &quot;key_five&quot;: &quot;value five&quot;})</pre><pre>print(my_dict)<br># prints {&#39;key_one&#39;: &#39;new value one&#39;, &#39;key_two&#39;: &#39;new value two&#39;, &#39;key_three&#39;: &#39;new value three&#39;, &#39;key_four&#39;: &#39;new value four&#39;, &#39;key_five&#39;: &#39;value five&#39;}</pre><p>In this example, we passed a dictionary as the argument to update. However, you can also pass in tuples and arrays as arguments or use assignment operation:</p><pre>my_dict = {<br>    &quot;key_one&quot;: &quot;value one&quot;<br>}</pre><pre># passing in an array of arrays<br>my_dict.update([[&quot;key_one&quot;, &quot;new value one&quot;], [&quot;key_two&quot;, &quot;value two&quot;]])</pre><pre># passing in an array of tuples<br>my_dict.update([(&quot;key_two&quot;, &quot;new value two&quot;), (&quot;key_three&quot;, &quot;value three&quot;)])</pre><pre># passing in a tuple of arrays<br>my_dict.update(([&quot;key_three&quot;, &quot;new value three&quot;], [&quot;key_four&quot;, &quot;value four&quot;]))</pre><pre># passing in a tuple of tuples<br>my_dict.update(((&quot;key_four&quot;, &quot;new value four&quot;), (&quot;key_five&quot;, &quot;value five&quot;)))</pre><pre># using assignment operation<br>my_dict.update(key_five=&quot;new value five&quot;, key_six=&quot;value six&quot;)</pre><pre>print(my_dict)<br># prints {&#39;key_one&#39;: &#39;new value one&#39;, &#39;key_two&#39;: &#39;new value two&#39;, &#39;key_three&#39;: &#39;new value three&#39;, &#39;key_four&#39;: &#39;new value four&#39;, &#39;key_five&#39;: &#39;new value five&#39;, &#39;key_six&#39;: &#39;value six&#39;}</pre><h3>Iterating Over Dictionaries</h3><p>The next most commonly used dict method is dict.items(), which returns an object that can be treated as a list of tuples of key/value pairs.</p><p>That’s a dense definition, so let’s unpack it a bit:</p><pre>my_dict = {<br>    &quot;a&quot;: 1,<br>    &quot;b&quot;: 2,<br>    &quot;c&quot;: 3,<br>    &quot;d&quot;: 4,<br>}</pre><pre>[key for key in my_dict]<br># [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;]<br>[my_dict[key] for key in my_dict]<br># [1, 2, 3, 4]</pre><p>We can iterate through a dictionary similarly to how we would a sequence, using either a loop or a comprehension. When we iterate through a dictionary, though, we can only access elements using keys. The object returned by dict.items() makes keys and values accessible independently of one another:</p><pre>my_dict = {<br>    &quot;a&quot;: 1,<br>    &quot;b&quot;: 2,<br>    &quot;c&quot;: 3,<br>    &quot;d&quot;: 4,<br>}</pre><pre>[item for item in my_dict.items()]<br># [(&#39;a&#39;, 1), (&#39;b&#39;, 2), (&#39;c&#39;, 3), (&#39;d&#39;, 4)]<br>[key for key, value in my_dict.items()]<br># [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;]<br>[value for key, value in my_dict.items()]<br># [1, 2, 3, 4]</pre><p>dict objects are very useful when accessing one key/value pair at a time, but dict.items() is an important tool in writing elegant loops and list comprehensions.</p><p>There are many more dict methods, but these are the most common that you will see in your software career. A full list of dict methods can be found in the <a href="https://docs.python.org/3/tutorial/datastructures.html#dictionaries">Python </a><a href="https://docs.python.org/3/tutorial/datastructures.html#dictionaries">dict documentationLinks to an external site.</a>.</p><p><strong>Sets</strong> are the last built-in data structure in Python. Sets share the following characteristics:</p><ul><li>Set elements are <em>unique</em>. Duplicates are not supported.</li><li>Set elements are <em>unordered</em>. This means that they cannot be accessed by index.</li><li>Sets are mutable, but can only <em>store</em> immutable data.</li></ul><p>Like lists, tuples, and dictionaries, sets can be defined using their class constructor or with brackets:</p><pre>my_set = set([1, 2, 3])<br>my_set = {1, 2, 3}</pre><blockquote><em>NOTE: Instantiating an empty set requires the use of the </em><em>set() class constructor. Closed curly brackets </em><em>{} will instantiate an empty dictionary.</em></blockquote><h3>When Are Sets Used?</h3><p>Sets are much less commonly used than sequences and maps, but they can be helpful in accomplishing a handful of common tasks:</p><p>Instantiating a set using a sequence is a good way to isolate unique members:</p><pre>my_list = [1, 2, 1, 3, 2]<br>set(my_list)<br># {1, 2, 3}</pre><p>…though it is important to remember that sets are unordered, so our output might not be pretty:</p><pre>my_string = &quot;the big red cat ate the fat rat&quot;<br>set(my_string)<br># {&#39;g&#39;, &#39;h&#39;, &#39;b&#39;, &#39;r&#39;, &#39;e&#39;, &#39;d&#39;, &#39;f&#39;, &#39;c&#39;, &#39;t&#39;, &#39;a&#39;, &#39;i&#39;, &#39; &#39;}</pre><p>To determine if two collections have the same members, we can check their sets:</p><pre>set(range(1, 10)) == set([1, 2, 3, 4, 5, 6, 7, 8, 9])<br># True</pre><p>If the sets are not identical, we can use the intersection &amp; operator to see what they have in common:</p><pre>set_1 = {1, 2, 3}<br>set_2 = {3, 4, 5}<br>set_1 &amp; set_2<br># 3</pre><p>…or we can check for differences using the difference - operator:</p><pre>set_1 = {1, 2, 3}<br>set_2 = {3, 4, 5}<br>set_1 - set_2<br># {1, 2}<br>set_2 - set_1<br># {4, 5}</pre><p>Using these operators also allows us to dynamically modify sets as our program runs:</p><pre>set_1 = {1, 2, 3}<br>set_2 = {3, 4, 5}<br>set_1 &amp;= set_2<br># {3}<br>set_2 -= set_1<br># {4, 5}</pre><p>Sets also support comprehensions with the same syntax as lists:</p><pre>sentence = &quot;Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.&quot;<br>unique_consonants = {c.lower() for c in sentence if c not in &quot;aeiou ,.&quot;}<br># {&#39;g&#39;, &#39;p&#39;, &#39;b&#39;, &#39;l&#39;, &#39;r&#39;, &#39;d&#39;, &#39;m&#39;, &#39;q&#39;, &#39;c&#39;, &#39;t&#39;, &#39;s&#39;, &#39;n&#39;}</pre><p>For more set features, see the <a href="https://docs.python.org/3/library/stdtypes.html#set">Python </a><a href="https://docs.python.org/3/library/stdtypes.html#set">set documentation.Links to an external site.</a></p><h3>Conclusion</h3><p>Sets are not the most common data structure in Python, but they can be useful when you need to create and compare unique collections of data. Remember that sets are <strong>unique, unordered, and mutable</strong>.</p><h3>Conclusion to Data Structures</h3><p>Python’s built-in data structures:</p><ul><li>Sequences (lists, tuples, ranges, strings) are ordered collections of data.</li><li>Dictionaries are the only mapping type in Python, connecting keys to values.</li><li>Sets are unordered collections of unique elements. Their structure can be changed, but their elements cannot.</li></ul><h3>Intro to Object-Oriented Programming</h3><h3>Key Vocab</h3><ul><li><strong>Class</strong>: a bundle of data and functionality. Can be copied and modified to accomplish a wide variety of programming tasks.</li><li><strong>Initialize</strong>: create a working copy of a class using its __init__() method.</li><li><strong>Instance</strong>: one specific working copy of a class. It is created when a class’s __init__() method is called.</li><li><strong>Object</strong>: the more common name for an instance. The two can usually be used interchangeably.</li><li><strong>Object-Oriented Programming</strong>: programming that is oriented around data (made mobile and changeable in <strong>objects</strong>) rather than functionality. Python is an object-oriented programming language.</li><li><strong>Procedural Programming</strong>: programming that is oriented around procedures that are called in sequential order. Fortran and C are procedural programming languages.</li><li><strong>Function</strong>: a series of steps that create, transform, and move data.</li><li><strong>Method</strong>: a function that is defined inside of a class.</li><li><strong>Magic Method</strong>: a special type of method in Python that starts and ends with double underscores. These methods are called on objects under certain conditions without needing to use their names explicitly. Also called <strong>dunder methods</strong> (for <strong>d</strong>ouble <strong>under</strong>score).</li><li><strong>Attribute</strong>: variables that belong to an object.</li><li><strong>Property</strong>: attributes that are controlled by methods.</li></ul><h3>Creating Instances of Classes</h3><p>Open up the Python shell, or create a new Python file to code along, and enter the following code:</p><pre># Remember that Python requires some indented code in each code block.<br># Instead of empty blocks, we use the &quot;pass&quot; keyword to do nothing.</pre><pre>class Dog:<br>    pass</pre><pre>fido = Dog()<br>fido<br># &lt;__main__.Dog object at 0x1049a87f0&gt;</pre><p>In the code sample above, once we’ve defined our Dog class with the class keyword, we immediately can bring to life new individual dogs, the variable fido which points to a new <strong>instance</strong> of a dog.</p><p>We <strong>instantiate</strong> an instance of the Dog class by calling the constructor function Dog(). This creates our <strong>instance</strong> of the Dog class, which we assign to the variable fido. An instance of a class is also referred to as an object.</p><p><strong>Instantiate</strong> means bringing a new object to life, a new individual, like a particular dog, like Snoopy or Lassie or Rover. Each particular dog is an individual that was <strong>instantiated</strong> when we called the constructor function Dog() to birth it into our world of programming.</p><p>We call these individuals, each specific dog or version of our class, <strong>instances</strong>. An <strong>instance</strong> is a single occurrence of an <strong>object.</strong> <strong>Instances</strong> refer to the individual objects produced from the class.</p><pre>class Dog:<br>    pass</pre><pre>fido = Dog()<br>fido<br># &lt;__main__.Dog object at 0x1049a87f0&gt;</pre><pre>snoopy = Dog()<br>snoopy<br># &lt;__main__.Dog object at 0x104971d90&gt;</pre><p>snoopy and fido are two different variables pointing at separate instances of the Dog class.</p><h3>Different Instances are Different Objects</h3><p>Let’s make three dogs:</p><pre>class Dog:<br>    pass</pre><pre>fido = Dog()<br>fido<br># &lt;__main__.Dog object at 0x1049a87f0&gt;</pre><pre>snoopy = Dog()<br>snoopy<br># &lt;__main__.Dog object at 0x104971d90&gt;</pre><pre>lassie = Dog()<br>lassie<br># &lt;__main__.Dog object at 0x10498c040&gt;</pre><p>Notice that every time you make an instance of a class, Python tells you that the return value is something that looks like # &lt;__main__.Dog object at 0x1049a87f0&gt;. This is the default way that Python communicates to you that you are dealing with an instance of a particular class. The __main__ tells you that the object is accessible from a global scope in the current module (file or shell) that you&#39;re working in. 0x1049a87f0 describes the instance&#39;s location in memory.</p><p>Each of these instances is totally unique, even though they are all born from Dog.</p><pre>class Dog:<br>    pass</pre><pre>fido = Dog()<br>fido<br># &lt;__main__.Dog object at 0x1049a87f0&gt;</pre><pre>snoopy = Dog()<br>snoopy<br># &lt;__main__.Dog object at 0x104971d90&gt;</pre><pre>snoopy == fido<br># False</pre><p>Classes are the blueprints that define the behavior and information our objects will contain. They let us manufacture and instantiate new instances.</p><p>Class names begin with capital letters because they are stored in Python constants. If your class name contains two words, the name should be in UpperCamelCase (also called <em>PascalCase</em> if you’re feeling fancy), like this:</p><h3>Conclusion</h3><p>In summary: to create a new class definition, use the class keyword. A class is like a template, or a blueprint, for creating objects with similar characteristics.</p><p>To use the class to create individual objects, call the class with closed parentheses as you would a function or method. This will <strong>instantiate</strong> (create a new <strong>instance</strong> of) an object from the class. Each instance created will be a unique object in memory.</p><h3>Introduction</h3><p>We know that classes are a collection of data and functionality that act as a factory for our objects. We create those objects by calling our class just as we would a function, with closed parentheses:</p><pre>class Dog:<br>    pass</pre><pre>fido = Dog()<br># &lt;__main__.Dog object at 0x1027f07f0&gt;</pre><p>But what can this instance of a dog stored in the local variable fido do? In fact, how do we even ask this object to do something?</p><h3>The Behavior of Objects</h3><p>Objects on their own don’t do very much. In order to see the behavior of an object, we need to interact with it to elicit a response. There are certain strategies for interacting with objects that allow us to access their data and functionality from the outside.</p><h3>Dot Notation</h3><p>We send objects messages asking them to perform an operation or task through a syntax known as “Dot Notation”.</p><pre>class Dog:<br>    pass</pre><pre>fido = Dog()<br># &lt;__main__.Dog object at 0x1027f07f0&gt;</pre><pre>fido.__dir__()<br># [&#39;__module__&#39;, &#39;__dict__&#39;, &#39;__weakref__&#39;, &#39;__doc__&#39;, &#39;__repr__&#39;, &#39;__hash__&#39;,<br># &#39;__str__&#39;, &#39;__getattribute__&#39;, &#39;__setattr__&#39;, &#39;__delattr__&#39;, &#39;__lt__&#39;,<br># &#39;__le__&#39;, &#39;__eq__&#39;, &#39;__ne__&#39;, &#39;__gt__&#39;, &#39;__ge__&#39;, &#39;__init__&#39;, &#39;__new__&#39;,<br># &#39;__reduce_ex__&#39;, &#39;__reduce__&#39;, &#39;__subclasshook__&#39;, &#39;__init_subclass__&#39;,<br># &#39;__format__&#39;, &#39;__sizeof__&#39;, &#39;__dir__&#39;, &#39;__class__&#39;]</pre><p>When we interact with an object through dot notation, we are calling the variable or function that is defined inside of the object. We call these instance variables <strong>attributes</strong> and these instance functions <strong>methods</strong>. Unless otherwise specified, all of an object’s methods are considered <strong>instance methods</strong>. <strong>Instance methods</strong> can access and modify the attributes of an instance.</p><p>In the example above, we access the fido instance&#39;s __dir__() method by separating the object, fido and the method, __dir__() by a dot (.).</p><p>The __dir__() method provides you with a list of the object&#39;s methods and attributes. You&#39;ll notice that even though we didn&#39;t provide the Dog class with any attributes or methods, it has many by default!</p><blockquote><em>I thought of objects being like biological cells and/or individual computers on a network, only able to communicate with messages. — Alan Kay</em></blockquote><pre>&quot;Strings are objects too.&quot;.upper()<br># &#39;STRINGS ARE OBJECTS TOO.&#39;</pre><h3>Building Your Own Instance Methods</h3><p>If you haven’t already, fork and clone this lab to your local environment and run pytest -x. Follow along below to get the first few tests for the Dog class to pass. Once you have those passing, you will complete the remaining tasks on your own.</p><p>How do we add our own methods to our classes? In our Dog example, can we teach our Dog a new trick? Can we teach our Dog to bark for example?</p><p>We can. We’re used to defining functions already with the def keyword. If we place this function definition within the body of a class, that function becomes a specific behavior of instances of that class, not a generic procedure we can just call whenever we want.</p><p>Let’s create our Dog class in lib/dog.py. It&#39;s a convention among Python developers to define each class in its own file, using the class name to determine the file name.</p><p>In the Dog class, let&#39;s define our bark() instance method:</p><pre>class Dog:<br>  # Class body</pre><pre>  # Instance Method Definition<br>  def bark(self):<br>    print(&quot;Woof!&quot;)</pre><p>Note the use of the self keyword in our instance method definition above. We will explore the concept of self in depth in the next module- just know for now that it allows methods to access the other methods and attributes. self is <strong>required</strong> in instance method definitions, though you don&#39;t actually need to pass it in when you call the method.</p><p>With this code in place, if you run the tests you should now be passing the first three tests.</p><p>Now let’s create an instance of Dog and verify that our Dog object knows how to bark:</p><pre>class Dog:<br>    def bark(self):<br>        print(&quot;Woof!&quot;)</pre><pre>fido = Dog()<br>fido.bark()<br># Woof!</pre><p>If you execute this code in the terminal by running python lib/dog.py, you should see &quot;Woof!&quot; written out.</p><p>By defining bark() within the Dog class, bark becomes a method of all instances of Dogs. Let&#39;s create a second instance of Dog, snoopy, and verify that snoopy also knows how to bark by running python lib/dog.py again.</p><pre>class Dog:<br>  def bark(self):<br>    print(&quot;Woof!&quot;)</pre><pre>fido = Dog()<br>fido.bark()<br># Woof!</pre><pre>snoopy = Dog()<br>snoopy.bark()<br># Woof!</pre><p>Objects can only do what we teach them to do via the code we write and the methods we define. For example, currently, Dogs do not know how to sit.</p><pre>class Dog:<br>  def bark(self):<br>    print(&quot;Woof!&quot;)</pre><pre>fido = Dog()<br>fido.bark()<br># Woof!</pre><pre>fido.sit()<br># AttributeError: &#39;Dog&#39; object has no attribute &#39;sit&#39;</pre><p>In the same manner, instance methods, the methods that belong to particular instances of particular classes, cannot be used globally like procedural methods. They cannot be called without an instance.</p><pre>class Dog:<br>  def bark(self):<br>    print(&quot;Woof!&quot;)</pre><pre>fido = Dog()<br>fido.bark()<br># Woof!</pre><pre># Let&#39;s try just calling bark without fido<br>bark()<br># NameError: name &#39;bark&#39; is not defined</pre><p>We’ve already seen many new instances of different classes being created:</p><pre>class Dog:<br>    pass</pre><pre>fido = Dog()<br># &lt;__main__.Dog object at 0x104fc0550&gt;</pre><pre>snoopy = Dog()<br># &lt;__main__.Dog object at 0x104fc0562&gt;</pre><p>We know from their IDs that fido and snoopy live in different locations in memory, but their <em>behavior</em> is identical. We don&#39;t provide them any unique methods or attributes in the code above.</p><p>We can modify their attributes using dot notation as follows:</p><pre>fido.breed = &quot;Dalmatian&quot;<br>snoopy.breed = &quot;Beagle&quot;</pre><pre>fido.breed<br># Dalmatian<br>snoopy.breed<br># Beagle</pre><p>…but dogs are <em>born</em> with breeds, not assigned breeds later on. To provide objects with unique attributes upon instantiation, we use the __init__ method.</p><h3>__init__</h3><p>Every time we initialize a new object, the Python interpreter calls a <strong>magic method</strong> called __init__. <strong>Magic methods</strong> (also called <strong>dunder methods</strong> due to their <strong>d</strong>ouble <strong>under</strong>scores) are special methods that are not meant to be called by developers but are invoked by different cues and operators that act on their objects.</p><p>The __init__ method belongs to every class and is invoked when you initialize a class. Though you cannot see it in our Dog class above, there is code that is executed behind the scenes.</p><p>Though it always executes when we initialize an object, it does not do anything by default. Instead, we overwrite __init__ in most classes to change an object&#39;s behavior:</p><pre>class Dog:<br>    # Remember that all methods use &quot;self.&quot; We&#39;ll elaborate on this in a moment.<br>    def __init__(self):<br>        print(&quot;A dog is born!&quot;)</pre><pre>    def bark(self):<br>        print(&quot;Woof!&quot;)</pre><pre>fido = Dog()<br># A dog is born!</pre><p>__init__ can also be modified to take more arguments. This allows us to customize the behavior of unique objects:</p><pre>class Dog:<br>    def __init__(self, name):<br>        print(f&quot;{name} is born!&quot;)</pre><pre>    def bark(self):<br>        print(&quot;Woof!&quot;)</pre><pre>fido = Dog(&quot;Fido&quot;)<br># Fido is born!</pre><pre>snoopy = Dog(&quot;Snoopy&quot;)<br># Snoopy is born!</pre><p><em>When is the __init__ magic method run?</em></p><h3>self</h3><p>Modifying __init__ has allowed us to provide fido and snoopy with different behaviors, but now that they&#39;ve both been initialized, they&#39;re more or less the same dog. In order to make lasting changes to an object, we need to modify self. Before we do, open up the Python shell and let&#39;s take a look at self:</p><pre>class Dog:<br>    def __init__(self, name):<br>        print(f&quot;{name} is born!&quot;)</pre><pre>    def bark(self):<br>        print(&quot;Woof!&quot;)</pre><pre>    def showing_self(self):<br>        return self</pre><pre>fido = Dog(&quot;Fido&quot;)<br># Fido is born!<br>fido.showing_self()<br># &lt;__main__.Dog object at 0x104f8bfa0&gt;</pre><p>You might recognize this output from earlier- self is the same type of object as fido! As a matter of fact, it <em>is</em> fido!</p><pre>fido is fido.showing_self()<br># True</pre><p>How does this work? Inside the showing_self() method, we use the self keyword.</p><p>The self keyword <strong>refers to the instance</strong>, or object, that the showing_self() <strong>method is being called on</strong>.</p><p>So, when we call showing_self() on fido, the method will return the Dog instance that is fido.</p><p>If you’re familiar with Object Oriented JavaScript from previous experience, the closest equivalent to self in Python is this in JavaScript. Again, no worries if you haven&#39;t seen OOJS before. The this keyword behaves similarly, where this refers to <strong>the object to the left of the dot</strong> when a method is called on an object:</p><pre>class Dog {<br>  showingThis() {<br>    return this;<br>  }<br>}</pre><pre>const fido = new Dog();<br>fido.showingThis();<br>// =&gt; Dog {}</pre><h3>__init__ and self Together</h3><p>Now that we know that __init__ contains code that runs whenever we initialize a new object and that the self that is passed to each method is a reference to the initialized object, let&#39;s make some unique dogs:</p><pre>class Dog:<br>    def __init__(self, name):<br>        self.name = name</pre><pre>    def bark(self):<br>        print(&quot;Woof!&quot;)</pre><pre>fido = Dog(&quot;Fido&quot;)<br>fido.name<br># Fido</pre><pre>snoopy = Dog(&quot;Snoopy&quot;)<br>snoopy.name<br># Snoopy</pre><h3>Operating on self in an Instance Method</h3><p>Let’s say that Fido here is getting adopted. Fido’s new owner is Sophie. We can set Fido’s owner attribute equal to the string of &quot;Sophie&quot;. The name of his new owner:</p><pre>class Dog:<br>  def __init__(self, name):<br>    self.name = name</pre><pre>fido.owner = &quot;Sophie&quot;</pre><pre>fido.owner<br># &quot;Sophie&quot;</pre><p>Great, Fido now knows the name of his owner. Let’s think about the situation in which fido gets a new owner. This would occur at the moment in which fido is adopted.</p><p>To represent this with code, we could write an adopt() function like this:</p><pre>def adopt(dog, owner_name):<br>    dog.owner = owner_name</pre><p>Here we have a method that takes in two arguments, an instance of the Dog class and an owner&#39;s name. We could call our method like this:</p><pre>adopt(fido, &quot;Sophie&quot;)</pre><pre># now we can ask Fido who his owner is:</pre><pre>fido.owner<br># =&gt; &quot;Sophie&quot;</pre><p>However, the beauty of object-oriented programming is that we can encapsulate, or wrap up, attributes and behaviors into one object. Instead of writing a function that is not associated to any particular object and that takes in certain objects as arguments, we can simply teach our Dog instances how to get adopted.</p><p>Let’s refactor our code above into an instance method on the Dog class.</p><pre>class Dog:<br>    def __init__(self, name):<br>        self.name = name</pre><pre>    def bark(self):<br>        print(&quot;Woof!&quot;)</pre><pre>    def get_adopted(self, owner_name):<br>        self.owner = owner_name</pre><p>Here, we use the self keyword inside of the get_adopted() instance method to refer to whichever dog this method is being called on. We set that dog&#39;s owner equal to owner_name just as we would assign any other variable!</p><p>Think about it: if self <strong>refers to the object on which the method is being called</strong>, and if that object is an instance of the Dog class, then we can call any of our other instance methods on self.</p><p>Here’s how we’d use the get_adopted() method:</p><pre>fido = Dog(&quot;Fido&quot;)<br>fido.get_adopted(&quot;Sophie&quot;)<br>fido.owner<br># &quot;Sophie&quot;</pre><h3>Optional __init__ Arguments</h3><p>There are a number of things that are important to know about a dog that you’re planning to adopt. Age, weight, breed, and many more attributes factor into whether they’re a good fit for you and your home. Other things, like favorite toys, are not quite so important.</p><p>To accommodate these less important details, Python lets us set default values for arguments in any method or function. Let’s see how we would prepare an optional favorite_toy argument:</p><pre>class Dog:<br>    def __init__(self, name, favorite_toy=&quot;Any&quot;):<br>        self.name = name<br>        self.favorite_toy = favorite_toy</pre><pre>fido = Dog(&quot;Fido&quot;)<br>fido.favorite_toy<br># Any</pre><pre>snoopy = Dog(&quot;Snoopy&quot;, &quot;Tennis Ball&quot;)<br>snoopy.favorite_toy<br># Tennis Ball</pre><p>Do note, however, that arguments without default values are <em>not</em> optional:</p><pre>old_yeller = Dog()<br># TypeError: __init__() missing 1 required positional argument: &#39;name</pre><h3>Attributes and Properties</h3><h3>Introduction</h3><p>So far, we’ve learned how to build classes and give them instance methods. We also learned how to use the __init__ magic method to instantiate objects and the self keyword to modify its <strong>attributes</strong>.</p><p>In this lesson, we will continue to explore attributes and <strong>properties</strong>, a special type of attribute.</p><h3>Class Attributes vs Instance Attributes</h3><p>Let’s take a look at a class definition:</p><pre>class Human:<br>    species = &quot;Homo sapiens&quot;<br>    def __init__(self, name):<br>        self.name = name</pre><p>This class, Human, takes a name as an argument for its initialization method and saves it as an attribute of self. This attribute varies from one instance of the Human class to the next, so we call this an <em>instance attribute</em>.</p><p>Since species is set outside the scope of any methods, it is a <em>class attribute</em>. All members of the Human class have the same species, so this makes more sense than setting the same value for every new human upon instantation.</p><p>An interesting note about class attributes is that they can be accessed on the class itself, in addition to any instances:</p><pre>guido = Human(&quot;Guido&quot;)<br>guido.species<br># =&gt; Homo sapiens<br>Human.species<br># =&gt; Homo sapiens</pre><p>Since name is an instance attribute, calling it on the Human class will result in an error:</p><pre>guido = Human(&quot;Guido&quot;)<br>guido.name<br># =&gt; Guido<br>Human.name<br># =&gt; AttributeError: type object &#39;Human&#39; has no attribute &#39;name&#39;</pre><p><em>If we enter </em><em>guido.nationality = &quot;Dutch&quot; into the interpreter, will </em><em>nationality be a class or instance attribute?</em></p><h3>Setting and Getting Attributes</h3><p>Many programming languages opt to protect their objects’ attributes and methods (members). They accomplish this by making the distinction between <em>public</em>, <em>private</em>, and <em>protected</em>. These terms are good to know, as you will almost certainly encounter them in your software career:</p><ul><li><em>Public</em> members are available to anyone that can access the class.</li><li><em>Private</em> members are available to the class that instantiated them.</li><li><em>Protected</em> members are available to the class that instantiated them and any object that inherits from that class, but is not accessible otherwise.</li></ul><p>Python does not make the distinction between public, private, and protected. This makes it very easy for us to manipulate the members of a class or object with dot notation:</p><pre>class Human:<br>    species = &quot;Homo sapiens&quot;<br>    def __init__(self, name):<br>        self.name = name</pre><pre>guido = Human(&quot;Guido&quot;)<br>guido.species<br># =&gt; Homo sapiens<br>guido.name<br># =&gt; Guido</pre><pre># Changing species and name using dot notation<br>guido.species = &quot;Python programmer&quot;<br>guido.name = &quot;Guido van Rossum&quot;</pre><pre>guido.species<br># =&gt; Python programmer<br>guido.name<br># =&gt; Guido van Rossum</pre><pre># Adding new attributes using dot notation<br>guido.nationality = &quot;Dutch&quot;<br>guido.nationality<br># =&gt; Dutch</pre><p><strong>Because it is so simple to modify the attributes of classes and objects in Python, it is very rare that we write extra code to get or set attributes.</strong></p><p>Python also provides us a few built-in functions to manipulate attributes:</p><ul><li>getattr() retrieves the value of an attribute.</li><li>setattr() changes the value of an attribute, just as you would with dot notation.</li><li>hasattr() checks for the presence of an attribute.</li><li>delattr() removes an attribute from a class or object.</li></ul><p>You might be wondering at this point why getattr() and setattr() even exist when dot notation can be used to accomplish the same tasks:</p><pre># Getting<br>guido.name<br># =&gt; Guido van Rossum<br>getattr(guido, &quot;name&quot;)<br># =&gt; Guido van Rossum</pre><pre>#Setting<br>guido.nationality = &quot;Dutch&quot;<br>setattr(guido, &quot;nationality&quot;, &quot;Dutch&quot;)</pre><p>The value in Python’s attr() functions comes in their ability to create, retrieve, update, and delete attributes for which the names are unknown.</p><blockquote><em>NOTE: </em><em>getattr() also allows us to provide an optional third argument as a default value if the attribute does not exist.</em></blockquote><pre>my_attr = &quot;is_a_friend&quot;<br>getattr(guido, my_attr, False)<br># =&gt; False</pre><pre># Oh no! Let&#39;s try again.<br>setattr(guido, my_attr, True)<br>getattr(guido, my_attr, False)<br># =&gt; True</pre><p><em>Which </em><em>attr() function checks for the presence of an attribute?</em></p><h3>Properties</h3><p>Python’s flexibility with respect to members of classes and objects is very useful to us, but sometimes we need to prepare for bad actors (like me, right now):</p><pre># Setting Guido&#39;s age<br>guido.age = False</pre><p>It is always best practice to make our code as descriptive and easy to interpret as possible. Still, there are people who may not understand what we intended or who want to break our program. It’s clear that we want Guido’s age to be a numerical value between 0 and some reasonable upper limit (we’ll say 120). When we need to make sure an attribute meets a certain set of criteria, we need to configure it as a <strong>property</strong>.</p><p><strong>Properties</strong> in Python are attributes that are controlled by methods. The function of these methods is to make sure that the value of our property makes sense. We can configure <strong>properties</strong> using our knowledge of object-oriented programming and Python’s built-in property() function. Open up the Python shell or a Python file to follow along:</p><pre>class Human:<br>    species = &quot;Homo sapiens&quot;</pre><pre>    def __init__(self, age):<br>        self.age = age</pre><pre>    def get_age(self):<br>        print(&quot;Retrieving age.&quot;)<br>        return self._age</pre><pre>    def set_age(self, age):<br>        print(f&quot;Setting age to { age }&quot;)<br>        self._age = age</pre><pre>    age = property(get_age, set_age)</pre><p>Let’s break this down a bit:</p><ul><li>get_age() is compiled by the property function and prints &quot;Retrieving age&quot; when we access age through dot notation or an attr() function.</li><li>set_age() is compiled by the property() function and prints &quot;Setting age to { age }&quot; when we change our human&#39;s age.</li><li>The property() function compiles our getter and setter and calls them whenever anyone accesses our human&#39;s age.</li></ul><p>Notice the <em>single underscore</em> we place before the age attribute. This tells other Python programmers that this is meant to be treated as a <em>private</em> member of the class. It is not truly private, but it is a way to tell your coworkers that this is a <strong>property</strong> and there are methods that depend on its name and values.</p><blockquote><em>NOTE: This is still not a true </em>private<em> value; you can still manipulate it with dot notation and </em><em>attr() functions (though you shouldn&#39;t!)</em></blockquote><p>There’s still a problem- we’re not checking if the age is a number between 0 and 120. Let’s make one last change to finish our Human class:</p><pre>class Human:<br>    species = &quot;Homo sapiens&quot;</pre><pre>    def __init__(self, age):<br>        self.age = age</pre><pre>    def get_age(self):<br>        print(&quot;Retrieving age.&quot;)<br>        return self._age</pre><pre>    def set_age(self, age):<br>        if (type(age) in (int, float)) and (0 &lt;= age &lt;= 120):<br>            print(f&quot;Setting age to { age }.&quot;)<br>            self._age = age</pre><pre>        else:<br>            print(&quot;Age must be a number between 0 and 120.&quot;)</pre><pre>    age = property(get_age, set_age)</pre><p>Now we have a proper <strong>property</strong> set up. Let’s make sure it works:</p><pre>guido = Human(age=67)<br># =&gt; Setting age to 67.<br>guido.age = 0<br># =&gt; Setting age to 0.<br>guido.age = False<br># =&gt; Age must be a number between 0 and 120<br>guido.age = 66<br># =&gt; Setting age to 66.<br>guido.age<br># =&gt; Retrieving age.<br># =&gt; 66</pre><h3>Property Function Decorator : Code-Along</h3><h3>Key Vocab</h3><ul><li><strong>Attribute</strong>: variables that belong to an object.</li><li><strong>Property</strong>: attributes that are controlled by methods.</li><li><strong>Decorator</strong>: function that takes another function as an argument and returns a new function with added functionality.</li></ul><h3>Introduction</h3><p>Properties in Python are attributes that are controlled by methods. We’ve already seen how to use the property() function to define getter and setter methods that control how object attributes are accessed and modified.</p><p>A <strong>decorator</strong> is a function that takes another function as an argument and returns a new function, often attaching pre- or post-processing functionality. The decorator syntax was not available when the property() function was originally introduced. However, the decorator syntax was added in Python 2.4, and using property() as a decorator has become a popular practice.</p><h3>Code-Along</h3><p>This lesson is a code-along, so fork and clone the repo.</p><p><strong>NOTE: Remember to run </strong><strong>pipenv install to install the dependencies and </strong><strong>pipenv shell to enter your virtual environment before running your code.</strong></p><pre>pipenv install<br>pipenv shell</pre><h3>Reviewing property()</h3><p>Before we see how to use a decorator to define a property, let’s review the original property() function.</p><p>We’ll start with a Dog class with attributes for name and breed.</p><ul><li>name must be a string of 1 to 25 characters in length</li><li>breed must be a string in the list of approved breeds</li></ul><p>We define getter and setter methods for the attributes, then use the property function to enforce that the methods are used to access and mutate the attributes:</p><pre>APPROVED_BREEDS = [<br>    &quot;Mastiff&quot;,<br>    &quot;Chihuahua&quot;,<br>    &quot;Corgi&quot;,<br>    &quot;Shar Pei&quot;,<br>    &quot;Beagle&quot;,<br>    &quot;French Bulldog&quot;,<br>    &quot;Pug&quot;,<br>    &quot;Pointer&quot;<br>]<br></pre><pre>class Dog:<br>    def __init__(self, name=&#39;Fido&#39;, breed=&#39;Mastiff&#39;):<br>        self.name = name<br>        self.breed = breed</pre><pre>    def get_name(self):<br>        return self._name</pre><pre>    def set_name(self, name):<br>        if isinstance(name, str) and 1 &lt;= len(name) &lt;= 25:<br>            self._name = name.title()<br>        else:<br>            raise ValueError(<br>                &quot;Name must be string between 1 and 25 characters.&quot;)</pre><pre>    name = property(get_name, set_name)</pre><pre>    def get_breed(self):<br>        return self._breed</pre><pre>    def set_breed(self, breed):<br>        if breed in APPROVED_BREEDS:<br>            self._breed = breed<br>        else:<br>            raise ValueError(&quot;Breed must be in list of approved breeds.&quot;)</pre><pre>    breed = property(get_breed, set_breed)</pre><p>Let’s use the debugger to create a few instances of Dog.</p><p>Type python lib/debug.py to start an ipdb session.</p><p>If we create a Dog with a valid name and breed, no exception is thrown:</p><pre>ipdb&gt; Dog(&quot;Fido&quot;, &quot;Corgi&quot;)<br>&lt;dog.Dog object at 0x1051dc700&gt;</pre><p>However, passing a name that is not a string results in a ValueError exception:</p><pre>ipdb&gt; Dog(7, &quot;Pug&quot;)<br>*** ValueError: Name must be string between 1 and 25 characters.</pre><p>A name with an invalid length also throws the exception:</p><pre>ipdb&gt; Dog(&quot;Fido the Pug who likes to roll in the mud&quot;, &quot;Pug&quot;)<br>*** ValueError: Name must be string between 1 and 25 characters.</pre><p>An exception is thrown if the breed is not in the approved list:</p><pre>ipdb&gt; Dog(&quot;Fifi&quot;, &quot;Poodle&quot;)<br>*** ValueError: Breed must be in list of approved breeds.</pre><p>Type exit() to exit out of the ipdb session.</p><p><em>Will this code throw an exception?<br></em><em>dog = Dog(&quot;Snoopy&quot;, &quot;Beagle&quot;)<br>dog.breed = &quot;Beagle, Blue Tick&quot;</em></p><p>The lesson repo contains a file dog_property_test.py for testing the Dog class and its properties.</p><pre>from dog import Dog<br>import pytest<br></pre><pre>class TestDogProperties:<br>    &#39;&#39;&#39;Class Dog in dog.py&#39;&#39;&#39;</pre><pre>    def test_name_breed_valid(self):<br>        &#39;&#39;&#39;validates name and breed properties are initialized with valid values&#39;&#39;&#39;<br>        try:<br>            # No exception should be thrown since name and breed are valid<br>            dog = Dog(&quot;Fido&quot;, &quot;Corgi&quot;)<br>        except Exception as exc:<br>            # The assertion fails if an exception is thrown<br>            assert False, f&#39;Dog(&quot;Fido&quot;, &quot;Corgi&quot;) raised an exception {exc}&#39;</pre><pre>    def test_name_is_string_valid_length(self):<br>        &#39;&#39;&#39;validates name property is assigned a string between 1 and 25 characters&#39;&#39;&#39;<br>        dog = Dog(&quot;Fido&quot;, &quot;Corgi&quot;)<br>        with pytest.raises(ValueError):<br>            dog.name = 7  # not a string<br>        with pytest.raises(ValueError):<br>            dog.name = &#39;&#39;  # too short<br>        with pytest.raises(ValueError):<br>            dog.name = &#39;Fido the adorable Corgi who likes to steal socks&#39;  # too long</pre><pre>    def test_breed_is_approved_breed(self):<br>        &#39;&#39;&#39;validates breed property is in list of approved choices&#39;&#39;&#39;<br>        dog = Dog(&quot;Snoopy&quot;, &quot;Beagle&quot;)<br>        with pytest.raises(ValueError):<br>            dog.breed = &quot;Poodle&quot;  # not an approved breed</pre><p>Let’s run the tests to confirm the current implementation of the name and breed properties. The tests should pass.</p><pre>pytest -x</pre><h3>Function Decorators</h3><p>We decorate a function by placing the name of the decorator with a leading @ symbol before the definition of the function you want to decorate:</p><pre>@decorator<br>def func(a):<br>    return a</pre><p>This syntax is equivalent to the following:</p><pre>def func(a):<br>    return a</pre><pre>func = decorator(func)</pre><h3>Using property() as a Decorator</h3><p>We use the @property decorator to define a property&#39;s getter method. The method should use the public name for the underlying managed attribute, for example name.</p><p>Delete the get_name method:</p><pre>def get_name(self):<br>        return self._name</pre><p>Add the name getter method decorated with @property as shown:</p><pre>@property<br>def name(self):<br>    &quot;&quot;&quot;The name property&quot;&quot;&quot;<br>    return self._name</pre><p>Delete the set_name method:</p><pre>def set_name(self, name):<br>    if isinstance(name, str) and 1 &lt;= len(name) &lt;= 25:<br>        self._name = name.title()<br>    else:<br>        raise ValueError(<br>            &quot;Name must be string between 1 and 25 characters.&quot;)</pre><p>Add the name setter method decorated with @name.setter as shown:</p><pre>@name.setter<br>def name(self, name):<br>    &quot;&quot;&quot;Name must be a string between 1 and 25 characters in length&quot;&quot;&quot;<br>    if isinstance(name, str) and 1 &lt;= len(name) &lt;= 25:<br>        self._name = name<br>    else:<br>        raise ValueError(&quot;Name must be string between 1 and 25 characters.&quot; )</pre><p>Finally, you can delete the call to the property function as the decorators have defined the getter and setter methods:</p><pre>name = property(get_name, set_name)</pre><p>We’ll define the breed property in a similar manner. The final version of the Dog class is as shown:</p><pre>APPROVED_BREEDS = [<br>    &quot;Mastiff&quot;,<br>    &quot;Chihuahua&quot;,<br>    &quot;Corgi&quot;,<br>    &quot;Shar Pei&quot;,<br>    &quot;Beagle&quot;,<br>    &quot;French Bulldog&quot;,<br>    &quot;Pug&quot;,<br>    &quot;Pointer&quot;<br>]<br></pre><pre>class Dog:<br>    def __init__(self, name=&#39;Fido&#39;, breed=&#39;Mastiff&#39;):<br>        self.name = name<br>        self.breed = breed</pre><pre>    @property<br>    def name(self):<br>        &quot;&quot;&quot;The name property&quot;&quot;&quot;<br>        return self._name</pre><pre>    @name.setter<br>    def name(self, name):<br>        &quot;&quot;&quot;Name must be a string between 1 and 25 characters in length&quot;&quot;&quot;<br>        if isinstance(name, str) and 1 &lt;= len(name) &lt;= 25:<br>            self._name = name<br>        else:<br>            raise ValueError(<br>                &quot;Name must be string between 1 and 25 characters.&quot;<br>            )</pre><pre>    @property<br>    def breed(self):<br>        &quot;&quot;&quot;The breed property&quot;&quot;&quot;<br>        return self._breed</pre><pre>    @breed.setter<br>    def breed(self, breed):<br>        &quot;&quot;&quot;Breed must be in the list of approved breeds&quot;&quot;&quot;<br>        if breed in APPROVED_BREEDS:<br>            self._breed = breed<br>        else:<br>            raise ValueError(&quot;Breed must be in list of approved breeds.&quot;)</pre><p>Notice that now the method names actually match the attributes name and breed, and the decorators clearly indicate the purpose of each method. This is considered to be more Pythonic - more intuitive to Python developers in general.</p><p>If we need methods for deleting the properties, we would decorate the methods with @name.deleter and @breed.deleter.</p><p>Run the tests to confirm the updated class implementation works.</p><pre>pytest -x</pre><p>You can also use the ipdb debugger to instantiate Dog objects and attempt to set the name and breed attributes to valid and invalid values.</p><h3>Conclusion</h3><p>Let’s summarize the important points when creating properties with the decorator approach:</p><ul><li>The @property decorator must decorate the getter method, which should have the same name as the attribute.</li><li>The docstring must go in the getter method.</li><li>The setter and deleter methods must be decorated with the same name as the getter method plus .setter and .deleter, respectively.</li></ul><h3>Principles of Object-Oriented Design</h3><h3>The Single Responsibility Principle and Separation of Concerns</h3><p>The <strong>single responsibility principle</strong> is the idea that classes in object-oriented programming should have <strong>one job</strong>, one responsibility, and their services (i.e., methods) should be aligned with that responsibility. This principle goes hand in hand with the <strong>separation of concerns</strong>: the idea that the various responsibilities, or <em>concerns</em>, of a computer program should be separated out into <strong>discrete sections</strong>.</p><p>Let’s take the example of an online shopping web application. Such an application has a number of jobs to handle: we need to have users that sign in and purchase items; we have the items themselves that we are selling; we likely have a shopping cart as well. We could develop an application that takes care of all of these jobs in the following manner:</p><pre>class MyStore:</pre><pre>    def sign_in(self, user):<br>        self.user = user</pre><pre>    def current_user(self):<br>        return self.user</pre><pre>    def item(self, item):<br>        self.item = item</pre><pre>    def item_price(self, price):<br>        self.item_price = price</pre><pre>    def shopping_cart(self):<br>        self.shopping_cart = list()</pre><pre>    def add_item_to_cart(self, item)<br>        self.shopping_cart.append(item)</pre><p>As you can see, our code starts to get out of control relatively quickly. What happens when our program needs to grow to accommodate a feature like coupons? Will we continue to add code to this one file? What happens if our program breaks? How will we determine which of our many methods is responsible for the bug? What if we need to change a particular feature of our app? How can we be sure that we’ve tracked down all of the affected methods?</p><p>Instead, we want to <strong>separate the concerns</strong>, or responsibilities, of such an application, wrapping each concern in its own class that produces its own objects.</p><p>We could write a User class, an Item class and a ShoppingCart class. The User class should be responsible for assigning a user a name and other details and signing a user in and out. The Item class should have methods that describe an item&#39;s attributes, including its price. The ShoppingCart class can collect individual item objects and total their price at the time of checkout.</p><p>By creating classes with their own responsibilities, we create an application that is organized and logical, and accommodates future change. We also create a program that doesn’t give us a headache to even look at.</p><h3>Abstraction and Don’t Repeat Yourself (DRY)</h3><p>Another basic OO principle is that of <strong>Don’t Repeat Yourself</strong> (DRY). If you find yourself repeating the same lines of code again and again, that is a good candidate for refactoring. As programmers, we are lazy (in a good way!) — we are always looking for ways to achieve the desired behavior by writing less code, and we hate to repeat ourselves. Let’s take a look at an example by revisiting our online shopping application.</p><p>Lately, our client has been offering a variety of discounts. At the time of checkout, a user can tell our application that they have a 10, 25, or 50 percent discount. So, our program needs to determine if a user has a discount and then apply it, if present. Let’s take a look at the checkout() method of our ShoppingCart class.</p><pre>def checkout(self, discount=0):<br>    # The shopping_cart method returns an array of all the user&#39;s items<br>    total = sum([item.price for item in self.shopping_cart()])</pre><pre>    if discount == 10:<br>        total -= total * 10 / 100.00<br>    elif discount == 20:<br>        total -= total * 20 / 100.00<br>    elif discount == 50:<br>        total -= total * 50 / 100.00</pre><pre>    return total</pre><p>In the above method, we are using an if/else statement to determine what kind of discount a user has, if any, and then doing some math to calculate the appropriate total. In order to take a discount into account, we are using six lines of code every time we check out a user! That&#39;s a lot of repetition. Additionally, what if our application needs to apply coupons to a user&#39;s total <em>before</em> they check out? Maybe our client has decided to give their users 20% on their current total if they refer a friend to the site. We would have to use the same if/else statement elsewhere in our code. That&#39;s a lot of code to constantly re-type.</p><p><strong>Top-Tip:</strong> If you find yourself copy/pasting the same lines of code more than three times in order to re-use it throughout your program, consider it a “code smell”. A code smell is a sign that you should refactor.</p><p>Let’s refactor this by creating an attribute to access data about a coupon amount. Then, our checkout() method can simply use the coupon attribute to help it calculate the user&#39;s total:</p><pre>class ShoppingCart:<br>    def __init__(self, coupon=0):<br>        self.coupon = coupon</pre><pre>    def checkout(self):<br>        total = sum([item.price for item in self.shopping_cart()])<br>        total -= total * self.coupon / 100<br>        return total</pre><p>We’ve achieved the same behavior with less code. This refactor has the added benefit of being <em>flexible</em>, meaning it will accommodate future change. If our client decides to add a new type of coupon, a 23% off discount, the coupon method, having <em>abstracted</em> away the value of the coupon, will still work. This is the benefit of abstraction, and we prefer abstracting out attributes by wrapping them inside methods over having our code rely on literal values.</p><h3>Domain Modeling</h3><p>One important concept to help organize your object oriented code is the idea of <strong>domain modeling</strong>.</p><p>A domain model is a representation of real-world concepts in software. The concept of domain modeling is key in object orientation. In object orientation, we think of our classes as templates for objects. The instances of our classes are thought of as objects. For example, a Person class produces people objects that have attributes (data) and behaviors, as described and enacted by instance methods.</p><p>Let’s think of an example on a slightly larger scale. Let’s say we are writing an application that will be used by a major automobile manufacturer to help manage their plants. In this case, we need a program that represents not just individual cars, but the entire car factory. In this (simplified) example, you could write an AutoPlant class that produces individual cars and has instance methods that handle things like take_inventory or paint_cars.</p><p>Such a program not only represents a single object or concept but an entire environment — that of the auto factory. Consequently, this program could be understood as a <strong>domain model</strong>. It takes the world of the auto factory, and maps the individual parts of that world to different parts of your program.</p><p>As we begin to write more and more advanced programs, you’ll see that to really accurately model a domain, we’ll need to build a program that contains more than one class.</p><h3>Conclusion</h3><p>This has been a very brief intro into the what, why and how of design principles in object-oriented Python. These principles are meant to guide you, not limit you. These principles are also just the very tip of the OO design iceberg. You’ll learn more about design over the remainder of this course and you’ll learn even more about design over the course of the rest of your programming life.</p><h3>Conclusion to Object-Oriented Programming Basics</h3><p>In this section we explained the concept of class and instance variables, as well as instance methods. We learned about creating properties using Python’s built-in property() function, as well as how to dynamically manipulate attributes using attr() functions. We can now set instance attributes from the __init__ magic method at the same time as we instantiate objects using the self keyword.</p><p>Javascript</p><ul><li>JavaScript, where null, undefined, false, 0, NaN, and &quot;&quot; are all falsy values:</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3dd5d9f01e46" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A side-by-side comparison of code differences between JavaScript and Python, presented in a table :]]></title>
            <link>https://medium.com/@weddynkatha265/a-side-by-side-comparison-of-code-differences-between-javascript-and-python-presented-in-a-table-3f32b38d679f?source=rss-16477706e78b------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f32b38d679f</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[ｐｙｔｈｏｎ]]></category>
            <category><![CDATA[python-programming]]></category>
            <dc:creator><![CDATA[WeddyNkatha265]]></dc:creator>
            <pubDate>Tue, 27 Aug 2024 08:12:21 GMT</pubDate>
            <atom:updated>2024-08-27T08:25:06.129Z</atom:updated>
            <content:encoded><![CDATA[<pre>| **Feature**          | **Python Code**                                                                                     | **JavaScript Code**                                                                                 |<br>|----------------------|-----------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------|<br>| **Variable Declaration** | `x = 10` &lt;br&gt; No keyword needed, and type is inferred.                                        | `let x = 10;` &lt;br&gt; Uses `let`, `const`, or `var` for declaration.                                |<br>| **Function Definition**  | `def greet(name): &lt;br&gt; return f&quot;Hello, {name}!&quot;`                                               | `function greet(name) { &lt;br&gt; return `Hello, ${name}!`; &lt;br&gt;}`                                    |<br>| **Conditional Statements** | `if x &gt; 0: &lt;br&gt; print(&quot;Positive&quot;)`                                                           | `if (x &gt; 0) { &lt;br&gt; console.log(&quot;Positive&quot;); &lt;br&gt;}`                                               |<br>| **Loops**            | `for i in range(5): &lt;br&gt; print(i)`                                                               | `for (let i = 0; i &lt; 5; i++) { &lt;br&gt; console.log(i); &lt;br&gt;}`                                       |<br>| **List/Array**       | `numbers = [1, 2, 3, 4, 5]` &lt;br&gt; Dynamic and can hold mixed types.                               | `let numbers = [1, 2, 3, 4, 5];` &lt;br&gt; Dynamic but typically holds similar types.                 |<br>| **Dictionary/Object**| `person = {&quot;name&quot;: &quot;Alice&quot;, &quot;age&quot;: 25}` &lt;br&gt; Key-value pairs in a dictionary.                   | `let person = {name: &quot;Alice&quot;, age: 25};` &lt;br&gt; Key-value pairs in an object.                     |<br>| **Print/Output**     | `print(&quot;Hello, World!&quot;)`                                                                        | `console.log(&quot;Hello, World!&quot;);`                                                                 |<br>| **Importing Modules**| `import math &lt;br&gt; print(math.sqrt(16))`                                                          | `import { sqrt } from &#39;mathjs&#39;; &lt;br&gt; console.log(sqrt(16));`                                     |<br>| **Exception Handling** | `try: &lt;br&gt; result = 10 / 0 &lt;br&gt; except ZeroDivisionError: &lt;br&gt; print(&quot;Cannot divide by zero!&quot;)` | `try { &lt;br&gt; let result = 10 / 0; &lt;br&gt;} catch (e) { &lt;br&gt; console.log(&quot;Cannot divide by zero!&quot;); &lt;br&gt;}` |</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*_dxXzP0a9IMZ7WvQpQR8EQ.png" /></figure><p>l</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lxaOP3-QqYlnqkKROA4muw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TOiNLR4_SxZHePUB71kIFw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f32b38d679f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Here’s a side-by-side comparison of Python and JavaScript :]]></title>
            <link>https://medium.com/@weddynkatha265/heres-a-side-by-side-comparison-of-python-and-javascript-eb8dd6da31e6?source=rss-16477706e78b------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb8dd6da31e6</guid>
            <dc:creator><![CDATA[WeddyNkatha265]]></dc:creator>
            <pubDate>Tue, 27 Aug 2024 07:36:52 GMT</pubDate>
            <atom:updated>2024-08-27T07:41:31.361Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wU3FnAEK1sWvRHXW" /><figcaption><strong>Python vs. JavaScript: A Side-by-Side Comparison</strong></figcaption></figure><p><strong>1. Purpose &amp; Usage</strong></p><ul><li><strong>Python:</strong></li><li>General-purpose language, widely used in data science, machine learning, web development, automation, and scripting.</li><li>Known for its simplicity and readability, making it a popular choice for beginners.</li></ul><p><strong>JavaScript:</strong></p><ul><li>Primarily a client-side scripting language, used extensively in web development to create interactive and dynamic web pages.</li><li>Can also be used for server-side development (Node.js) and building mobile and desktop applications.</li></ul><p><strong>2. Syntax &amp; Structure</strong></p><ul><li><strong>Python:</strong></li><li>Emphasizes readability with its use of indentation to define code blocks.</li><li>Follows a more traditional, clean syntax that is often described as “executable pseudocode.”</li><li>Example:</li><li>python</li><li>def greet(name): return f&quot;Hello, {name}!&quot;</li><li><strong>JavaScript:</strong></li><li>Uses curly braces {} to define code blocks and semicolons ; to end statements (though semicolons are optional).</li><li>Known for its flexibility but sometimes criticized for allowing multiple ways to accomplish the same task.</li><li>Example:</li></ul><h3><strong>javascript</strong></h3><ul><li>function greet(name) { return `Hello, ${name}!`; }</li></ul><p><strong>3. Typing System</strong></p><p><strong>Python:</strong></p><ul><li>Dynamically typed: You don’t need to declare variable types, and types are inferred at runtime.</li><li>Strongly typed: Implicit type conversion is less frequent, reducing the risk of type-related errors.</li></ul><p><strong>JavaScript:</strong></p><ul><li>Dynamically typed: Similar to Python, variable types are determined at runtime.</li><li>Weakly typed: Allows more implicit type conversions, which can lead to unexpected behavior.</li></ul><p><strong>4. Execution Environment</strong></p><p><strong>Python:</strong></p><ul><li>Runs on the server-side (backend), though it can be used for scripting on the client-side (e.g., with PyScript).</li><li>Interpreted language, often executed in a virtual environment or directly from the terminal.</li></ul><p><strong>JavaScript:</strong></p><ul><li>Traditionally runs in the browser (client-side), but with Node.js, it can also run on the server-side.</li><li>Interpreted by JavaScript engines like V8 in browsers or Node.js runtime.</li></ul><p><strong>5. Libraries &amp; Frameworks</strong></p><p><strong>Python:</strong></p><ul><li>Rich ecosystem with popular libraries like NumPy, Pandas, TensorFlow for data science, and Django, Flask for web development.</li><li>Extensive support for scientific computing, AI, and machine learning.</li></ul><p><strong>JavaScript:</strong></p><ul><li>Extensive collection of frameworks like React, Angular, and Vue.js for front-end development, and Express.js for back-end development.</li><li>A strong focus on web technologies and asynchronous programming.</li></ul><p><strong>6. Learning Curve</strong></p><p><strong>Python:</strong></p><ul><li>Generally considered easier to learn due to its simple and readable syntax.</li><li>Ideal for beginners or those entering programming through data science or automation.</li></ul><p><strong>JavaScript:</strong></p><ul><li>Can be more challenging due to its quirks, asynchronous nature, and the complexity of the web ecosystem.</li><li>Essential for front-end developers and those focused on web technologies.</li></ul><p><strong>7. Performance</strong></p><p><strong>Python:</strong></p><ul><li>Generally slower than JavaScript, especially in web applications, due to its interpreted nature.</li><li>Suitable for tasks where performance is less critical, or when using optimized libraries (e.g., NumPy for numerical computations).</li></ul><p><strong>JavaScript:</strong></p><ul><li>Often faster in web environments, especially with modern JavaScript engines like V8.</li><li>Designed with web performance in mind, making it well-suited for interactive applications.</li></ul><p><strong>8. Community &amp; Support</strong></p><p><strong>Python:</strong></p><ul><li>Strong community with vast resources, tutorials, and forums.</li><li>Extensive documentation and a culture of collaboration in the open-source community.</li></ul><p><strong>JavaScript:</strong></p><ul><li>One of the largest developer communities, with an abundance of tutorials, forums, and open-source projects.</li><li>Constantly evolving with frequent updates and new libraries.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb8dd6da31e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Fetching in React]]></title>
            <link>https://medium.com/@weddynkatha265/data-fetching-in-react-fa1cadc66775?source=rss-16477706e78b------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa1cadc66775</guid>
            <dc:creator><![CDATA[WeddyNkatha265]]></dc:creator>
            <pubDate>Fri, 09 Aug 2024 10:26:51 GMT</pubDate>
            <atom:updated>2024-08-09T10:26:51.074Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*bxEkHw1xewxOFjmGunb-Cw.png" /></figure><h3>Learning Goals</h3><ul><li>Use fetch within components</li><li>Decide whether to use fetch from an event handler or useEffect callback</li></ul><h3>Problem Statement</h3><p>We’ve seen that React components come with some neat-o bells and whistles. They can be nested within each other. They can pass information and logic between them with props and they can keep track of their own information in state.</p><p>So far though, we’ve been restricted to displaying information organized by the React app itself. In this lesson, we’re going to go a step further and incorporate remote data into our React apps. Using fetch requests to APIs, we can build dynamic, responsive apps around data that is provided to us remotely.</p><h3>Fetching Data in React Components</h3><p>For a minute, consider how a site like <a href="https://www.instagram.com/">InstagramLinks to an external site.</a> works. If you’ve got an account on Instagram, when you visit the site, you’ll see an endless scroll of photos from people you follow. Everyone sees the same <em>Instagram</em> website, but the images displayed are unique to the user.</p><p>Similarly, consider <a href="https://airbnb.com/">AirBnbLinks to an external site.</a>. When you click to look at a listing’s information, the page layout is always the same. The data, the images, the reviews… this information changes.</p><p>Both of these websites are built with React. When you go to one of these sites, React doesn’t have the specific listing or image content. If you’re on a slow connection (or <a href="https://developer.chrome.com/docs/devtools/network/reference#throttling">want to mimic one using the Chrome Dev ToolsLinks to an external site.</a>), you can see what is happening more clearly.</p><p><em>React</em> shows up first and renders <em>something</em>. Sometimes it is just the background or the skeleton of a website, or maybe navigation and CSS. On Instagram, a photo ‘card’ might appear but without an image or username attached.</p><p>React is <em>updating the DOM</em> based on the JSX being returned by its components <em>first</em>. Once the DOM has been updated, remote data is then requested. When that data has been received, React runs through an update of the necessary components and fills in the info it received. Text content will appear, user information, etc… This first set of data is likely just a JSON object specific to the user or content requested. This object might contain image URLs, so right after the component update, images will be able to load.</p><p>So, since the data is being requested <em>after</em> React has updated the DOM, is there a <em>side effect</em> that might be useful here?</p><p>Well, yes there is! Whenever we want to fetch data in our components without making a user trigger that request by clicking a button or submitting a form, the useEffect hook gives us a great place to do that. By putting a fetch() within useEffect, when the data is received, we can use setState to store the received data. This causes an update with that remote data stored in state. A very simple implementation of the App component with fetch might look like this:</p><pre>import React, { useState, useEffect } from &quot;react&quot;;</pre><pre>function App() {<br>  const [peopleInSpace, setPeopleInSpace] = useState([]);</pre><pre>  useEffect(() =&gt; {<br>    fetch(&quot;http://api.open-notify.org/astros.json&quot;)<br>      .then((response) =&gt; response.json())<br>      .then((data) =&gt; {<br>        setPeopleInSpace(data.people);<br>      });<br>  }, []);<br>  // use an empty dependencies array, so we only run the fetch request ONCE</pre><pre>  return &lt;div&gt;{peopleInSpace.map((person) =&gt; person.name)}&lt;/div&gt;;<br>}</pre><pre>export default App;</pre><p>React includes a <a href="https://reactjs.org/docs/faq-ajax.html#example-using-ajax-results-to-set-local-state">similar example of this patternLinks to an external site.</a> in their FAQs, since it’s a pretty common problem for single page applications.</p><p>In the code above, we start with an empty array in state for peopleInSpace. When the component is first rendered to the DOM, it will just display an empty &lt;div&gt;, since we have no elements in the peopleInSpace array.</p><p><strong>After</strong> the App component has been rendered to the DOM, the useEffect callback runs, and fetch initiates a network request to an API. Once data is returned from the API, we update React&#39;s internal state with that data, which tells React to re-render our component. After the component re-renders, new content will appear in the &lt;div&gt; based on the peopleInSpace array.</p><p>Placing fetch in a useEffect with an empty dependencies array is ideal for data that you need immediately when a user visits your website or uses your app. Since useEffect is also commonly used to initialize intervals, it is ideal to set up any repeating fetch requests here as well.</p><p>We can also add a loading indicator using this technique. Since our component will render once <em>before</em> useEffect runs our fetch request, we can set up another state variable to add a loading indicator, like this:</p><pre>function App() {<br>  const [peopleInSpace, setPeopleInSpace] = useState([]);<br>  const [isLoaded, setIsLoaded] = useState(false);</pre><pre>  useEffect(() =&gt; {<br>    fetch(&quot;http://api.open-notify.org/astros.json&quot;)<br>      .then((response) =&gt; response.json())<br>      .then((data) =&gt; {<br>        setPeopleInSpace(data.people);<br>        setIsLoaded(true);<br>      });<br>  }, []);</pre><pre>  // if the data hasn&#39;t been loaded, show a loading indicator<br>  if (!isLoaded) return &lt;h3&gt;Loading...&lt;/h3&gt;;</pre><pre>  return &lt;div&gt;{peopleInSpace.map((person) =&gt; person.name)}&lt;/div&gt;;<br>}</pre><h3>Fetching Data With Events</h3><p>We aren’t limited to sending fetch requests with useEffect. We can also tie them into events:</p><pre>function handleClick() {<br>  fetch(&quot;your API url&quot;)<br>    .then((res) =&gt; res.json())<br>    .then((json) =&gt; setData(json));<br>}</pre><pre>return &lt;button onClick={handleClick}&gt;Click to Fetch!&lt;/button&gt;;</pre><p>This lets us send requests on demand. Submitting form data would be handled this way, using a POST request instead of GET.</p><p>A slightly more complicated example would be the infinite scroll of sites like Instagram. An event listener tied to changes in the scroll position of a page could fire off a handleScroll method that requests data before a user reaches the bottom of a page.</p><h3>Using State with POST Requests</h3><p>One of the beautiful features of state is that we can organize it however we need. If we were building a form to submit to a server, we can structure state to work nicely with what the server is expecting in a POST request.</p><p>Say we were building a user sign up form. When we send the data, our server is expecting two values within the body of the POST, username and password.</p><p>Setting up a React controlled form, we can structure our state in the same way:</p><pre>function Form() {<br>  const [formData, setFormData] = useState({<br>    username: &quot;&quot;,<br>    password: &quot;&quot;,<br>  });</pre><pre>  //since the id values are the same as the keys in formData, we can write an abstract setFormData here<br>  function handleChange(event) {<br>    setFormData({<br>      ...formData,<br>      [event.target.id]: event.target.value,<br>    });<br>  }</pre><pre>  return (<br>    &lt;form onSubmit={handleSubmit}&gt;<br>      &lt;input<br>        type=&quot;text&quot;<br>        id=&quot;username&quot;<br>        value={formData.username}<br>        onChange={handleChange}<br>      /&gt;<br>      &lt;input<br>        type=&quot;text&quot;<br>        id=&quot;password&quot;<br>        value={formData.password}<br>        onChange={handleChange}<br>      /&gt;<br>    &lt;/form&gt;<br>  );<br>}</pre><p>Then, when setting up the fetch request, we can just pass the entire state within the body, as there are no other values:</p><pre>function handleSubmit(event) {<br>  event.preventDefault();<br>  fetch(&quot;the server URL&quot;, {<br>    method: &quot;POST&quot;,<br>    headers: {<br>      &quot;Content-Type&quot;: &quot;application/json&quot;,<br>    },<br>    body: JSON.stringify(formData),<br>  });<br>}</pre><p>Notice how we’re not bothering to worry about event.target when posting the data. Since the form is controlled, state contains the most up-to-date form data, and it is already in the right format!</p><h3>Conclusion</h3><p>When you need to <em>get</em> data from an API when your component is first rendered, using useEffect with an empty dependencies array, like this, is a good approach:</p><pre>useEffect(() =&gt; {<br>  fetch(&quot;/api&quot;)<br>    .then((r) =&gt; r.json())<br>    .then(setData);<br>}, []);</pre><p>Aside from that, there are no hard and fast rules for how to include fetch requests, and a lot of structure will depend on the data you’re working with. As a general practice for writing simpler component code, include fetch calls in the same component as your top level state.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa1cadc66775" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Event Handling in React]]></title>
            <link>https://medium.com/@weddynkatha265/event-handling-in-react-c5494c0d3259?source=rss-16477706e78b------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5494c0d3259</guid>
            <dc:creator><![CDATA[WeddyNkatha265]]></dc:creator>
            <pubDate>Thu, 08 Aug 2024 11:32:28 GMT</pubDate>
            <atom:updated>2024-08-08T11:32:28.166Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*bxEkHw1xewxOFjmGunb-Cw.png" /><figcaption>React</figcaption></figure><h3>Learning Goals</h3><ul><li>Understand how to use React events in our application</li><li>Attach event listeners to JSX elements</li></ul><h3>Overview</h3><p>In this lesson, we’ll cover the event system in React. We’ll learn how to attach event listeners to specific elements.</p><h3>Adding Event Handlers</h3><p>Consider the following component:</p><pre>function Tickler() {<br>  function tickle() {<br>    console.log(&quot;Teehee!&quot;);<br>  }</pre><pre>  return &lt;button&gt;Tickle me!&lt;/button&gt;;<br>}</pre><p>We have a tickle() function, but no way to trigger it! This is a perfect time to add an event listener so that we can see the message in our console. We attach an event listener to an element much like we add a prop.</p><p>The listener name is always comprised of on, and the event name itself, for example click. These are joined together and camel-cased, so if we wanted to add a click handler, we&#39;d call the prop onClick.</p><p>This prop takes a <strong>callback function</strong> as a value. It can either be a reference to a function (like our tickle() function), or an inline function. Most of the time, we&#39;ll use a function reference.</p><p>All together, it looks like this:</p><pre>&lt;button onClick={tickle}&gt;Tickle me!&lt;/button&gt;</pre><p>As you can see, we’re passing a function <em>reference</em>, and not executing the tickle function. Our updated component looks like this:</p><pre>function Tickler() {<br>  function tickle() {<br>    console.log(&quot;Teehee!&quot;);<br>  }</pre><pre>  return &lt;button onClick={tickle}&gt;Tickle me!&lt;/button&gt;;<br>}</pre><p>Now, when we click the button, we see a message in our console. Awesome!</p><p>We can also use an arrow function to define an event handler inline, and pass it to the event listener:</p><pre>function Tickler() {<br>  return &lt;button onClick={() =&gt; console.log(&quot;Teehee!&quot;)}&gt;Tickle me!&lt;/button&gt;;<br>}</pre><p>Arrow functions are a good choice if your event handler doesn’t need to handle much logic. If you have more than one line of code to run in your event handler, it’s a good idea to create a separate callback function (like in the first example).</p><h3>What Can We Listen For Events On?</h3><p>One important thing to note about event listeners: you can only attach them to DOM elements, <em>not</em> React components. For example, this will not work:</p><pre>function Clickable() {<br>  return &lt;button&gt;Click Me&lt;/button&gt;;<br>}</pre><pre>function App() {<br>  function handleClick() {<br>    console.log(&quot;click&quot;);<br>  }</pre><pre>  return &lt;Clickable onClick={handleClick} /&gt;;<br>}</pre><p>… but this will:</p><pre>function Clickable() {<br>  function handleClick() {<br>    console.log(&quot;click&quot;);<br>  }<br>  return &lt;button onClick={handleClick}&gt;Click Me&lt;/button&gt;;<br>}</pre><pre>function App() {<br>  return &lt;Clickable /&gt;;<br>}</pre><p>If we want to make the first example work so that handleClick is called in App, we&#39;d have to pass onClick as a <strong>prop</strong> on the Clickable component, like so:</p><pre>function Clickable({ onClick }) {<br>  return &lt;button onClick={onClick}&gt;Click Me&lt;/button&gt;;<br>}</pre><pre>function App() {<br>  function handleClick() {<br>    console.log(&quot;click&quot;);<br>  }</pre><pre>  return &lt;Clickable onClick={handleClick} /&gt;;<br>}</pre><p>In this example, we’re passing down a reference to the handleClick function as a <strong>prop</strong> called onClick to the Clickable component. Then, we&#39;re using that prop as the callback function for the &lt;button&gt; element&#39;s onClick attribute. That way, when the &lt;button&gt; element is clicked, the callback function handleClick will be called.</p><p>Whew! That’s a lot to keep track of. We’ll cover this concept of passing down callback functions as props in more detail later on.</p><p>Let’s explore a few other common event types and their use cases here. There’s some starter code provided, so feel free to code along and test things out in the console!</p><h3>onClick</h3><p>As we saw in the example above, adding a click event is pretty straightforward!</p><p>Using our Tickler component as an example, let&#39;s see what else we can do with a click event.</p><p>Update your component to look like this:</p><pre>function Tickler() {<br>  function tickle(event) {<br>    console.log(event);<br>  }</pre><pre>  return &lt;button onClick={tickle}&gt;Tickle me!&lt;/button&gt;;<br>}</pre><p>Just as in JavaScript, when we handle events in React, we can provide an event parameter to our event handler callback function. When the button is clicked, we can access all the information about the event (the event target, mouse coordinates via clientX and clientY, etc).</p><p>What if we wanted to pass other information to the event handler though? In the MultiButton component, we have three buttons that all share the same callback function for their onClick event:</p><pre>function MultiButton() {<br>  function handleClick(number) {<br>    console.log(`Button ${number} was clicked`);<br>  }</pre><pre>  return (<br>    &lt;div&gt;<br>      &lt;button onClick={handleClick}&gt;Button 1&lt;/button&gt;<br>      &lt;button onClick={handleClick}&gt;Button 2&lt;/button&gt;<br>      &lt;button onClick={handleClick}&gt;Button 3&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>When one of the buttons is clicked, we want the callback to log out the button’s number. If you try clicking one of those buttons now, you’ll still see the event object being logged, not the number of the button.</p><p>We could try this:</p><pre>function MultiButton() {<br>  function handleClick(number) {<br>    console.log(`Button ${number} was clicked`);<br>  }</pre><pre>  return (<br>    &lt;div&gt;<br>      &lt;button onClick={handleClick(1)}&gt;Button 1&lt;/button&gt;<br>      &lt;button onClick={handleClick(2)}&gt;Button 2&lt;/button&gt;<br>      &lt;button onClick={handleClick(3)}&gt;Button 3&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>…but now, the console messages will appear as soon as our component is rendered, not when the button is clicked. This is why we always need to provide a <em>function definition</em>, not a <em>function invocation</em> to our event handlers. Here’s the solution:</p><pre>function MultiButton() {<br>  function handleClick(number) {<br>    console.log(`Button ${number} was clicked`);<br>  }</pre><pre>  return (<br>    &lt;div&gt;<br>      &lt;button onClick={() =&gt; handleClick(1)}&gt;Button 1&lt;/button&gt;<br>      &lt;button onClick={() =&gt; handleClick(2)}&gt;Button 2&lt;/button&gt;<br>      &lt;button onClick={() =&gt; handleClick(3)}&gt;Button 3&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>By writing out an arrow function here, we’re providing each of our button’s onClick handlers a <em>function definition</em> that will only be <em>invoked</em> when the button is clicked.</p><h3>onChange</h3><p>The onChange attribute is useful for handling changes to <em>input values</em>. This event listener is often used with &lt;input&gt;, &lt;select&gt;, and &lt;textarea&gt; inputs (basically, anywhere you need to capture a user&#39;s input).</p><p>Here’s an example of using the onChange handler:</p><pre>function ChangeItUp() {<br>  function handleChange(event) {<br>    console.log(`${event.target.name}: ${event.target.value}`);<br>  }</pre><pre>  return (<br>    &lt;div&gt;<br>      &lt;input<br>        type=&quot;text&quot;<br>        name=&quot;search&quot;<br>        onChange={handleChange}<br>        placeholder=&quot;Enter search term...&quot;<br>      /&gt;</pre><pre>      &lt;select name=&quot;filter&quot; onChange={handleChange}&gt;<br>        &lt;option value=&quot;all&quot;&gt;Select a filter...&lt;/option&gt;<br>        &lt;option value=&quot;completed&quot;&gt;Completed&lt;/option&gt;<br>        &lt;option value=&quot;incomplete&quot;&gt;Incomplete&lt;/option&gt;<br>      &lt;/select&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>Try it out and note that, as text is entered into the &lt;input&gt; field, its value is captured using event.target.value and logged to the console.</p><h3>onSubmit</h3><p>Whenever you’re working with &lt;form&gt; elements, handling the submit event is a good way to interact with all the data from the form after it&#39;s been submitted.</p><p>Here’s a quick example:</p><pre>function Login() {<br>  function handleSubmit(event) {<br>    event.preventDefault();<br>    console.log(&quot;I submit&quot;);<br>  }</pre><pre>  return (<br>    &lt;form onSubmit={handleSubmit}&gt;<br>      &lt;input type=&quot;text&quot; name=&quot;username&quot; placeholder=&quot;Enter username...&quot; /&gt;<br>      &lt;input type=&quot;password&quot; name=&quot;password&quot; placeholder=&quot;Enter password...&quot; /&gt;<br>      &lt;button&gt;Login&lt;/button&gt;<br>    &lt;/form&gt;<br>  );<br>}</pre><p>When the form is submitted, just like in vanilla JavaScript, you must call event.preventDefault() to prevent the form from making a network request.</p><p>We’ll go into forms in more detail in a later lesson, and show the preferred way for collecting data from <em>all</em> the form input fields. For now, just remember: use the onSubmit event handler, and always call preventDefault()!</p><h3>How Does React Handle Events?</h3><p>You may have noticed when inspecting the event object that it&#39;s a bit different than the standard browser event. React&#39;s event object is a special object called: SyntheticBaseEvent.</p><p>React has its own event system with special event handlers called SyntheticEvent. The reason for having a specific event system instead of using native events is cross-browser compatibility. Some browsers treat events differently, and by wrapping these events into a consistent API, React makes our lives a lot easier. It&#39;s important to keep in mind that they are the <em>exact same events</em>, just implemented in a consistent way! That means these events also have methods that you can call like preventDefault(), stopPropagation(), and so on.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5494c0d3259" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>