<?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" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ example - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ example - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Wed, 26 Aug 2026 20:17:47 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/example/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ The Python Code Example Handbook ]]>
                </title>
                <description>
                    <![CDATA[ Very few programming languages are as universally loved as Python. The brainchild of Dutch programmer Guido van Rossum, Python is easy to learn, powerful, and an utter joy to work with. Thanks to its popularity, video and written resources about Pyth... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/the-python-code-example-handbook/</link>
                <guid isPermaLink="false">66b0ab5bb30dd4d00547bc18</guid>
                
                    <category>
                        <![CDATA[ beginners guide ]]>
                    </category>
                
                    <category>
                        <![CDATA[ example ]]>
                    </category>
                
                    <category>
                        <![CDATA[ handbook ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Farhan Hasin Chowdhury ]]>
                </dc:creator>
                <pubDate>Tue, 22 Aug 2023 21:54:38 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/08/Learn-Python-with-Code-Examples-Handbook-Cover.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Very few programming languages are as universally loved as Python. The brainchild of Dutch programmer Guido van Rossum, Python is easy to learn, powerful, and an utter joy to work with.</p>
<p>Thanks to its popularity, video and written resources about Python are plentiful. This handbook, however, tries to be a bit different by not being a definitive guide to the language.</p>
<p>Instead you'll learn about all the topics that I consider to be the language fundamentals with a lot of code examples.</p>
<p>I haven't discussed object-oriented programming in this handbook because I believe it to be a very broad subject deserving of its own separate handbook.</p>
<p>Near the end, I've also listed out some learning resources to further your knowledge of Python and programming in general.</p>
<p>Without any further ado, let's jump in!</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><a class="post-section-overview" href="#heading-prerequisites">Prerequisites</a></li>
<li><a class="post-section-overview" href="#heading-how-to-setup-python-on-your-computer">How to Setup Python on Your Computer</a></li>
<li><a class="post-section-overview" href="#heading-how-to-install-a-python-ide-on-your-computer">How to Install a Python IDE on Your Computer</a></li>
<li><a class="post-section-overview" href="#heading-how-to-create-a-new-project-on-pycharm">How to Create a New Project on PyCharm</a></li>
<li><a class="post-section-overview" href="#heading-how-to-write-the-hello-world-program-in-python">How to Write the Hello World Program in Python</a></li>
<li><a class="post-section-overview" href="#heading-how-to-initialize-and-publish-a-git-repository-from-pycharm">How to Initialize and Publish a Git Repository From PyCharm</a></li>
<li><a class="post-section-overview" href="#heading-how-to-work-with-variables-and-different-types-of-data-in-python">How to Work With Variables and Different Types of Data in Python</a></li>
<li><a class="post-section-overview" href="#heading-how-to-work-with-simple-numbers-in-python">How to Work With Simple Numbers in Python</a></li>
<li><a class="post-section-overview" href="#heading-how-to-take-inputs-from-users-in-python">How to Take Inputs From Users in Python</a></li>
<li><a class="post-section-overview" href="#heading-how-to-work-with-strings-in-python">How to Work With Strings in Python</a></li>
<li><a class="post-section-overview" href="#heading-what-are-the-sequence-types-in-python">What Are the Sequence Types in Python?</a><ul>
<li><a class="post-section-overview" href="#heading-lists-in-python">Lists in Python</a></li>
<li><a class="post-section-overview" href="#heading-tuples-in-python">Tuples in Python</a></li>
<li><a class="post-section-overview" href="#heading-ranges-in-python">Ranges in Python</a></li>
<li><a class="post-section-overview" href="#heading-how-indexing-works-in-python">How Indexing Works in Python</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-what-are-the-iterable-types-and-how-to-use-them-for-loops-in-python">What Are the Iterable Types and How to Use them for Loops in Python</a></li>
<li><a class="post-section-overview" href="#heading-how-to-use-while-loops-in-python">How to Use While Loops in Python</a></li>
<li><a class="post-section-overview" href="#heading-how-to-write-nested-loops-in-python">How to Write Nested Loops in Python</a></li>
<li><a class="post-section-overview" href="#heading-what-are-some-common-sequence-type-operations-in-python">What Are Some Common Sequence Type Operations in Python?</a><ul>
<li><a class="post-section-overview" href="#heading-how-to-use-the-in-operator-in-python">How to Use the in Operator in Python</a></li>
<li><a class="post-section-overview" href="#heading-how-to-use-the-and-operators-with-sequence-types-in-python">How to Use the + and * Operators with Sequence Types in Python</a></li>
<li><a class="post-section-overview" href="#heading-how-to-use-the-len-min-and-max-functions-in-python">How to Use the len(), min(), and max() Functions in Python</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-what-are-some-string-type-operations-in-python">What Are Some String Type Operations in Python?</a><ul>
<li><a class="post-section-overview" href="#heading-how-to-capitalize-strings-in-python">How to Capitalize Strings in Python</a></li>
<li><a class="post-section-overview" href="#heading-how-to-convert-strings-to-lower-case-or-upper-case-in-python">How to Convert Strings to Lower Case or Upper Case in Python</a></li>
<li><a class="post-section-overview" href="#heading-how-to-count-the-number-of-occurrences-of-a-substring-in-a-string-in-python">How to Count the Number of Occurrences of a Substring in a String in Python</a></li>
<li><a class="post-section-overview" href="#heading-how-to-split-and-join-strings-in-python">How to Split and Join Strings in Python</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-how-to-write-conditional-statements-in-python">How to Write Conditional Statements in Python</a></li>
<li><a class="post-section-overview" href="#heading-what-are-relational-and-logical-operators-in-python">What are Relational and Logical Operators in Python?</a></li>
<li><a class="post-section-overview" href="#heading-what-are-assignment-operators-in-python">What Are Assignment Operators in Python?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-the-set-type-in-python">What Is the Set Type in Python?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-the-mapping-type-in-python">What Is the Mapping Type in Python?</a><ul>
<li><a class="post-section-overview" href="#heading-what-are-dictionary-view-objects-in-python">What Are Dictionary View Objects in Python?</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-how-to-write-functions-in-python">How to Write Functions in Python</a><ul>
<li><a class="post-section-overview" href="#heading-how-to-write-anonymous-or-lambda-functions-in-python">How to Write Anonymous or Lambda Functions in Python</a></li>
<li><a class="post-section-overview" href="#heading-how-to-work-with-local-nonlocal-and-global-variables-in-python">How to Work with local, nonlocal and global Variables in Python</a></li>
<li><a class="post-section-overview" href="#heading-how-to-pass-a-variable-number-of-arguments-to-a-function-using-args-and-kwargs-in-python">How to Pass a Variable Number of Arguments to a Function Using <em>args and *</em>kwargs in Python</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-what-are-modules-in-python">What Are Modules in Python?</a></li>
<li><a class="post-section-overview" href="#heading-how-to-use-the-python-documentation-efficiently">How to Use the Python Documentation Efficiently</a></li>
<li><a class="post-section-overview" href="#heading-whats-next">What's Next?</a><ul>
<li><a class="post-section-overview" href="#heading-object-oriented-programming">Object Oriented Programming</a></li>
<li><a class="post-section-overview" href="#heading-algorithms-and-data-structures">Algorithms and Data Structures</a></li>
<li><a class="post-section-overview" href="#heading-django">Django</a></li>
<li><a class="post-section-overview" href="#heading-qt">Qt</a></li>
<li><a class="post-section-overview" href="#heading-pygame">PyGame</a></li>
<li><a class="post-section-overview" href="#heading-data-science">Data Science</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ul>
<h2 id="heading-prerequisites"><strong>Prerequisites</strong></h2>
<p>You don't need to know any other programming language for this book, but knowing one may help you understand the basics of Python.</p>
<p>Other than that you'll need to be efficient enough with your choice of operating system to download and install new software, and gain administrative access if needed.</p>
<h2 id="heading-how-to-setup-python-on-your-computer">How to Setup Python on Your Computer</h2>
<p>Installing Python on your computer is a very straightforward process. In fact, if you're on a Linux system, Python should already be installed.</p>
<p>Open up your terminal window and execute the following command:</p>
<pre><code>python --version
</code></pre><p>If Python is installed on your system, you'll get an output like <code>Python 3.10.4</code> or some other minor version.</p>
<p>Although most of the modern Linux distribution use Python 3 as default, some of the older distributions may still use Python 2 by default.</p>
<p>So if the aforementioned command refers to Python 2, try out the following command:</p>
<pre><code>python3 --version
</code></pre><p>I'd also suggest that you check for updates on your Linux distribution and install any new updates for Python.</p>
<p>Although Python comes preinstalled with macOS as well, I'd suggest that you follow this article by <a target="_blank" href="https://www.freecodecamp.org/news/author/dillionmegida/">Dillion Megida</a> and install a more recent version.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://www.freecodecamp.org/news/how-to-install-python-3-on-mac-and-update-the-python-version-macos-homebrew-command-guide/">https://www.freecodecamp.org/news/how-to-install-python-3-on-mac-and-update-the-python-version-macos-homebrew-command-guide/</a></div>
<p>Finally, for Windows, I'd suggest you follow an article by <a target="_blank" href="https://www.freecodecamp.org/news/author/fahimbinamin/">Md. Fahim Bin Amin</a> and properly install the latest version of Python.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://www.freecodecamp.org/news/how-to-install-python-in-windows-operating-system/">https://www.freecodecamp.org/news/how-to-install-python-in-windows-operating-system/</a></div>
<p>As long as you have a Python 3 version installed, you're good to go.</p>
<h2 id="heading-how-to-install-a-python-ide-on-your-computer">How to Install a Python IDE on Your Computer</h2>
<p>Much of your experience as a developer will depend on what program you've chosen to write your code in. A good integrated development environment (IDE) or Code Editor can really boost your productivity.</p>
<p>These days <a target="_blank" href="https://code.visualstudio.com/">Visual Studio Code</a> has become the go to code editor for all languages and platforms. But for the sake of simplicity, we'll use <a target="_blank" href="https://www.jetbrains.com/pycharm/">PyCharm</a> in this book.</p>
<p>If you'd like to use VS Code, have written a full-length article on <a target="_blank" href="https://www.freecodecamp.org/news/how-to-configure-visual-studio-code-for-python-development/">how to configure Visual Studio Code for Python development</a>. Feel free to check that out if you do not mind configuring your editor manually.</p>
<p>The professional edition of the IDE <a target="_blank" href="https://www.jetbrains.com/pycharm/buy/">can cost you $89.00 per year</a> but there is also a free and open-source community edition. Head over to the <a target="_blank" href="https://www.jetbrains.com/pycharm/download/">PyCharm download page</a>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/download-pycharm-page.png" alt="Image" width="600" height="400" loading="lazy">
<em>Download PyCharm page</em></p>
<p>Use the black "Download" button to download the community edition. The file size should be a little larger than 350 megabytes.</p>
<p>On Windows you'll get an executable installer, on macOS you'll get an Apple disc image, and on Linux you'll get a TAR archive.</p>
<p>I won't demonstrate the installation process in this book since it's similar to installing any other software on your machine.</p>
<p>Once installed, you can start the IDE from your start menu/app launcher. On your first launch, you'll be given the chance to configure a few things. I'd suggest you keep the defaults.</p>
<p>Once the configuration wizard ends, you should see the following welcome window:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/09/image-469.png" alt="Image" width="600" height="400" loading="lazy">
<em>Welcome to PyCharm screen - with options to start a new project, open a project, or get one from your VCS</em></p>
<p>Picking one IDE or code editor instead of the other one will not affect your experience with following this handbook, so feel free to use whatever you feel comfortable with.</p>
<h2 id="heading-how-to-create-a-new-project-on-pycharm">How to Create a New Project on PyCharm</h2>
<p>If you have the welcome window open from the previous section, click on the "New Project" button.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/start-a-new-project-in-pycharm.png" alt="Image" width="600" height="400" loading="lazy">
<em>Start a new project in PyCharm</em></p>
<p>In the next step, pick a location to store your project:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/09/image-472.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>In the location input box, the <code>HelloWorld</code> part is the name of the project. Then make sure you have "New environment using Virtualenv" selected. Then, make sure that the correct version of Python is selected from the "Base interpreter" dropdown.</p>
<p><a target="_blank" href="https://virtualenv.pypa.io/">Virtualenv</a> is a program that can create isolated Python environments from a given base interpreter. This is very helpful because later on when you'll work on multiple Python projects, their dependencies may conflict with each other.</p>
<p>Creating isolated environments for each project will solve that issue and it'll also keep your global Python installation free from any unnecessary package installation.</p>
<p>Since this may be your first Python project, I'd suggest you leave the "Create a main.py welcome script" option checked. Once you're happy with your choices, click the "Create" button.</p>
<p>The project creation process shouldn't take very long. Once it's done, the IDE should open the project automatically for you.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/09/image-473.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>You can use the play button at the top right corner to run the code. The button is configured to run the "main.py" file by default. </p>
<p>That's why you can see "main" written by its side. You can write your custom configuration as well, but that's a topic for a later section.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/09/image-474.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>You can see the output of your program at the bottom of the IDE. PyCharm comes with support for TODO comments, a built in terminal and more. You'll learn about a bunch of these features as you go forward.</p>
<h2 id="heading-how-to-write-the-hello-world-program-in-python">How to Write the Hello World Program in Python</h2>
<p>Continuing on from the last section, open up the "main.py" file and replace all the preexisting code with the following line of code:</p>
<pre><code class="lang-python">print(<span class="hljs-string">'Hello, World!'</span>)

<span class="hljs-comment"># Hello, World!</span>
</code></pre>
<p>The <code>print()</code> function prints out anything that you pass into the set of parenthesis. You don't have to name your Python file "main.py" specifically. It's just a way to let you know that this is the entry point to this program.</p>
<p>That's all you need to write the simplest executable program in Python. But there is even a better way to do it. Update the code as follows:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    print(<span class="hljs-string">'Hello, World!'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Hello, World!</span>
</code></pre>
<p>As you keep working on bigger projects, you'll eventually have more than one Python file in your project and this way of writing a script can be useful.</p>
<p>To simulate a bigger project, create another Python file by right clicking on the "HelloWorld" project name and selecting "Python File" under the "New" sub menu.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Name your file something like "library" and press enter while "Python file" is highlighted in the list of file types.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>A new file with the name "library.py" will show up on your project folder. Put the following line of code inside the file:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">greet</span>():</span>
    print(<span class="hljs-string">'Hello, World!'</span>)
</code></pre>
<p>This is a very simple function that prints out "Hello, World!" on the console. You can <code>import</code> and use this function in your "main.py" file.</p>
<p>To do so, update the code for "main.py" file as follows:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> library <span class="hljs-keyword">import</span> greet


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    greet()


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Hello, World!</span>
</code></pre>
<p>You're importing the <code>greet()</code> function from the "library.py" file and executing that inside the <code>main()</code> function.</p>
<p>Right now in your project, you have two types of Python file. You have the "main.py" file which is a script. In other words, you can run this file.</p>
<p>Then you have the "library.py" file which is a library. In other words, it houses a number of useful functions and variables that you can import inside other Python files.</p>
<p>Now imagine you have hundreds of files in your project and they more or less look the same. How would someone else find the entry point to the program?</p>
<p>The easiest way would be to perform a search for the line <code>if __name__ == '__main__'</code> on the entire project. This makes your code a lot more readable.</p>
<p>Now that I have you convinced that this is the way to go, let me explain what is actually going on here.</p>
<p>The <code>__name__</code> is a special Python variable. In case of a script, the value of this variable will be <code>__main__</code> and in case of a library, its value will be the name of that file.</p>
<p>So in the aforementioned program, the value of <code>__name__</code> inside the "main.py" file will be <code>__main__</code> and <code>library</code> inside the "library.py" file.</p>
<p>If you change the name of then "main.py" file to something else, the value will still be <code>__main__</code> because it's a script.</p>
<p>Nothing is stopping the "library.py" file from being a script, though. If you run that file instead, it'll become a script.</p>
<p>In languages like C/C++/Go/Java, you'll have a specified <code>main</code> function. That function will be the entry point to the program.</p>
<p>Since Python doesn't have anything like that, the usage of the <code>if __name__ == '__main__'</code> expression enforces a sense of a specified entry point to your program.</p>
<p>It tells the programmer and the IDE that this script is for execution (not for importing inside other Python files).</p>
<h2 id="heading-how-to-initialize-and-publish-a-git-repository-from-pycharm">How to Initialize and Publish a Git Repository From PyCharm</h2>
<p>You may already be familiar with <a target="_blank" href="https://git-scm.com/">Git</a> and know how to initialize a new repository. If you prefer using some other Git client, that's totally fine.</p>
<p>However I think knowing how to make commits right from your IDE can boost your productivity.</p>
<p>Keep in mind you'll need to have Git installed and configured on your system. If you don't have that, <a target="_blank" href="https://www.freecodecamp.org/news/git-first-time-setup/">this article</a> by <a target="_blank" href="https://www.freecodecamp.org/news/author/bolajiayodeji/">Bolaji Ayodeji</a> may come in handy.</p>
<p>Now, continuing on from the last section, if you look at the bottom of your IDE, you should see a "Version Control" tab.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-2-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Click on it and you should switch to the version control tab. Now click on the "Create Git repository..." link.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-3-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>PyCharm will ask you where you want to initialize the new repository. Make sure you're picking the right folder.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-4.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>As soon as you press the "OK" button, the "Version Control" tab will change to a "Git" tab.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-5-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>At it's current state, there are no commits. Before you make your first commit, I'd suggest you add a ".gitignore" file so that no unwanted file gets to the repository.</p>
<p>To generate a new gitignore file, head over to <a target="_blank" href="https://www.toptal.com/developers/gitignore/">gitignore.io</a> website. You can generate gitignore files for a large number of technologies from this website.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-6.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>You write the name of the technologies that you want to generate the file for. I usually go with "Python", "PyCharm" and hit the "Create" button.</p>
<p>The website will display the content of your desired ".gitignore" file. Select and copy everything from there and go back to PyCharm.</p>
<p>To simulate that, create a new file in your project by right clicking on the "HelloWorld" project name and selecting "File" under the "New" sub menu.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-7.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Name your file ".gitignore" and press enter. PyCharm will ask whether you want to add this file to Git or not. Click on Add and then paste the copied content.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-10.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>At this moment, your repository doesn't have any commits. To create a new commit, click on the "Commit local changes" link or switch to the "Commit" tab.</p>
<p>Since this is your first commit, check all "Changes" and "Unversioned Files" from the commit tab.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-11.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Since this is your first commit, put a descriptive commit message such as "Initial commit" and press the "Commit" button to finalize.</p>
<p>You've successfully made a commit to your local repository. You can now see all the commits under the master branch in detail.</p>
<p>Now it's time to publish this repository on GitHub. To do so, create a new repository under your GitHub account.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-14.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Then copy the SSH link to this repository. If you do not have SSH configured for your project, you may use the HTTPS link but I'd highly recommend SSH.</p>
<p>Now go back to PyCharm and look at the top right corner. Besides where it says Git, you'll find a few signs.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-15.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The downwards blue arrow will pull code from your remote repository, the tick sign will create a new commit, the upwards green arrow will push code.</p>
<p>The clock icon will show your commit history and finally the looped back arrow will revert your changes. Click on the push arrow and a new window will pop up.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-16.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Click on the "Define remote" link and inside the URL input box, paste the link you've copied from GitHub. Press the OK button and wait until the process ends.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-17.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>If everything goes fine, PyCharm will give you a "Push" button. It shouldn't take more than a few seconds to push the code to your remote repository.</p>
<p>If you're using HTTPS instead of SSH, you may have to provide your GitHub email and password on every push.</p>
<p>Once done, visit your remote repository and refresh the page to see if the changes have been pushed correctly or not.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-18.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Now you can commit and push your code to GitHub right from your IDE every time you make any significant change.</p>
<p>For example, delete the "library.py" file and update the code inside the "main.py" file to print out "Hello, World!" on the console.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    print(<span class="hljs-string">"Hello, World!"</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Hello, World!</span>
</code></pre>
<p>Once you've made the changes, switch to the commit tab and you'll see all the uncommitted changes.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-19.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Make sure you've checked all the changes you want to commit. Write a descriptive commit message.</p>
<p>Then instead of just committing, try the "Commit and Push..." button this time. A new window will show up.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-21.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>If everything looks good to you, click on the Push button and wait for the process to finish.</p>
<p>Remember, if you're using HTTPS you may have to reenter your email and password on every push.</p>
<p>You can check your remote repository on GitHub to make sure that the push has been done correctly.</p>
<p>You can do a lot more in terms of version controlling within PyCharm such as handling pull requests, but I'll leave those out for a later time.</p>
<h2 id="heading-how-to-work-with-variables-and-different-types-of-data-in-python">How to Work With Variables and Different Types of Data in Python</h2>
<p>A variable is an entity that can take on different values of different types. It's a named location in your computer's memory.</p>
<p>To create a new variable in Python, you just need to type out the name of the variable, followed by an equal sign and the value.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    book = <span class="hljs-string">'Dracula'</span>
    author = <span class="hljs-string">'Bram Stoker'</span>
    release_year = <span class="hljs-number">1897</span>
    goodreads_rating = <span class="hljs-number">4.01</span>

    print(book)
    print(author)
    print(release_year)
    print(goodreads_rating)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Dracula</span>
<span class="hljs-comment"># Bram Stoker</span>
<span class="hljs-comment"># 1897</span>
<span class="hljs-comment"># 4.01</span>
</code></pre>
<p>When it comes to naming your variable, the <a target="_blank" href="https://peps.python.org/pep-0008/#function-and-variable-names">PEP 8 - Style Guide for Python</a> says:</p>
<blockquote>
<p>Function names should be lowercase, with words separated by underscores as necessary to improve readability.</p>
</blockquote>
<p>And</p>
<blockquote>
<p>Variable names follow the same convention as function names.</p>
</blockquote>
<p>The <a target="_blank" href="https://peps.python.org/pep-0008/#names-to-avoid">guide also</a> says:</p>
<blockquote>
<p>Never use the characters ‘l’ (lowercase letter el), ‘O’ (uppercase letter oh), or ‘I’ (uppercase letter eye) as single character variable names. In some fonts, these characters are indistinguishable from the numerals one and zero. When tempted to use ‘l’, use ‘L’ instead.</p>
</blockquote>
<p>As long as you're keeping these guidelines in mind, declaring variables in Python is very straightforward.</p>
<p>Instead of declaring the variables in separate lines, you can declare them in one go as follows:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    book, author, release_year, goodreads_rating = <span class="hljs-string">'Dracula'</span>, <span class="hljs-string">'Bram Stoker'</span>, <span class="hljs-number">1897</span>, <span class="hljs-number">4.01</span>

    print(book)
    print(author)
    print(release_year)
    print(goodreads_rating)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Dracula</span>
<span class="hljs-comment"># Bram Stoker</span>
<span class="hljs-comment"># 1897</span>
<span class="hljs-comment"># 4.01</span>
</code></pre>
<p>All you have to do is write the individual variable names in a single line using commas as separators. </p>
<p>Then after the equal sign you have to write the corresponding values in the same order as their names again using commas as separators.</p>
<p>In fact, you can also print them all out in one go. The <code>print()</code> method can take multiple parameters separated by commas.</p>
<pre><code>def main():
    book, author, release_year, goodreads_rating = <span class="hljs-string">'Dracula'</span>, <span class="hljs-string">'Bram Stoker'</span>, <span class="hljs-number">1897</span>, <span class="hljs-number">4.01</span>

    print(book, author, release_year, goodreads_rating)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

# Dracula Bram Stoker <span class="hljs-number">1897</span> <span class="hljs-number">4.01</span>
</code></pre><p>These parameters are then printed on the terminal in a single line using spaces for separating each of them.</p>
<p>Speaking of the <code>print()</code> method, you can use the <code>+</code> sign to add variables with strings inside a print method:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    book, author, release_year, goodreads_rating = <span class="hljs-string">'Dracula'</span>, <span class="hljs-string">'Bram Stoker'</span>, <span class="hljs-number">1897</span>, <span class="hljs-number">4.01</span>

    print(book + <span class="hljs-string">' is a novel by '</span> + author + <span class="hljs-string">', published in '</span> + release_year + <span class="hljs-string">'. It has a rating of '</span> + goodreads_rating + <span class="hljs-string">' on goodreads.'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()


<span class="hljs-comment"># TypeError: can only concatenate str (not "int") to str</span>
</code></pre>
<p>If you try to run this code you'll get a <code>TypeError</code> that says Python can concatenate or add together strings not integers.</p>
<p>In the code snippet above, <code>book</code>, <code>author</code>, <code>release_year</code>, and <code>goodreads_rating</code> are all variables of different types.</p>
<p>The <code>book</code> and <code>author</code> variables are strings. The <code>release_year</code> is an integer and finally the <code>goodreads_rating</code> variable is a floating point number.</p>
<p>Whenever Python encounters a <code>+</code> sign in front of a numeric type, it assumes that the programmer may be performing an arithmetic operation.</p>
<p>The easiest way to solve this problem is to convert the numeric types to strings. You can do that by calling the <code>str()</code> method on the numeric variables.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    book, author, release_year, goodreads_rating = <span class="hljs-string">'Dracula'</span>, <span class="hljs-string">'Bram Stoker'</span>, <span class="hljs-number">1897</span>, <span class="hljs-number">4.01</span>

    print(book + <span class="hljs-string">' is a novel by '</span> + author + <span class="hljs-string">', published in '</span> + str(release_year) + <span class="hljs-string">'. It has a rating of '</span> + str(goodreads_rating) + <span class="hljs-string">' on goodreads.'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Dracula is a novel by Bram Stoker, published in 1897. It has a rating of 4.01 on goodreads.</span>
</code></pre>
<p>That's better – but you can make that line of code even more readable by using a f string.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    book, author, release_year, goodreads_rating = <span class="hljs-string">'Dracula'</span>, <span class="hljs-string">'Bram Stoker'</span>, <span class="hljs-number">1897</span>, <span class="hljs-number">4.01</span>

    print(<span class="hljs-string">f'<span class="hljs-subst">{book}</span> is a novel by <span class="hljs-subst">{author}</span>, published in <span class="hljs-subst">{release_year}</span>. It has a rating of <span class="hljs-subst">{goodreads_rating}</span> on goodreads.'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Dracula is a novel by Bram Stoker, published in 1897. It has a rating of 4.01 on goodreads.</span>
</code></pre>
<p>You can turn a regular string to a f string by putting a <code>f</code> in front of it and suddenly you can write variable names inside curly braces right within the string itself.</p>
<p>There is one last thing that's bugging me, and that's the length of the line of code itself. Fortunately you can split long strings into multiple shorter ones as follows:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    book, author, release_year, goodreads_rating = <span class="hljs-string">'Dracula'</span>, <span class="hljs-string">'Bram Stoker'</span>, <span class="hljs-number">1897</span>, <span class="hljs-number">4.01</span>

    print(<span class="hljs-string">f'<span class="hljs-subst">{book}</span> is a novel by <span class="hljs-subst">{author}</span>, published in <span class="hljs-subst">{release_year}</span>.'</span>
          <span class="hljs-string">f' It has a rating of <span class="hljs-subst">{goodreads_rating}</span> on goodreads.'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Dracula is a novel by Bram Stoker, published in 1897. It has a rating of 4.01 on goodreads.</span>
</code></pre>
<p>Now that's how a good piece of Python code should look. I'd suggest you try to make your code readable from the very beginning – you'll thank me later for that.</p>
<p>Other than <code>int</code> and <code>float</code>, there is another numeric type called <code>complex</code> in Python. It was specifically designed for dealing with numbers like <code>500+2j</code>.</p>
<p>There are also boolean data that can hold the value <code>True</code> or <code>False</code> and nothing else. You can actually ask Python questions and it'll answer in boolean.</p>
<p>Throughout this book you'll not see complex numbers in action and booleans will come into play much later. So for now, lets focus on simple numbers and strings.</p>
<h2 id="heading-how-to-work-with-simple-numbers-in-python">How to Work With Simple Numbers in Python</h2>
<p>Simple numbers in Python are of two types. Whole numbers are integers and numbers with floating points in them are floats.</p>
<p>In Python, you can represent integers using four different bases. These are decimal, hexadecimal, octal, and binary.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Base</td><td>Representation</td></tr>
</thead>
<tbody>
<tr>
<td>Decimal</td><td>404</td></tr>
<tr>
<td>Hexadecimal</td><td>0x194</td></tr>
<tr>
<td>Octal</td><td>0o624</td></tr>
<tr>
<td>Binary</td><td>0b000110010100</td></tr>
</tbody>
</table>
</div><p>So you can represent the value of 404 in hexadecimal, octal, or binary by prefixing the corresponding value with <code>0x</code>, <code>0o</code>, or <code>0b</code> respectively.</p>
<p>On the other hand you can represent floats with the precision of up to 15 significant digits in Python. Any digit after the 15th place may be inaccurate.</p>
<p>There are six different arithmetic operations that you can perform on any of the simple numeric types. The simplest of the bunch are addition and subtraction.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    num_1 = <span class="hljs-number">15</span>
    num_2 = <span class="hljs-number">12</span>

    print(<span class="hljs-string">f'sum of num_1 and num_2 is: <span class="hljs-subst">{num_1 + num_2}</span>'</span>)
    print(<span class="hljs-string">f'difference of num_1 and num_2 is: <span class="hljs-subst">{num_1 - num_2}</span>'</span>)

<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># sum of num_1 and num_2 is: 27</span>
<span class="hljs-comment"># difference of num_1 and num_2 is: 3</span>
</code></pre>
<p>In case of a subtraction operation, the result will be negative if the second operand is larger than the first one.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    num_1 = <span class="hljs-number">15</span>
    num_2 = <span class="hljs-number">12</span>

    print(<span class="hljs-string">f'difference of num_2 and num_1 is: <span class="hljs-subst">{num_2 - num_1}</span>'</span>)

<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># difference of num_2 and num_1 is: -3</span>
</code></pre>
<p>Similarly you can perform multiplication and division operations using their corresponding operators.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    num_1 = <span class="hljs-number">15</span>
    num_2 = <span class="hljs-number">12</span>

    print(<span class="hljs-string">f'product of num_1 and num_2 is: <span class="hljs-subst">{num_1 * num_2}</span>'</span>)
    print(<span class="hljs-string">f'quotient of num_1 and num_2 is: <span class="hljs-subst">{num_1 / num_2}</span>'</span>)
    print(<span class="hljs-string">f'floored quotient of num_1 and num_2 is: <span class="hljs-subst">{num_1 // num_2}</span>'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># product of num_1 and num_2 is: 180</span>
<span class="hljs-comment"># quotient of num_1 and num_2 is: 1.25</span>
<span class="hljs-comment"># floored quotient of num_1 and num_2 is: 1</span>
</code></pre>
<p>Keep in mind that you can not divide a number by zero in Python. If you attempt that, you'll get a <code>ZeroDivisionError</code> error (more on that later).</p>
<p>Output from a division operation will always be a float value, unless you perform a floored division by using two division operators.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    num_1 = <span class="hljs-number">15</span>
    num_2 = <span class="hljs-number">12</span>

    print(<span class="hljs-string">f'floored quotient of num_1 and num_2 is: <span class="hljs-subst">{num_1 // num_2}</span>'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># floored quotient of num_1 and num_2 is: 1</span>
</code></pre>
<p>In this case the result will be rounded off to the nearest integer low – so, for example, 0.25 will be lost. So only perform this operation when such loss of data is permissible.</p>
<p>The last operation to discuss is finding the remainder of a division operation.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    num_1 = <span class="hljs-number">15</span>
    num_2 = <span class="hljs-number">12</span>

    print(<span class="hljs-string">f'remainder of num_1 / num_2 is: <span class="hljs-subst">{num_1 % num_2}</span>'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># remainder of num_1 / num_2 is: 3</span>
</code></pre>
<p>This operation is also called a modulo or modulus operation. So if someone mentions the modulo or modulus operator, they're referring to the percent sign.</p>
<p>You can turn an unsigned number into a negative one just by adding a <code>-</code> sign in front of it. You can also freely convert between integer to float and vice versa.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    float_variable = <span class="hljs-number">1.25</span>
    integer_variable = <span class="hljs-number">55</span>

    print(<span class="hljs-string">f'<span class="hljs-subst">{float_variable}</span> converted to an integer is: <span class="hljs-subst">{int(float_variable)}</span>'</span>)
    print(<span class="hljs-string">f'<span class="hljs-subst">{integer_variable}</span> converted to a float is: <span class="hljs-subst">{float(integer_variable)}</span>'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># 1.25 converted to an integer is: 1</span>
<span class="hljs-comment"># 55 converted to a float is: 55.0</span>
</code></pre>
<p>Loss of data in case of a float to integer conversion is inevitable, so be careful. You can use the <code>int()</code> and <code>float()</code> methods on strings as well (more on that later).</p>
<p>Any arithmetic operation involving a float operand will always produce a float result, unless converted to integer explicitly.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    float_variable = <span class="hljs-number">5.0</span>
    integer_variable = <span class="hljs-number">55</span>

    print(<span class="hljs-string">f'the sum of <span class="hljs-subst">{float_variable}</span> and <span class="hljs-subst">{integer_variable}</span> is: <span class="hljs-subst">{float_variable + integer_variable}</span>'</span>)
    print(<span class="hljs-string">f'the sum of <span class="hljs-subst">{float_variable}</span> and <span class="hljs-subst">{integer_variable}</span> '</span>
          <span class="hljs-string">f'converted to integer is: <span class="hljs-subst">{int(float_variable + integer_variable)}</span>'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># the sum of 5.0 and 55 is: 60.0</span>
<span class="hljs-comment"># the sum of 5.0 and 55 converted to integer is: 60</span>
</code></pre>
<p>If you ever want to get the absolute value of a signed value you can do so using the <code>abs()</code> method.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    num_1 = <span class="hljs-number">-5.8</span>

    print(<span class="hljs-string">f'the absolute value of <span class="hljs-subst">{num_1}</span> is: <span class="hljs-subst">{abs(num_1)}</span>'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># the absolute value of -5.8 is: 5.8</span>
</code></pre>
<p>There is a similar method <code>pow(x, y)</code> that you can use to apply <code>x</code> as the power of <code>y</code> like this.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    x = <span class="hljs-number">2</span>
    y = <span class="hljs-number">3</span>

    print(<span class="hljs-string">f'<span class="hljs-subst">{<span class="hljs-number">2</span>}</span> to the power of <span class="hljs-subst">{<span class="hljs-number">3</span>}</span> is: <span class="hljs-subst">{pow(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>)}</span>'</span>)
    print(<span class="hljs-string">f'<span class="hljs-subst">{<span class="hljs-number">2</span>}</span> to the power of <span class="hljs-subst">{<span class="hljs-number">3</span>}</span> is: <span class="hljs-subst">{<span class="hljs-number">2</span> ** <span class="hljs-number">3</span>}</span>'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># 2 to the power of 3 is: 8</span>
<span class="hljs-comment"># 2 to the power of 3 is: 8</span>
</code></pre>
<p>You can perform the same operation using two multiplication operators but I always prefer the <code>pow()</code> method.</p>
<p>Finally there is the <code>divmod()</code> method that you can use to combine the division and modulo operation.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    num_1 = <span class="hljs-number">8</span>
    num_2 = <span class="hljs-number">2</span>

    print(<span class="hljs-string">f'division and modulus of <span class="hljs-subst">{num_1}</span> and <span class="hljs-subst">{num_2}</span> is: <span class="hljs-subst">{divmod(num_1, num_2)}</span>'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># division and modulus of 8 and 2 is: (4, 0)</span>
</code></pre>
<p>The method returns a tuple of numbers (more on that later). The first one is the result of the division and the second one is the result of the modulo operation.</p>
<p>These are the basic operations you can perform on simple numbers right from the get go. But you can do much more once you start to pull in the built-in modules.</p>
<h2 id="heading-how-to-take-inputs-from-users-in-python">How to Take Inputs From Users in Python</h2>
<p>Learning how to take input from a user is an important milestone because it lets you create programs that a human being can interact with.</p>
<p>Unlike many other programming languages, taking user inputs in Python is very straightforward.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    name = input(<span class="hljs-string">'What is your name? '</span>)

    print(<span class="hljs-string">f'Nice to meet you <span class="hljs-subst">{name}</span>'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># What is your name? Farhan</span>
<span class="hljs-comment"># Nice to meet you Farhan</span>
</code></pre>
<p>The built-in <code>input()</code> method does exactly what it sounds like. The method accepts a single parameter <code>prompt</code> which is of string type.</p>
<p>Whatever you write as the value of this parameter will be shown in the console – like in this case, "What is your name?" is the prompt.</p>
<p>Once the user writes something on the console and presses enter, the input method will return that as a string.</p>
<p>You can save that string to any variable like I've saved the name inside the <code>name</code> variable. Even if the user inputs a number, <code>input()</code> will return that as a string.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    name = input(<span class="hljs-string">'What is your name? '</span>)
    age = input(<span class="hljs-string">f'How old are you <span class="hljs-subst">{name}</span>? '</span>)
    current_year = input(<span class="hljs-string">f'What year is this again? '</span>)

    print(<span class="hljs-string">f'If my calculations are right, you were born in <span class="hljs-subst">{current_year - age}</span>'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># What is your name? Farhan</span>
<span class="hljs-comment"># How old are you Farhan? 27</span>
<span class="hljs-comment"># What year is this again? 2023</span>
<span class="hljs-comment"># TypeError: unsupported operand type(s) for -: 'str' and 'str'</span>
</code></pre>
<p>Even though Python is taking all the user inputs correctly, it fails to calculate the user's birth year because arithmetic operations are not a good fit for strings.</p>
<p>To solve this problem, you just have to convert the user inputs to numeric types using the <code>int()</code> or <code>float()</code> functions as needed.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    name = input(<span class="hljs-string">'What is your name? '</span>)
    age = int(input(<span class="hljs-string">f'How old are you <span class="hljs-subst">{name}</span>? '</span>))
    current_year = int(input(<span class="hljs-string">f'What year is this again? '</span>))

    print(<span class="hljs-string">f'If my calculations are right, you were born in <span class="hljs-subst">{current_year - age}</span>'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># What is your name? Farhan</span>
<span class="hljs-comment"># How old are you Farhan? 27</span>
<span class="hljs-comment"># What year is this again? 2023</span>
<span class="hljs-comment"># If my calculations are right, you were born in 1996</span>
</code></pre>
<p>There you go, works like a charm. You can perform this conversion at any point in the code. It's not mandatory to convert them right at the beginning.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    temperature_in_celsius = input(<span class="hljs-string">'What is the temperature in celsius? '</span>)

    temperature_in_fahrenheit = (float(temperature_in_celsius) * <span class="hljs-number">1.8</span>) + <span class="hljs-number">32</span>

    print(<span class="hljs-string">f'<span class="hljs-subst">{temperature_in_celsius}</span> degree celsius is equivalent to <span class="hljs-subst">{temperature_in_fahrenheit}</span> degree fahrenheit.'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># What is the temperature in celsius? 32</span>
<span class="hljs-comment"># 32 degree celsius is equivalent to 89.6 degree fahrenheit.</span>
</code></pre>
<p>This program can convert temperature from Celsius to Fahrenheit. In this program, I didn't convert the input from string to a numeric type right away.</p>
<p>I performed the conversion during the calculation leaving the original input variable intact. Also notice the use of <code>float()</code> instead of the <code>int()</code> function.</p>
<h2 id="heading-how-to-work-with-strings-in-python">How to Work With Strings in Python</h2>
<p>You've already seen examples of strings in the previous sections – but there is a lot more that you need to learn about strings.</p>
<p>In Python, anything enclosed within a set of single, double, or triple quotes is a string. These are sequences of bytes representing Unicode characters.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    book = <span class="hljs-string">'Dracula'</span>
    author = <span class="hljs-string">"Bram Stoker"</span>

    print(<span class="hljs-string">'Title:'</span>, book)
    print(<span class="hljs-string">'Author:'</span>, author)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Title: Dracula</span>
<span class="hljs-comment"># Author: Bram Stoker</span>
</code></pre>
<p>Declaring a string with single or double quotes makes no difference whatsoever. But based on the scenario, you may have to choose on over the other.</p>
<p>For example, if you have an apostrophe within your sentence, you may want to use double quotes.</p>
<pre><code>def main():
    question = <span class="hljs-string">"What's your name?"</span>

    print(question)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

# What<span class="hljs-string">'s your name?</span>
</code></pre><p>The opposite can also occur. For example, when you have a direct quote within your string:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    sentence = <span class="hljs-string">'Harriet Jacobs writes, "She sat down, quivering in every limb"'</span>

    print(sentence)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Harriet Jacobs writes, "She sat down, quivering in every limb"</span>
</code></pre>
<p>You can also go for <a target="_blank" href="https://www.freecodecamp.org/news/escape-sequences-python/">escape sequences</a> if you want to, but the <a target="_blank" href="https://peps.python.org/pep-0008/#string-quotes">PEP 8 - Style Guide for Python Code</a> recommends avoiding the usage of back slashes within strings.</p>
<p>Triple quotes are a different case altogether. You can put multi-line strings within triple quotes and Python will preserve the white spaces as well.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    synopsis = <span class="hljs-string">"""Dracula comprises journal entries, letters, and telegrams written by the main characters.
It begins with Jonathan Harker, a young English lawyer, as he travels to Transylvania.
Harker plans to meet with Count Dracula, a client of his firm, in order to finalize a property transaction.
When he arrives in Transylvania, the locals react with terror after he discloses his destination: Castle Dracula.
Though this unsettles him slightly, he continues onward.
The ominous howling of wolves rings through the air as he arrives at the castle.
When Harker meets Dracula, he acknowledges that the man is pale, gaunt, and strange.
Harker becomes further concerned when, after Harker cuts himself while shaving, Dracula lunges at his throat.
Soon after, Harker is seduced by three female vampires, from whom he barely escapes.
He then learns Dracula’s secret—that he is a vampire and survives by drinking human blood.
Harker correctly assumes that he is to be the count’s next victim.
He attacks the count, but his efforts are unsuccessful.
Dracula leaves Harker trapped in the castle and then, along with 50 boxes of dirt, departs for England."""</span>

    print(<span class="hljs-string">'Synopsis:'</span>, synopsis)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Synopsis: Dracula comprises journal entries, letters, and telegrams written by the main characters.</span>
<span class="hljs-comment"># It begins with Jonathan Harker, a young English lawyer, as he travels to Transylvania.</span>
<span class="hljs-comment"># Harker plans to meet with Count Dracula, a client of his firm, in order to finalize a property transaction.</span>
<span class="hljs-comment"># When he arrives in Transylvania, the locals react with terror after he discloses his destination: Castle Dracula.</span>
<span class="hljs-comment"># Though this unsettles him slightly, he continues onward.</span>
<span class="hljs-comment"># The ominous howling of wolves rings through the air as he arrives at the castle.</span>
<span class="hljs-comment"># When Harker meets Dracula, he acknowledges that the man is pale, gaunt, and strange.</span>
<span class="hljs-comment"># Harker becomes further concerned when, after Harker cuts himself while shaving, Dracula lunges at his throat.</span>
<span class="hljs-comment"># Soon after, Harker is seduced by three female vampires, from whom he barely escapes.</span>
<span class="hljs-comment"># He then learns Dracula’s secret—that he is a vampire and survives by drinking human blood.</span>
<span class="hljs-comment"># Harker correctly assumes that he is to be the count’s next victim.</span>
<span class="hljs-comment"># He attacks the count, but his efforts are unsuccessful.</span>
<span class="hljs-comment"># Dracula leaves Harker trapped in the castle and then, along with 50 boxes of dirt, departs for England.</span>
</code></pre>
<p>So if you ever want to print out a multi line string while preserving the white spaces, go for triple quotes.</p>
<p>You can declare a triple quoted string using three single quotes but the <a target="_blank" href="https://peps.python.org/pep-0008/#string-quotes">PEP 8 - Style Guide for Python Code</a> recommends the usage of three double quotes.</p>
<p>There is a lot more to learn about strings, but I'd like to introduce you to some other sequence types in Python.</p>
<h2 id="heading-what-are-the-sequence-types-in-python">What Are the Sequence Types in Python?</h2>
<p>In Python, there are three sequence types. They are lists, tuples, and ranges. I'll start with the lists because it's probably the most utilized sequence type in Python.</p>
<h3 id="heading-lists-in-python">Lists in Python</h3>
<p>A list in Python is exactly what it sounds like: a collection of data stored sequentially on the computer's memory.</p>
<p>You can create a new list in Python by writing out its name followed by an equal sign, followed by the values to store enclosed in square brackets:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    horror_books = [<span class="hljs-string">'Dracula'</span>, <span class="hljs-string">'Carmilla'</span>, <span class="hljs-string">'The Imago Sequence'</span>]

    print(horror_books)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># ['Dracula', 'Carmilla', 'The Imago Sequence']</span>
</code></pre>
<p>In this example, <code>horror_books</code> is a list of strings. But you can create lists of integers, floats, or even of mixed types.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    a_random_list = [<span class="hljs-string">'Dracula'</span>, <span class="hljs-number">1</span>, <span class="hljs-number">5.7</span>, <span class="hljs-string">'Carmilla'</span>]

    print(a_random_list)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># ['Dracula', 1, 5.7, 'Carmilla']</span>
</code></pre>
<p>Though this is perfectly valid, you may find yourself creating lists of the same types more often.</p>
<p>Lists in Python are mutable. This means you can modify a list after its creation. For example, you can use the <code>pop()</code> method to get rid of the last value in a list.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    horror_books = [<span class="hljs-string">'Dracula'</span>, <span class="hljs-string">'Carmilla'</span>, <span class="hljs-string">'The Imago Sequence'</span>]

    print(horror_books.pop())
    print(horror_books)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># The Imago Sequence</span>
<span class="hljs-comment"># ['Dracula', 'Carmilla']</span>
</code></pre>
<p>As you can see, the <code>pop()</code> method returns the last value from the list and gets rid of it. Like <code>pop()</code> there is the <code>append()</code> method for inserting new item to the list.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    horror_books = [<span class="hljs-string">'Dracula'</span>, <span class="hljs-string">'Carmilla'</span>, <span class="hljs-string">'The Imago Sequence'</span>]

    print(horror_books)

    horror_books.append(<span class="hljs-string">'The Exorcist'</span>)

    print(horror_books)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># ['Dracula', 'Carmilla', 'The Imago Sequence']</span>
<span class="hljs-comment"># ['Dracula', 'Carmilla', 'The Imago Sequence', 'The Exorcist']</span>
</code></pre>
<p>As you can see from the method name, it adds the new item at the end of the list. Given their mutable nature, lists can also be sorted.</p>
<p>Feel free to check out the following article written by my colleague <a target="_blank" href="https://www.freecodecamp.org/news/author/dionysia/">Dionysia Lemonaki</a> here on freeCodeCamp about how to sort lists in Python:</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://www.freecodecamp.org/news/python-sort-how-to-sort-a-list-in-python/">https://www.freecodecamp.org/news/python-sort-how-to-sort-a-list-in-python/</a></div>
<h3 id="heading-tuples-in-python">Tuples in Python</h3>
<p>Lists are not the only sequence type in Python. The closest sibling of lists in Python are tuples.</p>
<p>You can create a new tuple in Python by writing out its name followed by an equal sign, then enclosing inside a pair of parenthesis the values you want to store.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    horror_books = (<span class="hljs-string">'Dracula'</span>, <span class="hljs-string">'Carmilla'</span>, <span class="hljs-string">'The Imago Sequence'</span>)

    print(horror_books)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># ('Dracula', 'Carmilla', 'The Imago Sequence')</span>
</code></pre>
<p>Just like lists, you can also mix and match different types of data within a single tuple as you see fit.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    a_random_list = (<span class="hljs-string">'Dracula'</span>, <span class="hljs-number">1</span>, <span class="hljs-number">5.7</span>, <span class="hljs-string">'Carmilla'</span>)

    print(a_random_list)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># ('Dracula', 1, 5.7, 'Carmilla')</span>
</code></pre>
<p>The most glaring dissimilarity between a list and a tuple is the fact that a tuple is immutable. So there's no popping and appending for us this time.</p>
<h3 id="heading-ranges-in-python">Ranges in Python</h3>
<p>The final sequence type that you're going to learn about in this section is a range. A range in Python is just a range of numbers.</p>
<p>You can create a range by calling the <code>range()</code> method and it'll return a range of numbers. You can call the method in a few different ways.</p>
<p>The most common is by passing a single number as a parameter. In this case, the method will treat that number as the end of the range and 0 as the start.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    a_range = range(<span class="hljs-number">10</span>)

    print(a_range)

    list_a_range = list(a_range)

    print(list_a_range)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># range(0, 10)</span>
<span class="hljs-comment"># [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]</span>
<span class="hljs-comment"># (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)</span>
</code></pre>
<p>Printing out a range as is won't give you much information. You'll have to convert the range to a list or a tuple by either calling the <code>list()</code> or <code>tuple()</code> method.</p>
<p>Once converted, you can then print out the entire range to the console. Notice how 10 or the number passed to the <code>range()</code> method is not included in the range.</p>
<p>The second way of calling the method is by supplying both the starting and ending numbers for the range.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    a_range = range(<span class="hljs-number">5</span>, <span class="hljs-number">15</span>)

    print(a_range)

    list_a_range = list(a_range)

    print(list_a_range)

    tuple_a_range = tuple(a_range)

    print(tuple_a_range)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># range(5, 15)</span>
<span class="hljs-comment"># [5, 6, 7, 8, 9, 10, 11, 12, 13, 14]</span>
<span class="hljs-comment"># (5, 6, 7, 8, 9, 10, 11, 12, 13, 14)</span>
</code></pre>
<p>Once again, the number you pass as the ending for the range will not be included in the resultant range.</p>
<p>The third and final way to call the method is by also defining a step. For example, imagine you want a range comprising of all the odd numbers within 1 to 10.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    a_range = range(<span class="hljs-number">1</span>, <span class="hljs-number">10</span>, <span class="hljs-number">2</span>)

    print(a_range)

    list_a_range = list(a_range)

    print(list_a_range)

    tuple_a_range = tuple(a_range)

    print(tuple_a_range)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># range(1, 10, 2)</span>
<span class="hljs-comment"># [1, 3, 5, 7, 9]</span>
<span class="hljs-comment"># (1, 3, 5, 7, 9)</span>
</code></pre>
<p>Since the value of step is 2 in this case, the range will begin with 1 but then skip every second number.</p>
<p>It may take some time to wrap your head around this concept but practicing with different step values will help.</p>
<p>Or you can read the following article written by <a target="_blank" href="https://www.freecodecamp.org/news/author/bala-priya/">Bala Priya C</a>:</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://www.freecodecamp.org/news/python-range-function-explained-with-code-examples/">https://www.freecodecamp.org/news/python-range-function-explained-with-code-examples/</a></div>
<h3 id="heading-how-indexing-works-in-python">How Indexing Works in Python</h3>
<p>One of the most important concepts regarding sequence types that you need to understand is indexing.</p>
<p>You see, each element in a sequence has a number attached to it that expresses its position in the list called an index. These indices are 0 based.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/horror-books-list.svg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>This diagram represents our list of horror books. The index of the first book is 0 – this means that the first element is at the 0th place.</p>
<p>The second one is at the 1st place and the third one is at the 2nd place. This zero-based indexing is may seem confusing at first but you'll get the hang of it.</p>
<p>The most basic usage of a index is to access its corresponding value from the sequence.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    horror_books = [<span class="hljs-string">'Dracula'</span>, <span class="hljs-string">'Carmilla'</span>, <span class="hljs-string">'The Imago Sequence'</span>]

    print(horror_books[<span class="hljs-number">0</span>])
    print(horror_books[<span class="hljs-number">1</span>])
    print(horror_books[<span class="hljs-number">2</span>])


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Dracula</span>
<span class="hljs-comment"># Carmilla</span>
<span class="hljs-comment"># The Imago Sequence</span>
</code></pre>
<p>You can also use negative numbers as indices but in that case the counting will start from the end.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    books = [<span class="hljs-string">'Dracula'</span>, <span class="hljs-string">'Frankenstein'</span>, <span class="hljs-string">'The Omen'</span>, <span class="hljs-string">'The Exorcist'</span>, <span class="hljs-string">'The Legend of Sleepy Hollow'</span>,
             <span class="hljs-string">'And Then There Were None'</span>, <span class="hljs-string">'The ABC Murders'</span>, <span class="hljs-string">'The Valley of Fear'</span>]

    print(books[<span class="hljs-number">0</span>])

    print(books[<span class="hljs-number">1</span>])
    print(books[<span class="hljs-number">-1</span>])

    print(books[<span class="hljs-number">2</span>])
    print(books[<span class="hljs-number">-2</span>])


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Dracula</span>

<span class="hljs-comment"># Frankenstein</span>
<span class="hljs-comment"># The Valley of Fear</span>

<span class="hljs-comment"># The Omen</span>
<span class="hljs-comment"># The ABC Murders</span>
</code></pre>
<p>The 0th element in a list will always be the first one. Now if you access the element on the 1st position you get "Frankenstein".</p>
<p>But if you try to access the element on the -1st position, you get "The Valley of Fear" because that's the second item in reverse.</p>
<p>The element on the 2nd position is "The Omen" but the element at the -2nd position is "The ABC Murders" because that's the third item in reverse.</p>
<p>If you're finding it hard to wrap your head around, imagine the list like a clock.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/list-clock.svg" alt="Image" width="600" height="400" loading="lazy">
<em>Zero-based indexing represented as a circular diagram like a clock</em></p>
<p>Here the outer number is the negative index and the inner number is the positive index. If you try to match the outputs against this imaginary clock, it should be easier to understand.</p>
<h2 id="heading-what-are-the-iterable-types-and-how-to-use-them-for-loops-in-python">What Are the Iterable Types and How to Use them for Loops in Python</h2>
<p>So far you've learned about creating collections of data and accessing them one by one. That's cool but there is something cooler.</p>
<p>Imagine you have a list or some other type of that contains a bunch of numbers.</p>
<p>Now you want to multiply each number in that list by two, insert the multiplied numbers in a new list, and print out the list on the terminal.</p>
<p>This is an excellent use case for the <code>for</code> statement in Python. Let's begin by first iterating through each number in a given list.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    random_numbers = [<span class="hljs-number">6</span>, <span class="hljs-number">1</span>, <span class="hljs-number">3</span>, <span class="hljs-number">8</span>, <span class="hljs-number">0</span>, <span class="hljs-number">9</span>, <span class="hljs-number">12</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">0</span>, <span class="hljs-number">54</span>, <span class="hljs-number">8</span>, <span class="hljs-number">100</span>, <span class="hljs-number">55</span>, <span class="hljs-number">60</span>, <span class="hljs-number">70</span>, <span class="hljs-number">85</span>]

    <span class="hljs-keyword">for</span> number <span class="hljs-keyword">in</span> random_numbers:
        print(number)

<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># 6</span>
<span class="hljs-comment"># 1</span>
<span class="hljs-comment"># 3</span>
<span class="hljs-comment"># 8</span>
<span class="hljs-comment"># 0</span>
<span class="hljs-comment"># 9</span>
<span class="hljs-comment"># 12</span>
<span class="hljs-comment"># 3</span>
<span class="hljs-comment"># 4</span>
<span class="hljs-comment"># 0</span>
<span class="hljs-comment"># 54</span>
<span class="hljs-comment"># 8</span>
<span class="hljs-comment"># 100</span>
<span class="hljs-comment"># 55</span>
<span class="hljs-comment"># 60</span>
<span class="hljs-comment"># 70</span>
<span class="hljs-comment"># 85</span>
</code></pre>
<p>You start by writing out the word <code>for</code> followed by a variable name. I've used <code>number</code> but you can use anything that makes sense to you.</p>
<p>Although you write it as <code>for number</code>, Python reads it as <code>for each number</code> and wonders where are these numbers staying?</p>
<p>That's when you say <code>in</code> followed by the name of the sequence, <code>random_numbers</code> in this case.</p>
<p>Now Python understands that you want to do something with each number in the <code>random_numbers</code> sequence, but what?</p>
<p>That's what you have to write out after the colon and be very careful about the indentation. Anything indented one level after the for loop declaration is considered the loop body.</p>
<p>Inside the for loop you can write whatever you want to do with the current value of the <code>number</code> variable.</p>
<p>Since there are 17 numbers in the sequence, the loop will run 17 times and each time it'll have a new value.</p>
<p>It'll start at index 0 which has the value of 6 and go through index 1, 2, 3, 4, 5, and so on. </p>
<p>On each iteration, it'll save the value of the index it's currently working on inside the <code>number</code> variable and print it out. Hence you get the long list of numbers.</p>
<p>Instead of printing out the original value, you can multiply it by 2 and print out the resultant value instead.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    random_numbers = [<span class="hljs-number">6</span>, <span class="hljs-number">1</span>, <span class="hljs-number">3</span>, <span class="hljs-number">8</span>, <span class="hljs-number">0</span>, <span class="hljs-number">9</span>, <span class="hljs-number">12</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">0</span>, <span class="hljs-number">54</span>, <span class="hljs-number">8</span>, <span class="hljs-number">100</span>, <span class="hljs-number">55</span>, <span class="hljs-number">60</span>, <span class="hljs-number">70</span>, <span class="hljs-number">85</span>]

    <span class="hljs-keyword">for</span> number <span class="hljs-keyword">in</span> random_numbers:
        print(number * <span class="hljs-number">2</span>)

<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># 12</span>
<span class="hljs-comment"># 2</span>
<span class="hljs-comment"># 6</span>
<span class="hljs-comment"># 16</span>
<span class="hljs-comment"># 0</span>
<span class="hljs-comment"># 18</span>
<span class="hljs-comment"># 24</span>
<span class="hljs-comment"># 6</span>
<span class="hljs-comment"># 8</span>
<span class="hljs-comment"># 0</span>
<span class="hljs-comment"># 108</span>
<span class="hljs-comment"># 16</span>
<span class="hljs-comment"># 200</span>
<span class="hljs-comment"># 110</span>
<span class="hljs-comment"># 120</span>
<span class="hljs-comment"># 140</span>
<span class="hljs-comment"># 170</span>
</code></pre>
<p>Now you're getting the multiplied values. The final task is to insert these multiplied values in a new list and print out the new list itself.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    random_numbers = [<span class="hljs-number">6</span>, <span class="hljs-number">1</span>, <span class="hljs-number">3</span>, <span class="hljs-number">8</span>, <span class="hljs-number">0</span>, <span class="hljs-number">9</span>, <span class="hljs-number">12</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">0</span>, <span class="hljs-number">54</span>, <span class="hljs-number">8</span>, <span class="hljs-number">100</span>, <span class="hljs-number">55</span>, <span class="hljs-number">60</span>, <span class="hljs-number">70</span>, <span class="hljs-number">85</span>]
    multiplied_random_numbers = []

    <span class="hljs-keyword">for</span> number <span class="hljs-keyword">in</span> random_numbers:
        multiplied_random_numbers.append(number * <span class="hljs-number">2</span>)

    print(multiplied_random_numbers)

<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># [12, 2, 6, 16, 0, 18, 24, 6, 8, 0, 108, 16, 200, 110, 120, 140, 170]</span>
</code></pre>
<p>For that you'll need an empty list. Then, after multiplying the number, you can simply call the <code>append()</code> method on the new list and pass the multiplied value.</p>
<p>Finally, make sure that you're putting the print statement outside of the loop body otherwise you'll end up printing out the list 17 times.</p>
<p>The <code>for</code> loop works with all the sequence types and any iterable type in the Python language. What is an iterable type, I hear you ask.</p>
<p>Well, any object that has the <code>__iter__()</code> method is considered an iterable in Python.</p>
<p>You can call the <code>dir()</code> function on any object to list out all its methods and properties. Take the <code>random_numbers</code> list as an example.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    random_numbers = [<span class="hljs-number">6</span>, <span class="hljs-number">1</span>, <span class="hljs-number">3</span>, <span class="hljs-number">8</span>, <span class="hljs-number">0</span>, <span class="hljs-number">9</span>, <span class="hljs-number">12</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">0</span>, <span class="hljs-number">54</span>, <span class="hljs-number">8</span>, <span class="hljs-number">100</span>, <span class="hljs-number">55</span>, <span class="hljs-number">60</span>, <span class="hljs-number">70</span>, <span class="hljs-number">85</span>]

    print(dir(random_numbers))

<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># ['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']</span>
</code></pre>
<p>You can see some familiar methods such as <code>append</code>, <code>count</code>, and <code>index</code> but most importantly it has the <code>__iter__</code> method.</p>
<p>As you keep working in Python you'll eventually remember the types supported by the <code>for</code> loop but you can always use the <code>dir()</code> method on a object to find out.</p>
<h2 id="heading-how-to-use-while-loops-in-python">How to Use While Loops in Python</h2>
<p>There is another type of loop in Python known as the <code>while</code> loop. Unlike <code>for</code>, a <code>while</code> loop can execute a statement as long as a given condition evaluates to <code>true</code>.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    number = <span class="hljs-number">1</span>
    <span class="hljs-keyword">while</span> number &lt; <span class="hljs-number">11</span>:
        print(number)
        number += <span class="hljs-number">1</span>

<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># 1</span>
<span class="hljs-comment"># 2</span>
<span class="hljs-comment"># 3</span>
<span class="hljs-comment"># 4</span>
<span class="hljs-comment"># 5</span>
<span class="hljs-comment"># 6</span>
<span class="hljs-comment"># 7</span>
<span class="hljs-comment"># 8</span>
<span class="hljs-comment"># 9</span>
<span class="hljs-comment"># 10</span>
</code></pre>
<p>Here you have a variable <code>number</code> with the value <code>11</code> and a <code>while</code> loop that prints out the value of number, then increases it by 1.</p>
<p>A <code>while</code> loop starts by writing out <code>while</code> followed by the condition. Then you write the loop body starting from the next line after the colon.</p>
<p><code>for</code> loops are useful when you're trying to access every element inside an iterable. <code>while</code> loops are useful when you want to repeat the same set of instructions an arbitrary number of times.</p>
<p>The line <code>number += 1</code> is another way to write <code>number = number + 1</code> and it's very commonly used by programmers across different programming languages.</p>
<h2 id="heading-how-to-write-nested-loops-in-python">How to Write Nested Loops in Python</h2>
<p>You can also nest one loop inside another. For example, look at the following code that prints out multiplication tables:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    <span class="hljs-keyword">for</span> x <span class="hljs-keyword">in</span> range(<span class="hljs-number">1</span>, <span class="hljs-number">6</span>):
        print()
        <span class="hljs-keyword">for</span> y <span class="hljs-keyword">in</span> range(<span class="hljs-number">1</span>, <span class="hljs-number">11</span>):
            print(<span class="hljs-string">f"<span class="hljs-subst">{x}</span> x <span class="hljs-subst">{y}</span> = <span class="hljs-subst">{x * y}</span>"</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment">#</span>
<span class="hljs-comment"># 1 x 1 = 1</span>
<span class="hljs-comment"># 1 x 2 = 2</span>
<span class="hljs-comment"># 1 x 3 = 3</span>
<span class="hljs-comment"># 1 x 4 = 4</span>
<span class="hljs-comment"># 1 x 5 = 5</span>
<span class="hljs-comment"># 1 x 6 = 6</span>
<span class="hljs-comment"># 1 x 7 = 7</span>
<span class="hljs-comment"># 1 x 8 = 8</span>
<span class="hljs-comment"># 1 x 9 = 9</span>
<span class="hljs-comment"># 1 x 10 = 10</span>
<span class="hljs-comment">#</span>
<span class="hljs-comment"># 2 x 1 = 2</span>
<span class="hljs-comment"># 2 x 2 = 4</span>
<span class="hljs-comment"># 2 x 3 = 6</span>
<span class="hljs-comment"># 2 x 4 = 8</span>
<span class="hljs-comment"># 2 x 5 = 10</span>
<span class="hljs-comment"># 2 x 6 = 12</span>
<span class="hljs-comment"># 2 x 7 = 14</span>
<span class="hljs-comment"># 2 x 8 = 16</span>
<span class="hljs-comment"># 2 x 9 = 18</span>
<span class="hljs-comment"># 2 x 10 = 20</span>
<span class="hljs-comment">#</span>
<span class="hljs-comment"># 3 x 1 = 3</span>
<span class="hljs-comment"># 3 x 2 = 6</span>
<span class="hljs-comment"># 3 x 3 = 9</span>
<span class="hljs-comment"># 3 x 4 = 12</span>
<span class="hljs-comment"># 3 x 5 = 15</span>
<span class="hljs-comment"># 3 x 6 = 18</span>
<span class="hljs-comment"># 3 x 7 = 21</span>
<span class="hljs-comment"># 3 x 8 = 24</span>
<span class="hljs-comment"># 3 x 9 = 27</span>
<span class="hljs-comment"># 3 x 10 = 30</span>
<span class="hljs-comment">#</span>
<span class="hljs-comment"># 4 x 1 = 4</span>
<span class="hljs-comment"># 4 x 2 = 8</span>
<span class="hljs-comment"># 4 x 3 = 12</span>
<span class="hljs-comment"># 4 x 4 = 16</span>
<span class="hljs-comment"># 4 x 5 = 20</span>
<span class="hljs-comment"># 4 x 6 = 24</span>
<span class="hljs-comment"># 4 x 7 = 28</span>
<span class="hljs-comment"># 4 x 8 = 32</span>
<span class="hljs-comment"># 4 x 9 = 36</span>
<span class="hljs-comment"># 4 x 10 = 40</span>
<span class="hljs-comment">#</span>
<span class="hljs-comment"># 5 x 1 = 5</span>
<span class="hljs-comment"># 5 x 2 = 10</span>
<span class="hljs-comment"># 5 x 3 = 15</span>
<span class="hljs-comment"># 5 x 4 = 20</span>
<span class="hljs-comment"># 5 x 5 = 25</span>
<span class="hljs-comment"># 5 x 6 = 30</span>
<span class="hljs-comment"># 5 x 7 = 35</span>
<span class="hljs-comment"># 5 x 8 = 40</span>
<span class="hljs-comment"># 5 x 9 = 45</span>
<span class="hljs-comment"># 5 x 10 = 50</span>
</code></pre>
<p>To be honest, this is a very simple bit of code that makes use of a lot of the things you've already learned in this handbook.</p>
<p>To create a multiplication table we need two operands: one remains constant for the entire table and the other increases by 1 until it reaches 10. </p>
<p>Here, <code>x</code> represents the left operand or the constant one and <code>y</code> represents the right operand or the variable one.</p>
<p>The first loop iterates through a range of 1 to 5 and the second loop iterates through a range of 1 to 10.</p>
<p>Since the ending number of a range is exclusive, you need to put a number that is 1 higher than the desired ending number.</p>
<p>First the Python interpreter encounters the outer loop and starts executing it. While inside that loop, the value of <code>x</code> is 1.</p>
<p>The interpreter then encounters the inner loop and starts executing that. While inside the inner loop, the value of <code>x</code> remains 1 but the value of <code>y</code> increases in each iteration.</p>
<p>The inner loop is the body of the outer loop in this case, so the first iteration of the outer loop lasts until the inner loop finishes.</p>
<p>After finishing 10 iterations of the inner loop, the interpreter comes back to the outer loop and starts executing it once again.</p>
<p>This time the value of <code>x</code> becomes 2 since that's what comes next in the range.</p>
<p>Just like that, the outer loop executes 5 times and the inner loop executes 10 times for each of those iterations.</p>
<p>Like a lot of other concepts, wrapping your head around nested loops can be difficult, but practice will make things easier.</p>
<p>I'd suggest you go ahead and implement this program using <code>while</code> loops to test your understanding.</p>
<p>You can also take the two numbers from the user and print the multiplication table within that range.</p>
<p>For example, if the user puts 5 and 10 as inputs, then you'll print out the multiplication tables of all the numbers from 5 to 10.</p>
<p>You can nest loops to even deeper levels, but going deeper than two loops may cause performance issues so be careful with that.</p>
<h2 id="heading-what-are-some-common-sequence-type-operations-in-python">What Are Some Common Sequence Type Operations in Python?</h2>
<p>Assuming you remember the text sequence type (strings), you're now familiar with the four most popular Python sequence types.</p>
<p>So I think it's time for you to learn some common operations that you can perform on them. Let's begin, shall we?</p>
<h3 id="heading-how-to-use-the-in-operator-in-python">How to Use the <code>in</code> Operator in Python</h3>
<p>The <code>in</code> operator is the most common way of checking for any object's existence. For example, assume that you have a string and you want to check if it contains the word "red" or not.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    a_string = <span class="hljs-string">'Little Red Riding-Hood comes to me one Christmas Eve to give me information of the cruelty and '</span> \
               <span class="hljs-string">'treachery of that dissembling Wolf who ate her grandmother. '</span>

    print(<span class="hljs-string">'Red'</span> <span class="hljs-keyword">in</span> a_string)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># True</span>
</code></pre>
<p>It's literally like asking Python, if the word <code>Red</code> is <code>in</code> the <code>a_string</code> variable. And Python will give you either <code>True</code> or <code>False</code> as an answer.</p>
<p>The <code>in</code> operator is not exclusive to strings. You can actually use it on any other collection type such as lists, tuples, and ranges.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    books = [<span class="hljs-string">'Dracula'</span>, <span class="hljs-string">'Frankenstein'</span>, <span class="hljs-string">'The Omen'</span>, <span class="hljs-string">'The Exorcist'</span>, <span class="hljs-string">'The Legend of Sleepy Hollow'</span>]
    movies = (<span class="hljs-string">'A Christmas Carol'</span>, <span class="hljs-string">'The Sea Beast'</span>, <span class="hljs-string">'Enchanted'</span>, <span class="hljs-string">'Pinocchio'</span>, <span class="hljs-string">'The Addams Family'</span>)
    numbers = range(<span class="hljs-number">10</span>)

    print(<span class="hljs-string">'A Christmas Carol'</span> <span class="hljs-keyword">in</span> books)
    print(<span class="hljs-string">'Enchanted'</span> <span class="hljs-keyword">in</span> movies)
    print(<span class="hljs-number">5</span> <span class="hljs-keyword">in</span> numbers)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># False</span>
<span class="hljs-comment"># True</span>
<span class="hljs-comment"># True</span>
</code></pre>
<p>A Christmas Carol doesn't exist in the <code>books</code> list so it's a <code>False</code> statement. The other two statements are right, so they're <code>True</code>.</p>
<p>You may also want to find out about the absence of an object. For that, you can use the <code>not</code> operator in conjunction with the <code>in</code> operator.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    books = [<span class="hljs-string">'Dracula'</span>, <span class="hljs-string">'Frankenstein'</span>, <span class="hljs-string">'The Omen'</span>, <span class="hljs-string">'The Exorcist'</span>, <span class="hljs-string">'The Legend of Sleepy Hollow'</span>]
    movies = (<span class="hljs-string">'A Christmas Carol'</span>, <span class="hljs-string">'The Sea Beast'</span>, <span class="hljs-string">'Enchanted'</span>, <span class="hljs-string">'Pinocchio'</span>, <span class="hljs-string">'The Addams Family'</span>)
    numbers = range(<span class="hljs-number">10</span>)

    print(<span class="hljs-string">'A Christmas Carol'</span> <span class="hljs-keyword">not</span> <span class="hljs-keyword">in</span> books)
    print(<span class="hljs-string">'Enchanted'</span> <span class="hljs-keyword">not</span> <span class="hljs-keyword">in</span> movies)
    print(<span class="hljs-number">15</span> <span class="hljs-keyword">not</span> <span class="hljs-keyword">in</span> numbers)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># True</span>
<span class="hljs-comment"># False</span>
<span class="hljs-comment"># True</span>
</code></pre>
<p>A Christmas Carol doesn't exist in the <code>books</code> list, so the first statement evaluates to <code>true</code>. The second one evaluates to false because Enchanted is present in the <code>movies</code> list.</p>
<p>The last one is self explanatory at this point. The <code>in</code> and <code>not in</code> operators come in very handy when working with conditional statements.</p>
<h3 id="heading-how-to-use-the-and-operators-with-sequence-types-in-python">How to Use the <code>+</code> and <code>*</code> Operators with Sequence Types in Python</h3>
<p>You've already learned about <code>+</code> and <code>*</code> as arithmetic operators – but in the case of sequence types, they play a very different role.</p>
<p>The <code>+</code> operator lets you merge two sequences together.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    books = [<span class="hljs-string">'Dracula'</span>, <span class="hljs-string">'Frankenstein'</span>, <span class="hljs-string">'The Omen'</span>, <span class="hljs-string">'The Exorcist'</span>, <span class="hljs-string">'The Legend of Sleepy Hollow'</span>]
    more_books = [<span class="hljs-string">'And Then There Were None'</span>, <span class="hljs-string">'The ABC Murders'</span>, <span class="hljs-string">'The Valley of Fear'</span>, <span class="hljs-string">'The Hound of the Baskervilles'</span>, <span class="hljs-string">'The Chestnut Man'</span>]


    print(books + more_books)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># ['Dracula', 'Frankenstein', 'The Omen', 'The Exorcist', 'The Legend of Sleepy Hollow', 'And Then There Were None', 'The ABC Murders', 'The Valley of Fear', 'The Hound of the Baskervilles', 'The Chestnut Man']</span>
</code></pre>
<p>As you can see, the operator has appended the content of the <code>books</code> list to the content of the <code>more_books</code> list.</p>
<p>The <code>*</code> operator, on the other hand, makes multiple copies of a given sequence.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    books = [<span class="hljs-string">'Dracula'</span>, <span class="hljs-string">'Frankenstein'</span>, <span class="hljs-string">'The Omen'</span>, <span class="hljs-string">'The Exorcist'</span>, <span class="hljs-string">'The Legend of Sleepy Hollow'</span>]


    print(books * <span class="hljs-number">2</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># ['Dracula', 'Frankenstein', 'The Omen', 'The Exorcist', 'The Legend of Sleepy Hollow', 'Dracula', 'Frankenstein', 'The Omen', 'The Exorcist', 'The Legend of Sleepy Hollow']</span>
</code></pre>
<p>So multiplying the <code>books</code> list by 2 gives us all the 5 books in the list twice. These operators work the same for tuples, strings, ranges or any other sequence types.</p>
<h3 id="heading-how-to-use-the-len-min-and-max-functions-in-python">How to Use the <code>len()</code>, <code>min()</code>, and <code>max()</code> Functions in Python</h3>
<p>The <code>len()</code> function can return the length of a given sequence. And the <code>min()</code> and <code>max()</code> functions can return the minimum and maximum value in a given sequence, respectively.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    random_numbers = [<span class="hljs-number">6</span>, <span class="hljs-number">1</span>, <span class="hljs-number">3</span>, <span class="hljs-number">8</span>, <span class="hljs-number">0</span>]


    print(len(random_numbers))
    print(min(random_numbers))
    print(max(random_numbers))


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># 5</span>
<span class="hljs-comment"># 0</span>
<span class="hljs-comment"># 8</span>
</code></pre>
<p>Since there are 5 elements in the list, 5 is the output from the <code>len()</code> function call. </p>
<p>The smallest value in the list is 0 and the largest value is 8 which are the outputs from the <code>min()</code> and <code>max()</code> function calls, respectively.</p>
<p>Depending on the type of programs you end up writing in the future, these three functions can prove to be some of the most useful ones.</p>
<h2 id="heading-what-are-some-string-type-operations-in-python">What Are Some String Type Operations in Python?</h2>
<p>In the previous section, you've learned about some common operations that you can perform on any sequence type including strings.</p>
<p>However, the text sequence type aka strings have some special operations available to them.</p>
<p>In this chapter I'll introduce you to some of the most common string methods. Keep in mind that this is not a definitive list.</p>
<p>Although each of the methods I'm going to teach you performs a different task, they have one thing in common. None of them modifies a given string variable in place, but rather returns a new, modified copy.</p>
<p>If you want to learn about all the available string methods, feel free to consult the official Python documentation.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://docs.python.org/3/library/stdtypes.html#string-methods">https://docs.python.org/3/library/stdtypes.html#string-methods</a></div>
<p>Also remember it's not a matter of just going through each method and memorizing their usage.</p>
<p>It's about knowing what works best in a given scenario and coming up with clever solutions. And that requires practice.</p>
<h3 id="heading-how-to-capitalize-strings-in-python">How to Capitalize Strings in Python</h3>
<p>The first method you're going to learn is called <code>capitalize()</code> and it does what it sounds like.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    country_name = <span class="hljs-string">'bangladesh'</span>

    print(country_name.capitalize())


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Bangladesh</span>
</code></pre>
<p>As you can see from the code snippet above, the <code>capitalize()</code> method turns the first letter of the word to a capital letter.</p>
<p>This is simple, but let's try this on a string with multiple words in it – a sentence perhaps.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    book_name = <span class="hljs-string">'the house of silk'</span>

    print(book_name.capitalize())


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># The house of silk</span>
</code></pre>
<p>Although the method did its job, there is slight problem. Depending on what you're trying to achieve, you may expect the first letter of each word to be capitalized.</p>
<p>That's where the <code>title()</code> method comes in. This method returns a title cased version of a given string.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    book_name = <span class="hljs-string">'the house of silk'</span>

    print(book_name.title())


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># The House Of Silk</span>
</code></pre>
<p>But there is still an issue. Take the following string with apostrophes for example.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    book_name = <span class="hljs-string">"alice's adventures in wonderland"</span>

    print(book_name.title())


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Alice'S Adventures In Wonderland</span>
</code></pre>
<p>As you can see, the <code>title()</code> method treats the <code>s</code> following the apostrophe as a separate word and capitalizes it.</p>
<p>Regarding this issue, the <a target="_blank" href="https://docs.python.org/3/library/stdtypes.html#str.title">official documentation</a> states:</p>
<blockquote>
<p>The algorithm uses a simple language-independent definition of a word as groups of consecutive letters. The definition works in many contexts but it means that apostrophes in contractions and possessives form word boundaries.</p>
</blockquote>
<p>The <code>capwords()</code> helper function can solve this issue. This function breaks the string into multiple words based on the spaces between them, capitalizes the words, joins them back into a string and returns that to the user.</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> string <span class="hljs-keyword">import</span> capwords


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    book_name = <span class="hljs-string">"alice's adventures in wonderland"</span>

    print(capwords(book_name))


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Alice's Adventures In Wonderland</span>
</code></pre>
<p>Pay attention to the <code>import</code> statement at the top. The <code>capwords()</code> function is not a method within the string type but a function that resides inside the <code>string</code> module.</p>
<p>You'll learn about modules and imports in more details later on. For now, just roll with it. Although the function uses spaces to split words, you can overwrite it.</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> string <span class="hljs-keyword">import</span> capwords


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    address = <span class="hljs-string">'house 42, road 02, wonderland'</span>

    print(capwords(address, <span class="hljs-string">', '</span>))


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># House 42, Road 02, Wonderland</span>
</code></pre>
<p>As you can see, in this case the string has multiple parts divided by a comma followed by a space.</p>
<p>The <code>capwords()</code> function can take a custom delimiter as its second parameter. You can pass any string as the delimiter.</p>
<p>Finally, there is the <code>istitle()</code> method that can check whether a given string is in title case or not.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    book_name = <span class="hljs-string">'hearts in atlantis'</span>

    print(<span class="hljs-string">f'Is "<span class="hljs-subst">{book_name}</span>" in title case? <span class="hljs-subst">{book_name.istitle()}</span>'</span>)
    print(<span class="hljs-string">f'Is "<span class="hljs-subst">{book_name.title()}</span>" in title case? <span class="hljs-subst">{book_name.title().istitle()}</span>'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Is "hearts in atlantis" in title case? False</span>
<span class="hljs-comment"># Is "Hearts In Atlantis" in title case? True</span>
</code></pre>
<p>However, keep in mind that the <code>istitle()</code> method doesn't work with the <code>capwords()</code> helper function.</p>
<h3 id="heading-how-to-convert-strings-to-lower-case-or-upper-case-in-python">How to Convert Strings to Lower Case or Upper Case in Python</h3>
<p>Apart from capitalization, you may want to convert an entire string to upper case or lower case. You can do that by using the <code>upper()</code> and <code>lower()</code> methods in Python.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    book_name = <span class="hljs-string">'moriarty'</span>

    print(book_name.upper())

    another_book_name = <span class="hljs-string">'DRACULA'</span>

    print(another_book_name.lower())


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># MORIARTY</span>
<span class="hljs-comment"># dracula</span>
</code></pre>
<p>There are also the <code>isupper()</code> and <code>islower()</code> methods to check whether a given string is already in either of the letter cases or not.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    book_name = <span class="hljs-string">'moriarty'</span>

    print(book_name)
    print(<span class="hljs-string">f'Is <span class="hljs-subst">{book_name}</span> in upper case? <span class="hljs-subst">{book_name.isupper()}</span>'</span>)
    print(<span class="hljs-string">f'Is <span class="hljs-subst">{book_name}</span> in lower case? <span class="hljs-subst">{book_name.islower()}</span>'</span>)

    another_book_name = <span class="hljs-string">'DRACULA'</span>

    print(another_book_name)
    print(<span class="hljs-string">f'Is <span class="hljs-subst">{another_book_name}</span> in upper case? <span class="hljs-subst">{another_book_name.islower()}</span>'</span>)
    print(<span class="hljs-string">f'Is <span class="hljs-subst">{another_book_name}</span> in lower case? <span class="hljs-subst">{another_book_name.isupper()}</span>'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># moriarty</span>
<span class="hljs-comment"># Is moriarty in upper case? False</span>
<span class="hljs-comment"># Is moriarty in lower case? True</span>
<span class="hljs-comment"># DRACULA</span>
<span class="hljs-comment"># Is DRACULA in upper case? True</span>
<span class="hljs-comment"># Is DRACULA in lower case? False</span>
</code></pre>
<p>There is one last method called <code>casefold()</code> which is kind of a more aggressive version of the <code>lower()</code> method.</p>
<p>According to the <a target="_blank" href="https://docs.python.org/3/library/stdtypes.html#str.casefold">official documentation</a>:</p>
<blockquote>
<p>Casefolding is similar to lowercasing but more aggressive because it is intended to remove all case distinctions in a string. For example, the German lowercase letter 'ß' is equivalent to "ss". Since it is already lowercase, lower() would do nothing to 'ß'; casefold() converts it to "ss".</p>
</blockquote>
<p>The usage of this method is identical to the <code>lower()</code> method.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    book_name = <span class="hljs-string">'DRACULA'</span>

    print(book_name.casefold())


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># dracula</span>
</code></pre>
<p>These three methods are fine and dandy, but what if you don't want to use any of these particular methods and just want to switch the case of a given string?</p>
<p>The <code>swapcase()</code> method can do just that.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    book_name = <span class="hljs-string">'HEARTS IN ATLANTIS'</span>

    print(book_name.swapcase())


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># hearts in atlantis</span>
</code></pre>
<p>As you can see, the method has converted the book name into lower case from upper case.</p>
<h3 id="heading-how-to-count-the-number-of-occurrences-of-a-substring-in-a-string-in-python">How to Count the Number of Occurrences of a Substring in a String in Python</h3>
<p>If you want to find out the number of occurrences of a substring within a string, you can use the <code>count()</code> method in Python.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    paragraph = <span class="hljs-string">'''At three in the morning the chief Sussex detective, obeying the urgent call from Sergeant Wilson of 
    Birlstone, arrived from headquarters in a light dog-cart behind a breathless trotter. By the five-forty train in 
    the morning he had sent his message to Scotland Yard, and he was at the Birlstone station at twelve o'clock to 
    welcome us. White Mason was a quiet, comfortable-looking person in a loose tweed suit, with a clean-shaved, 
    ruddy face, a stoutish body, and powerful bandy legs adorned with gaiters, looking like a small farmer, 
    a retired gamekeeper, or anything upon earth except a very favourable specimen of the provincial criminal 
    officer.'''</span>

    substring = <span class="hljs-string">'morning'</span>

    print(<span class="hljs-string">f'The substring "<span class="hljs-subst">{substring}</span>" shows up <span class="hljs-subst">{paragraph.count(substring)}</span> times in the paragraph.'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># The substring "morning" shows up 2 times in the paragraph.</span>
</code></pre>
<p>If you call the <code>count()</code> method without passing anything to it, the method will return the number of empty spaces in the given string.</p>
<h3 id="heading-how-to-split-and-join-strings-in-python">How to Split and Join Strings in Python</h3>
<p>You can actually break a string into a list of words or join a list of words in a string in Python.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    string = <span class="hljs-string">'Holmes was certainly not a difficult man to live with'</span>

    word_list = string.split()

    print(word_list)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># ['Holmes', 'was', 'certainly', 'not', 'a', 'difficult', 'man', 'to', 'live', 'with']</span>
</code></pre>
<p>If you call the <code>split()</code> method without any parameters, it'll split the given string into words using the spaces as separators.</p>
<p>You can override that by passing a custom separator and also fix the number of splits you want.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    string = <span class="hljs-string">'Holmes,was,certainly,not,a,difficult,man,to,live,with'</span>

    word_list = string.split(<span class="hljs-string">','</span>, <span class="hljs-number">5</span>)

    print(word_list)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># ['Holmes', 'was', 'certainly', 'not', 'a', 'difficult,man,to,live,with']</span>
</code></pre>
<p>This time I've replaced the spaces in the source string with commas. I've also overridden the default separator with a comma and fixed the number of splits to five.</p>
<p>As you can see in the output, there are five splits and the rest of the string is kept unchanged as the sixth element in the list.</p>
<p>The <code>split()</code> method is good for using with data that has been intentionally delimited. Using it with natural text with punctuation may produce unexpected results.</p>
<p>The opposite of the <code>split()</code> method is <code>join()</code> and it works on any iterator type in Python.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    word_list = [<span class="hljs-string">'Holmes'</span>, <span class="hljs-string">'was'</span>, <span class="hljs-string">'certainly'</span>, <span class="hljs-string">'not'</span>, <span class="hljs-string">'a'</span>, <span class="hljs-string">'difficult'</span>, <span class="hljs-string">'man'</span>, <span class="hljs-string">'to'</span>, <span class="hljs-string">'live'</span>, <span class="hljs-string">'with'</span>]
    string = <span class="hljs-string">''</span>

    string = string.join(word_list)

    print(string)

    word_list = [<span class="hljs-string">'Holmes '</span>, <span class="hljs-string">'was '</span>, <span class="hljs-string">'certainly '</span>, <span class="hljs-string">'not '</span>, <span class="hljs-string">'a '</span>, <span class="hljs-string">'difficult '</span>, <span class="hljs-string">'man '</span>, <span class="hljs-string">'to '</span>, <span class="hljs-string">'live '</span>, <span class="hljs-string">'with'</span>]
    string = <span class="hljs-string">''</span>

    string = string.join(word_list)

    print(string)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Holmeswascertainlynotadifficultmantolivewith</span>
<span class="hljs-comment"># Holmes was certainly not a difficult man to live with</span>
</code></pre>
<p>There you have it. Notice how the <code>join()</code> method didn't care about adding spaces as separator after each word in the first call.</p>
<p>So I appended a space with each word in the list and in the second call the line has become much more readable.</p>
<h2 id="heading-how-to-write-conditional-statements-in-python">How to Write Conditional Statements in Python</h2>
<p>This is where it gets interesting. In Python or in any other programming language you can make decisions based on conditions.</p>
<p>I hope you remember the <code>boolean</code> data type from a previous section – the one that can only hold <code>True</code> or <code>False</code> values.</p>
<p>Well, you can use a boolean with an <code>if</code> statement (a conditional statement) in Python to perform an action conditionally.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    number = int(input(<span class="hljs-string">'what number would you like to check?\n- '</span>))

    <span class="hljs-keyword">if</span> number % <span class="hljs-number">2</span> == <span class="hljs-number">0</span>:
        print(<span class="hljs-string">f"<span class="hljs-subst">{number}</span> is even."</span>)
    <span class="hljs-keyword">else</span>:
        print(<span class="hljs-string">f"<span class="hljs-subst">{number}</span> is odd."</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># what number would you like to check?</span>
<span class="hljs-comment"># - 10</span>
<span class="hljs-comment"># 10 is even.</span>
</code></pre>
<p>You start by writing out <code>if</code> followed by a condition and a colon. By condition, what I mean is a statement that evaluates to a boolean value (true or false).</p>
<p>You've been using the <code>==</code> operator since the beginning and already know that it checks whether the value on the left side of it is equal to the one in the right or not.</p>
<p>So, if you divide a given number by 2 and the remainder is 0, that's an even number – otherwise, it'll be odd.</p>
<p>You can use the <code>if...else</code> statement to choose between two different options. But, if you have multiple options to choose from, you can use the <code>if...elif...else</code> statement.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    year = int(input(<span class="hljs-string">'which year would you like to check?\n- '</span>))

    <span class="hljs-keyword">if</span> year % <span class="hljs-number">400</span> == <span class="hljs-number">0</span> <span class="hljs-keyword">and</span> year % <span class="hljs-number">100</span> == <span class="hljs-number">0</span>:
        print(<span class="hljs-string">f"<span class="hljs-subst">{year}</span> is leap year."</span>)
    <span class="hljs-keyword">elif</span> year % <span class="hljs-number">4</span> == <span class="hljs-number">0</span> <span class="hljs-keyword">and</span> year % <span class="hljs-number">100</span> != <span class="hljs-number">0</span>:
        print(<span class="hljs-string">f"<span class="hljs-subst">{year}</span> is leap year."</span>)
    <span class="hljs-keyword">else</span>:
        print(<span class="hljs-string">f"<span class="hljs-subst">{year}</span> is not leap year."</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># which year would you like to check?</span>
<span class="hljs-comment"># - 2004</span>
<span class="hljs-comment"># 2004 is leap year.</span>
</code></pre>
<p>The <code>elif</code> statement usually goes after an <code>if</code> statement and before an <code>else</code> statement.</p>
<p>Think of it like "else if", so if the <code>if</code> statement fails, then the <code>elif</code> will take over. You write it exactly like a regular <code>if</code> statement.</p>
<p>Another new thing in this example is the <code>and</code> operator. It's one of the logical operators in Python. It does what it does in real life.</p>
<p>If the expressions on both sides of the <code>and</code> statement evaluates to <code>true</code>, then the whole expression evaluates to <code>true</code>. Simple.</p>
<p>Don't worry if you do not understand the <code>and</code> operator in detail at the moment. You'll learn about it and its siblings in the very next section.</p>
<p>Another thing you need to understand is that these <code>if</code> statements are just regular statements so you can do pretty much anything inside them.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    number = int(input(<span class="hljs-string">'what number would you like to check?\n- '</span>))

    is_not_prime = <span class="hljs-literal">False</span>

    <span class="hljs-keyword">if</span> number == <span class="hljs-number">1</span>:
        print(<span class="hljs-string">f"<span class="hljs-subst">{number}</span> is not a prime number."</span>)
    <span class="hljs-keyword">elif</span> number &gt; <span class="hljs-number">1</span>:
        <span class="hljs-keyword">for</span> n <span class="hljs-keyword">in</span> range(<span class="hljs-number">2</span>, number):
            <span class="hljs-keyword">if</span> (number % n) == <span class="hljs-number">0</span>:
                is_not_prime = <span class="hljs-literal">True</span>
                <span class="hljs-keyword">break</span>

        <span class="hljs-keyword">if</span> is_not_prime:
            print(<span class="hljs-string">f"<span class="hljs-subst">{number}</span> is not a prime number."</span>)
        <span class="hljs-keyword">else</span>:
            print(<span class="hljs-string">f"<span class="hljs-subst">{number}</span> is a prime number."</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># what number would you like to check?</span>
<span class="hljs-comment"># - 10</span>
<span class="hljs-comment"># 10 is not a prime number.</span>
</code></pre>
<p>This example is a bit more complex than what you've seen so far. So let me break it down for you. The program checks whether a given number is a prime number or not.</p>
<p>First, you take a number from the user. For a number to be prime, it has to be divisible only by 1 and itself. Since 1 is only divisible by 1, it's not a prime number.</p>
<p>Now, if the given number is larger than 1, then you'd have to divide the number with all the numbers from 2 to that particular number.</p>
<p>If the number is divisible by any of these numbers, then you'll turn the <code>is_not_prime</code> variable to <code>True</code>, and <code>break</code> the loop.</p>
<p>The <code>break</code> statement simply breaks out of a loop immediately. There is also the <code>continue</code> statement that can skip the current iteration instead of breaking out.</p>
<p>Finally, if the <code>is_not_prime</code> variable is <code>True</code> then the number is not prime, otherwise it's a prime number.</p>
<p>So as you can see, not only you can put loops inside a conditional statement but also put conditional statements inside a loop.</p>
<p>The final example that I'd like to show you is the <code>for...else</code> statement. As you can see in the example above, you have a <code>for</code> statement followed by a <code>if...else</code> statement.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    number = int(input(<span class="hljs-string">'what number would you like to check?\n- '</span>))

    <span class="hljs-keyword">if</span> number == <span class="hljs-number">1</span>:
        print(<span class="hljs-string">f"<span class="hljs-subst">{number}</span> is not a prime number."</span>)
    <span class="hljs-keyword">elif</span> number &gt; <span class="hljs-number">1</span>:
        <span class="hljs-keyword">for</span> n <span class="hljs-keyword">in</span> range(<span class="hljs-number">2</span>, number):
            <span class="hljs-keyword">if</span> (number % n) == <span class="hljs-number">0</span>:
                print(<span class="hljs-string">f"<span class="hljs-subst">{number}</span> is not a prime number."</span>)
                <span class="hljs-keyword">break</span>
        <span class="hljs-keyword">else</span>:
            print(<span class="hljs-string">f"<span class="hljs-subst">{number}</span> is a prime number."</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># what number would you like to check?</span>
<span class="hljs-comment"># - 5</span>
<span class="hljs-comment"># 5 is a prime number.</span>
</code></pre>
<p>If you put an <code>else</code> statement on the same level as a <code>for</code> statement, then Python will execute whatever you put inside that <code>else</code> block as soon as the loop has finished.</p>
<h2 id="heading-what-are-relational-and-logical-operators-in-python">What are Relational and Logical Operators in Python?</h2>
<p>In the examples above, you've seen the usage of <code>==</code> as well as the <code>and</code> operators. In this section, you'll learn about them in detail.</p>
<p>The relational operators come in handy when you want to check the relationship between two operands. There are six of these operators:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>OPERATOR</td><td>EXPLANATION</td><td>USAGE</td></tr>
</thead>
<tbody>
<tr>
<td><code>==</code></td><td>Equal To</td><td><code>5 == 5</code> gives you <code>True</code>, but <code>5 == 10</code> gives you <code>False</code></td></tr>
<tr>
<td><code>!=</code></td><td>Not Equal To</td><td><code>5 != 10</code> gives you <code>True</code>, but <code>5 != 5</code> gives you <code>False</code></td></tr>
<tr>
<td><code>&gt;</code></td><td>Greater Than</td><td><code>10 &gt; 5</code> gives you <code>True</code>, but <code>5 &gt; 10</code>gives you <code>False</code></td></tr>
<tr>
<td><code>&lt;</code></td><td>Less Than</td><td><code>5 &lt; 10</code> gives you <code>True</code>, but <code>10 &lt; 5</code> gives you <code>False</code></td></tr>
<tr>
<td><code>&gt;=</code></td><td>Greater Than or Equal</td><td><code>10 &gt;= 5</code> and <code>10 &gt;= 10</code> gives you <code>True</code>, but <code>5 &gt;= 10</code> gives you <code>False</code></td></tr>
<tr>
<td><code>&lt;=</code></td><td>Less Than or Equal</td><td><code>5 &lt;= 10</code> and <code>5 &lt;= 5</code> gives you <code>True</code>, but <code>10 &lt;= 5</code> gives you <code>False</code></td></tr>
</tbody>
</table>
</div><p>You've been using the <code>equal to</code> operator since the very beginning. The other ones you'll learn about as you keep going.</p>
<p>Apart from these, there are three logical operators in Python. They are the <code>and</code>, <code>or</code>, and <code>not</code> operators.</p>
<p>Take an RPG game, for example, where the hero has to have a level 45 or up shield and a level 48 or up sword in order to go to the next level.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    shield = int(input(<span class="hljs-string">'what is your shield level? '</span>))
    sword = int(input(<span class="hljs-string">'what is your sword level? '</span>))

    <span class="hljs-keyword">if</span> shield &gt;= <span class="hljs-number">45</span> <span class="hljs-keyword">and</span> sword &gt;= <span class="hljs-number">48</span>:
        print(<span class="hljs-string">'you shall pass!'</span>)
    <span class="hljs-keyword">else</span>:
        print(<span class="hljs-string">'you shall not pass!'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># what is your shield level? 42</span>
<span class="hljs-comment"># what is your sword level? 52</span>
<span class="hljs-comment"># you shall not pass!</span>
</code></pre>
<p>Unless you meet both conditions, the statement will evaluate to <code>False</code>. You can have more conditions in a statement like this:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    shield = int(input(<span class="hljs-string">'what is your shield level? '</span>))
    sword = int(input(<span class="hljs-string">'what is your sword level? '</span>))
    armor = int(input(<span class="hljs-string">'what is your armor level? '</span>))

    <span class="hljs-keyword">if</span> shield &gt;= <span class="hljs-number">45</span> <span class="hljs-keyword">and</span> sword &gt;= <span class="hljs-number">48</span> <span class="hljs-keyword">and</span> armor &gt;= <span class="hljs-number">25</span>:
        print(<span class="hljs-string">'you shall pass!'</span>)
    <span class="hljs-keyword">else</span>:
        print(<span class="hljs-string">'you shall not pass!'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># what is your shield level? 45</span>
<span class="hljs-comment"># what is your sword level? 50</span>
<span class="hljs-comment"># what is your armor level? 10</span>
<span class="hljs-comment"># you shall not pass!</span>
</code></pre>
<p>The <code>or</code> operator, on the other hand, is a bit more forgiving. If any of the given conditions evaluates true, than the entire statement will evaluate to true.</p>
<p>For example in another horror game, you can only get into The Castle Dracula if you are more than 500,000 years old or legally dead.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    age = <span class="hljs-number">10</span>_000
    is_legally_dead = <span class="hljs-literal">True</span>

    <span class="hljs-keyword">if</span> is_legally_dead <span class="hljs-keyword">or</span> age &gt; <span class="hljs-number">500</span>_000:
        print(<span class="hljs-string">'you shall pass!'</span>)
    <span class="hljs-keyword">else</span>:
        print(<span class="hljs-string">'you shall not pass!'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># you shall pass!</span>
</code></pre>
<p>You can mix the <code>and</code> and <code>or</code> operators together. I won't list out all the possible combinations of these operators, but as you keep working with Python, you'll get to use a lot of them.</p>
<p>The last logical operator that I'd like to discuss is the <code>not</code> operator. This operator takes only one operand and returns the opposite value.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    print(<span class="hljs-string">'not True ='</span>, <span class="hljs-keyword">not</span> <span class="hljs-literal">True</span>)
    print(<span class="hljs-string">'not False ='</span>, <span class="hljs-keyword">not</span> <span class="hljs-literal">False</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># not True = False</span>
<span class="hljs-comment"># not False = True</span>
</code></pre>
<p>For example, if you change the rules of the horror game we talked about in the previous example and make is so that only people who are over 500,000 years old and not Van Helsing can enter the castle.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    age = <span class="hljs-number">800</span>_000
    is_van_helsing = <span class="hljs-literal">True</span>

    <span class="hljs-keyword">if</span> age &gt; <span class="hljs-number">500</span>_000 <span class="hljs-keyword">and</span> <span class="hljs-keyword">not</span> is_van_helsing:
        print(<span class="hljs-string">'you shall pass!'</span>)
    <span class="hljs-keyword">else</span>:
        print(<span class="hljs-string">'you shall not pass!'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># you shall not pass!</span>
</code></pre>
<p>Since we've been talking about conditional statements and some of the operators associated with them, I'd like to introduce you to another statement first introduced in Python 3.10, the <code>match...case</code> statement.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://www.freecodecamp.org/news/python-switch-statement-switch-case-example/">https://www.freecodecamp.org/news/python-switch-statement-switch-case-example/</a></div>
<p>Since my colleague <a target="_blank" href="https://www.freecodecamp.org/news/author/kolade/">Kolade Chris</a> has written such a nice article on the topic, I'll not repeat that here. Feel free to check it out at your leisure.</p>
<h2 id="heading-what-are-assignment-operators-in-python">What Are Assignment Operators in Python?</h2>
<p>You've already encountered the simple assignment operator which is the <code>=</code> sign you used to assign a value to a variable.</p>
<p>Now there are a few variations to this operator that you can use to perform arithmetic and bitwise operations while also assigning a value.</p>
<p>Bitwise operations are a little out of the scope of this book, so I'll stick to the arithmetic operations.</p>
<p>There are seven different assignment operators in Python. Since you've already learned about the simple one, I'll discuss the other six in the following table.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>OPERATOR</td><td>USAGE</td><td>EQUIVALENT TO</td></tr>
</thead>
<tbody>
<tr>
<td><code>+=</code></td><td><code>a += b</code></td><td><code>a = a + b</code></td></tr>
<tr>
<td><code>-=</code></td><td><code>a -= b</code></td><td><code>a = a - b</code></td></tr>
<tr>
<td><code>*=</code></td><td><code>a *= b</code></td><td><code>a = a * b</code></td></tr>
<tr>
<td><code>/=</code></td><td><code>a /= b</code></td><td><code>a = a / b</code></td></tr>
<tr>
<td><code>%=</code></td><td><code>a %= b</code></td><td><code>a = a % b</code></td></tr>
<tr>
<td><code>**=</code></td><td><code>a **= b</code></td><td><code>a = a ** b</code></td></tr>
</tbody>
</table>
</div><p>These operators are not exclusive to Python, and in most programming resources, you'll find these in a much earlier chapter.</p>
<p>But I wanted to wait until you've learned about taking input from the user, working with ranges, and looping through them before introducting them here.</p>
<p>Assume that you want to write a program that calculates the sum of all the numbers within a given range.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    start = int(input(<span class="hljs-string">'which number do you want to start from?\n- '</span>))
    end = int(input(<span class="hljs-string">'which number do you want to stop at?\n- '</span>))

    total = <span class="hljs-number">0</span>

    <span class="hljs-keyword">for</span> number <span class="hljs-keyword">in</span> range(start, end + <span class="hljs-number">1</span>):
        total += number

    print(<span class="hljs-string">f"the sum of the numbers between <span class="hljs-subst">{start}</span> and <span class="hljs-subst">{end}</span> is: <span class="hljs-subst">{total}</span>"</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># which number do you want to start from?</span>
<span class="hljs-comment"># - 1</span>
<span class="hljs-comment"># which number do you want to stop at?</span>
<span class="hljs-comment"># - 10</span>
<span class="hljs-comment"># the sum of the numbers between 1 and 10 is: 55</span>
</code></pre>
<p>I hope you remember that the ending number of a <code>range()</code> function call is exclusive. So I had to add a <code>+1</code> with the ending number.</p>
<p>Otherwise it's a very simple range based for loop that adds each number to the <code>total</code> variable and prints it out once the loop has finished.</p>
<h2 id="heading-what-is-the-set-type-in-python">What Is the Set Type in Python?</h2>
<p>So far you've learned about a number of iterable types such as lists, tuples, and also strings. There is another one known as a set. Let's look at an example:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    numbers = {<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>}

    <span class="hljs-keyword">for</span> number <span class="hljs-keyword">in</span> numbers:
        print(number)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># 1</span>
<span class="hljs-comment"># 2</span>
<span class="hljs-comment"># 3</span>
<span class="hljs-comment"># 4</span>
<span class="hljs-comment"># 5</span>
</code></pre>
<p>You can create a new set by putting the values between a set of curly braces. Keep in mind however, you can not create an empty set using the curly braces.</p>
<p>You'll have to use the <code>set()</code> function for that.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    numbers = {}

    print(type(numbers))

    numbers = set()

    print(type(numbers))


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># &lt;class 'dict'&gt;</span>
<span class="hljs-comment"># &lt;class 'set'&gt;</span>
</code></pre>
<p>As you can see, usage of empty curly braces creates a dictionary whereas the <code>set()</code> function creates an empty set.</p>
<p>Sets may seem similar to lists, but they are actually quite different. For starters, you can not put duplicate values in a set.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    numbers_list = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">3</span>, <span class="hljs-number">2</span>, <span class="hljs-number">4</span>]

    print(numbers_list)

    numbers_set = set(numbers_list)

    print(numbers_set)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># [1, 2, 3, 4, 5, 3, 2, 4]</span>
<span class="hljs-comment"># {1, 2, 3, 4, 5}</span>
</code></pre>
<p>The list of numbers can hold duplicate values without any problem. But as soon as you create a set from that list, all the duplicate values will be gone.</p>
<p>Sets are mutable, so you can add new values to a set using the <code>add()</code> method.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    numbers = {<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>}

    numbers.add(<span class="hljs-number">500</span>)

    print(numbers)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># {1, 2, 3, 4, 5, 500}</span>
</code></pre>
<p>Likewise you can use the <code>discard()</code> method to remove an item from a set or use the <code>clear()</code> method to remove all values altogether.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    numbers = {<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>}

    numbers.discard(<span class="hljs-number">3</span>)

    print(numbers)

    numbers.clear()

    print(numbers)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># {1, 2, 4, 5}</span>
<span class="hljs-comment"># set()</span>
</code></pre>
<p>Notice how an empty set shows up as <code>set()</code> instead of <code>{}</code> because the latter indicates an empty dictionary.</p>
<p>Apart from the fact that a set never contains duplicate values, there is another speciality of this type.</p>
<p>You can perform set operations such as union, intersection, complement, and  difference using sets in Python.</p>
<p>My colleague <a target="_blank" href="https://www.freecodecamp.org/news/author/estefaniacn/">Estefania Cassingena Navone</a> has written an excellent guide on sets, frozen set and all the operations that you can perform on them.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://www.freecodecamp.org/news/python-sets-detailed-visual-introduction/">https://www.freecodecamp.org/news/python-sets-detailed-visual-introduction/</a></div>
<p>Finally, if you'd like to get a definitive look at the set type, the <a target="_blank" href="https://docs.python.org/3/library/stdtypes.html#set-types-set-frozenset">official documentation</a> will more than suffice.</p>
<h2 id="heading-what-is-the-mapping-type-in-python">What Is the Mapping Type in Python?</h2>
<p>You've already learned about the sequence types and set types in Python. Those are really useful for containing a bunch of data.</p>
<p>But situations where you want to store data in key value pairs are not uncommon. Take, for example, an online bookshop where you have to store the prices of the books.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    programming_books = {
        <span class="hljs-string">'C Programming Language'</span>: <span class="hljs-number">35</span>,
        <span class="hljs-string">'Introduction to Algorithms'</span>: <span class="hljs-number">100</span>,
        <span class="hljs-string">'Clean Code: A Handbook of Agile Software Craftsmanship'</span>: <span class="hljs-number">50</span>
    }

    print(programming_books)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># {'C Programming Language': 35, 'Introduction to Algorithms': 100, 'Clean Code: A Handbook of Agile Software Craftsmanship': 50}</span>
</code></pre>
<p>The variable <code>programming_books</code> here is a mapping type usually known as a dictionary. Declaring a dictionary is similar to declaring a list or tuple but you use a set of curly braces instead of square braces or parenthesis.</p>
<p>Enclosed within the braces are a bunch of key value pairs. The strings on the left side are the keys and the numbers are the values. You can access any of the keys using the <code>get()</code> method.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    programming_books = {
        <span class="hljs-string">'C Programming Language'</span>: <span class="hljs-number">35</span>,
        <span class="hljs-string">'Introduction to Algorithms'</span>: <span class="hljs-number">100</span>,
        <span class="hljs-string">'Clean Code: A Handbook of Agile Software Craftsmanship'</span>: <span class="hljs-number">50</span>
    }

    cpl = <span class="hljs-string">'C Programming Language'</span>
    algo = <span class="hljs-string">'Introduction to Algorithms'</span>

    print(<span class="hljs-string">f"The price of <span class="hljs-subst">{cpl}</span> is $<span class="hljs-subst">{programming_books.get(cpl)}</span>"</span>)
    print(<span class="hljs-string">f"The price of <span class="hljs-subst">{algo}</span> is $<span class="hljs-subst">{programming_books[algo]}</span>"</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># The price of C Programming Language is $35</span>
<span class="hljs-comment"># The price of Introduction to Algorithms is $100</span>
</code></pre>
<p>Alternatively, you can also use square braces like you did with lists to access a dictionary item.</p>
<p>Dictionaries are mutable which means you can add new items to them, remove or change existing items.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    programming_books = {
        <span class="hljs-string">'C Programming Language'</span>: <span class="hljs-number">35</span>,
        <span class="hljs-string">'Introduction to Algorithms'</span>: <span class="hljs-number">100</span>,
        <span class="hljs-string">'Clean Code: A Handbook of Agile Software Craftsmanship'</span>: <span class="hljs-number">50</span>
    }

    key = <span class="hljs-string">'C Programming Language'</span>

    programming_books[key] = <span class="hljs-number">45</span>

    programming_books[<span class="hljs-string">'The Pragmatic Programmer'</span>] = <span class="hljs-number">32</span>

    print(programming_books)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># {'C Programming Language': 45, 'Introduction to Algorithms': 100, 'Clean Code: A Handbook of Agile Software Craftsmanship': 50, 'The Pragmatic Programmer': 32}</span>
</code></pre>
<p>You can change an existing item by accessing the item using the square braces and assign a new value to it. The price of C Programming Language has gone up by $10.</p>
<p>If you put a nonexistent key in between the square braces, then that'll show up as a new item. The price of The Pragmatic Programmer was not in the dictionary before but now it has been added.</p>
<p>For removing an item from a dictionary, you can use the <code>popitem()</code> or the <code>pop()</code> method.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    programming_books = {
        <span class="hljs-string">'C Programming Language'</span>: <span class="hljs-number">35</span>,
        <span class="hljs-string">'Introduction to Algorithms'</span>: <span class="hljs-number">100</span>,
        <span class="hljs-string">'Clean Code: A Handbook of Agile Software Craftsmanship'</span>: <span class="hljs-number">50</span>
    }

    print(programming_books.popitem())

    key = <span class="hljs-string">'C Programming Language'</span>

    print(programming_books.pop(key))

    print(programming_books)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># ('Clean Code: A Handbook of Agile Software Craftsmanship', 50)</span>
<span class="hljs-comment"># 35</span>
<span class="hljs-comment"># {'Introduction to Algorithms': 100}</span>
</code></pre>
<p>The <code>popitem()</code> method removes the last item in the dictionary and returns that as a tuple.</p>
<p>The <code>pop()</code> method, on the other hand, returns the value for a given key and removes the pair.</p>
<p>The final <code>print()</code> function call shows that indeed two items were removed from the dictionary due to the pop calls.</p>
<p>Finally, there is the <code>clear()</code> method that wipes out all the pairs in a given dictionary in one go.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    programming_books = {
        <span class="hljs-string">'C Programming Language'</span>: <span class="hljs-number">35</span>,
        <span class="hljs-string">'Introduction to Algorithms'</span>: <span class="hljs-number">100</span>,
        <span class="hljs-string">'Clean Code: A Handbook of Agile Software Craftsmanship'</span>: <span class="hljs-number">50</span>
    }

    programming_books.clear()

    print(programming_books)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># {}</span>
</code></pre>
<h3 id="heading-what-are-dictionary-view-objects-in-python">What Are Dictionary View Objects in Python?</h3>
<p>So far in this section, you've seen dictionaries printed out as long comma separated lines between pairs of curly braces – but that's not very readable.</p>
<p>This is where the view objects come in handy. You can call some specific methods on dictionaries and get view objects in return.</p>
<p>The first method that I'm going to discuss is the <code>keys()</code> methods. It returns the keys of a given dictionary and you can loop over them.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    programming_books = {
        <span class="hljs-string">'C Programming Language'</span>: <span class="hljs-number">35</span>,
        <span class="hljs-string">'Introduction to Algorithms'</span>: <span class="hljs-number">100</span>,
        <span class="hljs-string">'Clean Code: A Handbook of Agile Software Craftsmanship'</span>: <span class="hljs-number">50</span>
    }

    <span class="hljs-keyword">for</span> key <span class="hljs-keyword">in</span> programming_books.keys():
        print(key)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># C Programming Language</span>
<span class="hljs-comment"># Introduction to Algorithms</span>
<span class="hljs-comment"># Clean Code: A Handbook of Agile Software Craftsmanship</span>
</code></pre>
<p>Just like the <code>keys()</code> method, there is the <code>values()</code> method that returns the values in a dictionary instead.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    programming_books = {
        <span class="hljs-string">'C Programming Language'</span>: <span class="hljs-number">35</span>,
        <span class="hljs-string">'Introduction to Algorithms'</span>: <span class="hljs-number">100</span>,
        <span class="hljs-string">'Clean Code: A Handbook of Agile Software Craftsmanship'</span>: <span class="hljs-number">50</span>
    }

    <span class="hljs-keyword">for</span> value <span class="hljs-keyword">in</span> programming_books.values():
        print(value)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># 35</span>
<span class="hljs-comment"># 100</span>
<span class="hljs-comment"># 50</span>
</code></pre>
<p>Finally, if you want both the keys and the values as tuples, you can use the <code>items</code> method.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    programming_books = {
        <span class="hljs-string">'C Programming Language'</span>: <span class="hljs-number">35</span>,
        <span class="hljs-string">'Introduction to Algorithms'</span>: <span class="hljs-number">100</span>,
        <span class="hljs-string">'Clean Code: A Handbook of Agile Software Craftsmanship'</span>: <span class="hljs-number">50</span>
    }

    <span class="hljs-keyword">for</span> item <span class="hljs-keyword">in</span> programming_books.items():
        print(item)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># ('C Programming Language', 35)</span>
<span class="hljs-comment"># ('Introduction to Algorithms', 100)</span>
<span class="hljs-comment"># ('Clean Code: A Handbook of Agile Software Craftsmanship', 50)</span>
</code></pre>
<h2 id="heading-how-to-write-functions-in-python">How to Write Functions in Python</h2>
<p>A function in Python (and programming in general) is a self-contained collection of instructions that perform a single task.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">print_hello</span>():</span>
    print(<span class="hljs-string">'Hello, World!'</span>)


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    print_hello()


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Hello, World!</span>
</code></pre>
<p>You define a function by writing out <code>def</code> followed by the name of the funtion and a colon. You can then write the function body from the next indented line.</p>
<p>In this example, the <code>print_hello()</code> prints out <code>Hello, World!</code> on the terminal. It doesn't accept any argument.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">print_hello</span>(<span class="hljs-params">message</span>):</span>
    print(message)


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    print_hello(<span class="hljs-string">'Hello, Universe!'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Hello, Universe!</span>
</code></pre>
<p>Now instead of printing out <code>Hello, World!</code> all the time, you can pass a custom message for the function to print out.</p>
<p>You can make a function accept multiple arguments and even set a default value for it.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">print_hello</span>(<span class="hljs-params">message, is_lower=False</span>):</span>
    <span class="hljs-keyword">if</span> is_lower:
        print(message.lower())
    <span class="hljs-keyword">else</span>:
        print(message.upper())


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    print_hello(<span class="hljs-string">'Hello, Universe!'</span>)
    print_hello(<span class="hljs-string">'Hello, Universe!'</span>, <span class="hljs-literal">True</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># HELLO, UNIVERSE!</span>
<span class="hljs-comment"># hello, universe!</span>
</code></pre>
<p>Setting a default value to a function parameter makes it optional. So if you do not pass a value during the function call, your program will use the default value.</p>
<p>Instead of printing out the message outright, you can make the function return the message.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">hello</span>(<span class="hljs-params">message, is_lower=False</span>):</span>
    <span class="hljs-keyword">if</span> is_lower:
        <span class="hljs-keyword">return</span> message.lower()
    <span class="hljs-keyword">else</span>:
        <span class="hljs-keyword">return</span> message.upper()


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    print(hello(<span class="hljs-string">'Hello, Universe!'</span>))
    print(hello(<span class="hljs-string">'Hello, Universe!'</span>, <span class="hljs-literal">True</span>))


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># HELLO, UNIVERSE!</span>
<span class="hljs-comment"># hello, universe!</span>
</code></pre>
<p>Since the function doesn't print out the message anymore, changing its name from <code>print_hello()</code> to just <code>hello()</code> makes more sense.</p>
<p>When you call the function with or without a custom message, the function returns a string that you can then print out within the <code>main()</code> function.</p>
<p>You can also save the message in variables instead of passing them to the <code>print()</code> function directly.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">hello</span>(<span class="hljs-params">message, is_lower=False</span>):</span>
    <span class="hljs-keyword">if</span> is_lower:
        <span class="hljs-keyword">return</span> message.lower()
    <span class="hljs-keyword">else</span>:
        <span class="hljs-keyword">return</span> message.upper()


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    uppercase_message = hello(<span class="hljs-string">'Hello, Universe!'</span>)
    print(uppercase_message)

    lowercase_message = hello(<span class="hljs-string">'Hello, Universe!'</span>, <span class="hljs-literal">True</span>)
    print(lowercase_message)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># HELLO, UNIVERSE!</span>
<span class="hljs-comment"># hello, universe!</span>
</code></pre>
<p>It's not that you can only pass singular values to a function. You can pass lists, tuples, dictionaries or any other object to a function.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">total</span>(<span class="hljs-params">numbers</span>):</span>
    s = <span class="hljs-number">0</span>
    <span class="hljs-keyword">for</span> number <span class="hljs-keyword">in</span> numbers:
        s += number
    <span class="hljs-keyword">return</span> s


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    print(total([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>, <span class="hljs-number">10</span>]))


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># 55</span>
</code></pre>
<p>In this function, you can pass a list of numbers to and get their sum. I had to name the function <code>total()</code> instead of <code>sum()</code> because there is a built-in function with that name.</p>
<p>There is one last concept regarding functions that I'd like to discuss in this section, and that is recursion.</p>
<p>Recursion in Python or programming in general is the technique of making a function call itself to perform a task iteratively.</p>
<p>For example, imagine a function that accepts an integer and calculates the sum of all natural numbers up to that given integer. You can write this program using loops.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">natural_sum</span>(<span class="hljs-params">last_number</span>):</span>
    <span class="hljs-keyword">if</span> last_number &lt; <span class="hljs-number">1</span>:
        <span class="hljs-keyword">return</span> last_number

    total = <span class="hljs-number">0</span>
    <span class="hljs-keyword">for</span> number <span class="hljs-keyword">in</span> range(<span class="hljs-number">1</span>, last_number + <span class="hljs-number">1</span>):
        total += number

    <span class="hljs-keyword">return</span> total


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    last_number = int(input(<span class="hljs-string">'up to which number would you like to calculate the sum?\n- '</span>))

    print(natural_sum(last_number))


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># up to which number would you like to calculate the sum?</span>
<span class="hljs-comment"># - 10</span>
<span class="hljs-comment"># 55</span>
</code></pre>
<p>There is nothing new there, just regular usage of a range-based for loop. Now, you can also write the same program without any loop.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">recursive_natural_sum</span>(<span class="hljs-params">last_number</span>):</span>
    <span class="hljs-keyword">if</span> last_number &lt; <span class="hljs-number">1</span>:
        <span class="hljs-keyword">return</span> last_number

    <span class="hljs-keyword">return</span> last_number + recursive_natural_sum(last_number - <span class="hljs-number">1</span>)


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    last_number = int(input(<span class="hljs-string">'up to which number would you like to calculate the sum?\n- '</span>))

    print(recursive_natural_sum(last_number))


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># up to which number would you like to calculate the sum?</span>
<span class="hljs-comment"># - 10</span>
<span class="hljs-comment"># 55</span>
</code></pre>
<p>At a glance, this piece of code may look very complicated to you. But in reality it's very simple. Let's break it down step by step.</p>
<p>When you call the <code>recursive_natural_sum()</code> function with the value of 10 for the first time, you start a chain reaction of sorts.</p>
<p>Since the value is not less than 1, the <code>if</code> statement evaluates to <code>False</code> and the second <code>return</code> statement gets called.</p>
<p>Inside that <code>return</code> statement, you're calling the <code>recursive_natural_sum()</code> function by passing the value of <code>last_number - 1</code> which is 9 at this point.</p>
<p>You're also adding the returned value from this call to the current value of the <code>last_number</code> variable.</p>
<p>But you'll not get a return value because your inner function call will call itself again with <code>last_number - 1</code> which will be 8 at that point.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/recursion-1.drawio.svg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>This calling goes on and on until the value of <code>last_digit</code> becomes zero. Once it becomes zero, the <code>if</code> statement evaluates to <code>True</code> and the function calls start to return a value.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/recursion-2.drawio-1.svg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The value returned from each function call is <code>last_digit + (last_digit - 1)</code> by the end of the recursion chain it adds up to 55.</p>
<p>My colleague <a target="_blank" href="https://www.freecodecamp.org/news/author/beau/">Beau Carnes</a> has written a more in-depth article discussing how recursion works. You may take a look at it if you want to learn more.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://www.freecodecamp.org/news/how-recursion-works-explained-with-flowcharts-and-a-video-de61f40cb7f9/">https://www.freecodecamp.org/news/how-recursion-works-explained-with-flowcharts-and-a-video-de61f40cb7f9/</a></div>
<p>I'm not sating that recursive functions are easier than loops – but at times, using a recursive function instead of nested loops can be more efficient.</p>
<h3 id="heading-how-to-write-anonymous-or-lambda-functions-in-python">How to Write Anonymous or Lambda Functions in Python</h3>
<p>Anonymous or lambda functions are functions without any name. This is not something exclusive to Python and most of the modern programming languages have some sort of lambda implementation.</p>
<p>Instead of beginning the function declaration with <code>def</code>, you instead start with writing out <code>lambda</code> followed by a colon and the function body.</p>
<pre><code class="lang-python">print_hello = <span class="hljs-keyword">lambda</span>: print(<span class="hljs-string">'Hello, World!'</span>)


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    print_hello()


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Hello, World!</span>
</code></pre>
<p>Since lambdas do not have a name, you have to put it in a variable in order to access it but that's not recommended. If you need a named function, use <code>def</code> instead.</p>
<p>Lambda functions are useful when you want to pass a function as an argument to another function call. Take the <code>filter()</code> function for example.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">check_even</span>(<span class="hljs-params">number</span>):</span>
    <span class="hljs-keyword">if</span> number % <span class="hljs-number">2</span> == <span class="hljs-number">0</span>:
        <span class="hljs-keyword">return</span> <span class="hljs-literal">True</span>
    <span class="hljs-keyword">else</span>:
        <span class="hljs-keyword">return</span> <span class="hljs-literal">False</span>


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">5</span>, <span class="hljs-number">4</span>, <span class="hljs-number">7</span>, <span class="hljs-number">88</span>, <span class="hljs-number">12</span>, <span class="hljs-number">15</span>, <span class="hljs-number">55</span>, <span class="hljs-number">77</span>, <span class="hljs-number">95</span>]

    even_numbers = filter(check_even, numbers)

    print(list(even_numbers))


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># [2, 4, 88, 12]</span>
</code></pre>
<p>The <code>filter()</code> function takes a function and an iterable type as its two arguments. The function should describe the logic for filtering and the iterable type will contain the values you want to filter from.</p>
<p>In this code, you have a list of numbers and you want to filter out the odd numbers from that list.</p>
<p>The <code>check_even()</code> function takes a number as argument. It then returns <code>True</code> if the number is divisible by two and <code>False</code> if not.</p>
<p>The <code>filter()</code> function iterates through the list of numbers and passes each number to the <code>check_even()</code> function.</p>
<p>It keeps the number if the <code>check_even()</code> function returns <code>True</code> or discards the number if the <code>check_even()</code> function returns <code>False</code>.</p>
<p>Now this <code>check_even()</code> function doesn't have any purpose other than checking if a given number is divisible by two or not. So you can write it as a lambda.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">5</span>, <span class="hljs-number">4</span>, <span class="hljs-number">7</span>, <span class="hljs-number">88</span>, <span class="hljs-number">12</span>, <span class="hljs-number">15</span>, <span class="hljs-number">55</span>, <span class="hljs-number">77</span>, <span class="hljs-number">95</span>]

    even_numbers = filter(<span class="hljs-keyword">lambda</span> number: <span class="hljs-literal">True</span> <span class="hljs-keyword">if</span> number % <span class="hljs-number">2</span> == <span class="hljs-number">0</span> <span class="hljs-keyword">else</span> <span class="hljs-literal">False</span>, numbers)

    print(list(even_numbers))


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># [2, 4, 88, 12]</span>
</code></pre>
<p>This lambda takes an argument named <code>number</code> then returns <code>True</code> if that's divisible by two and <code>False</code> otherwise.</p>
<p>You can add multiple arguments separating each by a comma. Finally a lambda doesn'e need a return statement but you can assume a return.</p>
<p>So <code>True if number % 2 == 0 else False</code> is equivalent to <code>return True if number % 2 == 0 else False</code>. The <code>if...else</code> statement inside the lambda is in short hand form.</p>
<h3 id="heading-how-to-work-with-local-nonlocal-and-global-variables-in-python">How to Work with local, nonlocal and global Variables in Python</h3>
<p>Scope of a variable in Python or programming in general refers to region where that variable is accessible.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">outside</span>():</span>
    message = <span class="hljs-string">'Hello, World!'</span>


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    print(message)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># NameError: name 'msg' is not defined</span>
</code></pre>
<p>In this example, the <code>message</code> variable is defined inside the <code>outside()</code> function and there is no existence of it anywhere else.</p>
<p>As a result, when you try to access that variable from the <code>main()</code> function, you get a <code>NameError</code> since the variable is scoped to the <code>outside()</code> function.</p>
<p>Variables like this are called local variables and they only exist within the block they've been declared.</p>
<p>Global variables, on the other hand, are usually declared outside of any particular block of code.</p>
<pre><code class="lang-python">message = <span class="hljs-string">'Hello, World!'</span>


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    print(message)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Hello, World!</span>
</code></pre>
<p>As you can see, now the <code>message</code> variable has no indentation and is declared at the top of the function. You could've declared the variable after the <code>main()</code> function.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    print(message)


message = <span class="hljs-string">'Hello, World!'</span>

<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Hello, World!</span>
</code></pre>
<p>This works because you don't try to access the variable until you call the <code>main()</code> function inside the <code>if</code> statement.</p>
<p>Although global variables are accessible pretty much everywhere, it can be a bit tricky to work with if you have a local variable with a similar name.</p>
<pre><code class="lang-python">message = <span class="hljs-string">'Hello, {name}!'</span>


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    message = message.format(name=<span class="hljs-string">'Farhan'</span>)
    print(message)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># UnboundLocalError: local variable 'message' referenced before assignment</span>
</code></pre>
<p>In this code, you have a placeholder for a name inside the <code>message</code> variable. You can use the <code>format()</code> method to put a name there.</p>
<p>But if you try to run this code, you'll get a <code>local variable 'message' referenced before assignment</code> message. In simpler words, you're trying to access a local variable named <code>message</code> before even assigning anything to it.</p>
<p>So clearly, Python is looking for a local variable with the given name instead of accessing the global one. Since it's asking, try giving it a local variable.</p>
<pre><code class="lang-python">message = <span class="hljs-string">'Hello, {name}!'</span>


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    message = str()

    message = message.format(name=<span class="hljs-string">'Farhan'</span>)
    print(message)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()
</code></pre>
<p>This time the error will be gone but you will not get any output in your console. This is because the local <code>message</code> variable is empty and there is no placeholder to put a name in.</p>
<p>This is where the <code>global</code> keyword comes in. Instead of creating a local variable, you can let Python know that you're trying to access the global <code>message</code> variable.</p>
<pre><code class="lang-python">message = <span class="hljs-string">'Hello, {name}!'</span>


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    <span class="hljs-keyword">global</span> message

    message = message.format(name=<span class="hljs-string">'Farhan'</span>)
    print(message)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Hello, Farhan!</span>
</code></pre>
<p>Now, instead of trying to look for a variable named <code>message</code> within the local scope, Python will directly reach out to the global scope.</p>
<p>Finally, there is the <code>nonlocal</code> keyword usually used in nested functions. It solves a similar problem as the <code>global</code> keyword but in a local scope.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">greet</span>(<span class="hljs-params">name</span>):</span>
    message = <span class="hljs-string">'Hello, {name}!'</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">include_name</span>():</span>
        message = message.format(name=name)

    include_name()
    <span class="hljs-keyword">return</span> message


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    print(greet(<span class="hljs-string">'Farhan'</span>))


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># UnboundLocalError: local variable 'message' referenced before assignment</span>
</code></pre>
<p>In this example, you're dealing with three functions. There is the <code>main()</code> function, there is the <code>greet()</code> function, and inside that is the <code>include_name()</code> function.</p>
<p>The <code>greet()</code> function takes a name as an argument but doesn't include that in the message right away.</p>
<p>Instead it calls the <code>include_name()</code> function defined within its local scope. That's where the problem begins.</p>
<p>You see, the <code>message</code> variable is outside the scope of the <code>include_message()</code> function and that's why you're getting the <code>referenced before assignment</code> error message.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">greet</span>(<span class="hljs-params">name</span>):</span>
    message = <span class="hljs-string">'Hello, {name}!'</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">include_name</span>():</span>
        <span class="hljs-keyword">global</span> message

        message = message.format(name=name)

    include_name()
    <span class="hljs-keyword">return</span> message


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    print(greet(<span class="hljs-string">'Farhan'</span>))


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># NameError: name 'message' is not defined</span>
</code></pre>
<p>You can't use the <code>global</code> keyword either since the <code>message</code> variable is not defined in the global scope and that's what the error message dictates.</p>
<p>You can use the <code>nonlocal</code> keyword to use variables that are not in the global scope but in the scope of the outer function.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">greet</span>(<span class="hljs-params">name</span>):</span>
    message = <span class="hljs-string">'Hello, {name}!'</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">include_name</span>():</span>
        <span class="hljs-keyword">nonlocal</span> message
        message = message.format(name=name)

    include_name()
    <span class="hljs-keyword">return</span> message


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    print(greet(<span class="hljs-string">'Farhan'</span>))


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Hello, Farhan!</span>
</code></pre>
<p>Now the <code>include_name()</code> function will look for the <code>message</code> variable within the scope of the <code>greet()</code> function instead of its local scope.</p>
<h3 id="heading-how-to-pass-a-variable-number-of-arguments-to-a-function-using-args-and-kwargs-in-python">How to Pass a Variable Number of Arguments to a Function Using <em>args and *</em>kwargs in Python</h3>
<p>Imagine a function that takes a bunch of numbers as arguments and returns their sum. In a function like this, it'd be nice to have the provision of passing a variable number of arguments.</p>
<p>Surely you can pass the numbers as a tuple or as a list but you may want to pass them as regular arguments separated by commas. You can do that by using <code>*args</code> or non key arguments in Python.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">total</span>(<span class="hljs-params">*args</span>):</span>
    print(type(args))

    t = <span class="hljs-number">0</span>
    <span class="hljs-keyword">for</span> arg <span class="hljs-keyword">in</span> args:
        t += arg

    <span class="hljs-keyword">return</span> t


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    print(total(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>))


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># &lt;class 'tuple'&gt;</span>
<span class="hljs-comment"># 15</span>
</code></pre>
<p>Here, you can pass an arbitrary number of variables to the <code>total()</code> function as argument and you'll have access to them as a tuple inside that function.</p>
<p>It's not mandatory to name the argument as <code>*args</code><em>,</em> you can call it something more descriptive like <code>_*_numbers</code> or anything else. As long as you put the asterisk in front, you're good to go.</p>
<p>Like <code>*args</code> there is also <code>**kwargs</code> or keyword arguments that will allow you to access the function arguments as a dictionary.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">items</span>(<span class="hljs-params">**kwargs</span>):</span>
    print(type(kwargs))

    <span class="hljs-keyword">for</span> key, value <span class="hljs-keyword">in</span> kwargs.items():
        print(<span class="hljs-string">f"<span class="hljs-subst">{key}</span> : <span class="hljs-subst">{value}</span>"</span>)


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    items(
        Apple=<span class="hljs-number">10</span>,
        Orange=<span class="hljs-number">8</span>,
        Grape=<span class="hljs-number">35</span>
    )


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># &lt;class 'dict'&gt;</span>
<span class="hljs-comment"># Apple : 10</span>
<span class="hljs-comment"># Orange : 8</span>
<span class="hljs-comment"># Grape : 35</span>
</code></pre>
<p>In this case, you can pass arbitrary number of key-value pairs and access them as a dictionary inside the <code>items()</code> function.</p>
<p>Just like the the <code>*args</code> keyword, you don't have to absolutely name it <code>**kwargs</code>. Instead you can name it anything you want.</p>
<p>As long as you put the double asterisks at the front, you'll be fine. The <code>items()</code> method within dictionaries lets you iterate through them.</p>
<p>You can also change the names of the <code>key</code> and <code>value</code> variables. A more readable version of the function can be as follows:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">items</span>(<span class="hljs-params">**fruits</span>):</span>
    print(type(fruits))

    <span class="hljs-keyword">for</span> fruit, price <span class="hljs-keyword">in</span> fruits.items():
        print(<span class="hljs-string">f"<span class="hljs-subst">{fruit}</span> : <span class="hljs-subst">{price}</span>"</span>)


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    items(
        Apple=<span class="hljs-number">10</span>,
        Orange=<span class="hljs-number">8</span>,
        Grape=<span class="hljs-number">35</span>
    )


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># &lt;class 'dict'&gt;</span>
<span class="hljs-comment"># Apple : 10</span>
<span class="hljs-comment"># Orange : 8</span>
<span class="hljs-comment"># Grape : 35</span>
</code></pre>
<p>Keep in mind that the type of the keys in this case has to be a string and the values can be anything you want.</p>
<h2 id="heading-what-are-modules-in-python">What Are Modules in Python?</h2>
<p>As you project grows, breaking off your code into multiple files becomes a necessity. A module in Python is just a file containing Python code that you can import inside other Python files.</p>
<p>For example, assume that you have a Python project with two files. The first one may be "mathstuff.py" and the other one may be "main.py".</p>
<p>The "mathstuff.py" file can contain stuff related to mathematics, for example a function that sums up all the natural numbers in a range.</p>
<pre><code class="lang-python"><span class="hljs-comment"># mathstuff.py</span>

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">natural_sum</span>(<span class="hljs-params">last_number</span>):</span>
    <span class="hljs-keyword">if</span> last_number &lt; <span class="hljs-number">1</span>:
        <span class="hljs-keyword">return</span> last_number

    total = <span class="hljs-number">0</span>
    <span class="hljs-keyword">for</span> number <span class="hljs-keyword">in</span> range(<span class="hljs-number">1</span>, last_number + <span class="hljs-number">1</span>):
        total += number

    <span class="hljs-keyword">return</span> total
</code></pre>
<p>Now you can import this function any other file such as the "main.py" file.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> mathstuff


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    last_number = int(input(<span class="hljs-string">'up to which number would you like to calculate the sum?\n- '</span>))

    print(mathstuff.natural_sum(last_number))


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># up to which number would you like to calculate the sum?</span>
<span class="hljs-comment"># - 10</span>
<span class="hljs-comment"># 55</span>
</code></pre>
<p>The <code>import</code> statement, as the name suggests, imports bits of code from another file or module.</p>
<p>It's not uncommon to house more than one function, variable, or other object in a Python module and often times you may want to use only few of them.</p>
<p>You can use the <code>from...import</code> statement in these situations.</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> mathstuff <span class="hljs-keyword">import</span> natural_sum


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    last_number = int(input(<span class="hljs-string">'up to which number would you like to calculate the sum?\n- '</span>))

    print(natural_sum(last_number))


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># up to which number would you like to calculate the sum?</span>
<span class="hljs-comment"># - 10</span>
<span class="hljs-comment"># 55</span>
</code></pre>
<p>It also saves you from having to write the module name everytime you want to access a function or object living inside that module.</p>
<p>Finally, you can use the <code>as</code> keyword to change the name of an imported module to make that more easily accessible.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> mathstuff <span class="hljs-keyword">as</span> math


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    last_number = int(input(<span class="hljs-string">'up to which number would you like to calculate the sum?\n- '</span>))

    print(math.natural_sum(last_number))


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># up to which number would you like to calculate the sum?</span>
<span class="hljs-comment"># - 10</span>
<span class="hljs-comment"># 55</span>
</code></pre>
<p>Also works with the <code>from...import</code> statement.</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> mathstuff <span class="hljs-keyword">import</span> natural_sum <span class="hljs-keyword">as</span> nsum


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    last_number = int(input(<span class="hljs-string">'up to which number would you like to calculate the sum?\n- '</span>))

    print(nsum(last_number))


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># up to which number would you like to calculate the sum?</span>
<span class="hljs-comment"># - 10</span>
<span class="hljs-comment"># 55</span>
</code></pre>
<p>Importing modules is something that you'll have to do all the time. Apart from modules, there is also the idea of packages.</p>
<p>In these examples, both files are in the same folder. Packages are a nifty little way of keeping related Python modules together in different folders.</p>
<p>For example, in a web framework, you may have a package called <code>framework</code> that houses all the code that comes with this web framework.</p>
<p>Now this <code>framework</code> package can in turn have multiple subpackages – for example there may be a package named <code>http</code> for handling HTTP requests and responses.</p>
<pre><code>├───framework
│   └───http
</code></pre><p>At the moment, these are just regular folders. To turn them into Python, all you need is to create "<strong>init</strong>.py" files inside them.</p>
<pre><code>├───framework
│   │   __init__.py
│   │
│   └───http
│           __init__.py
</code></pre><p>Now these files have turned into packages. These "<strong>init</strong>.py" files will tell the Python import system that these folders are indeed packages.</p>
<p>Finally, to put some code inside the <code>http</code> package, create a file named <code>response.py</code> with the following content:</p>
<pre><code class="lang-python"><span class="hljs-comment"># framework/http/response.py</span>

<span class="hljs-keyword">from</span> json <span class="hljs-keyword">import</span> dumps


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">as_json</span>(<span class="hljs-params">message</span>):</span>
    <span class="hljs-keyword">return</span> dumps({
        <span class="hljs-string">'message'</span>: message
    })
</code></pre>
<p>First, you're importing the <code>dumps</code> function from the <code>json</code> package. These are part of the Python standard library.</p>
<p>The <code>dumps</code> function can turn a Python object like a dictionary into a JSON string, which means the <code>as_json()</code> function returns a given value in JSON format.</p>
<pre><code class="lang-json">{<span class="hljs-attr">"message"</span>: <span class="hljs-string">"Hello, World"</span>}
</code></pre>
<p>Now you can import this function in the "main.py" file.</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> framework.http.response <span class="hljs-keyword">import</span> as_json


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    print(as_json(<span class="hljs-string">'Hello, World!'</span>))


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># {"message": "Hello, World"}</span>
</code></pre>
<p>Instead of putting the <code>as_json()</code> function inside another Python file, you can simply put it inside the "framework/http/<strong>init</strong>.py" file.</p>
<p>Then you can update the "main.py" file to use the updated package path.</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> framework.http <span class="hljs-keyword">import</span> as_json


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    print(as_json(<span class="hljs-string">'Hello, World!'</span>))


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># {"message": "Hello, World"}</span>
</code></pre>
<p>If you ever try out a framework like Django, you'll see that the framework contains a huge amount of packages, so understanding how the import system works will help you out immensely.</p>
<h2 id="heading-how-to-use-the-python-documentation-efficiently">How to Use the Python Documentation Efficiently</h2>
<p>Since you're now out of infancy as a Python programmer, I'd like to show you how you can browse through the official Python documentation.</p>
<p>You may think, well browsing documentation is not hard and you'd be absolutely right. But it can be daunting at first.</p>
<p>So what I'm going to do is give you a little primer on how I have used the documentation throughout my career.</p>
<p>The first step is to visit <a target="_blank" href="https://docs.python.org/">https://docs.python.org/</a> and you'll automatically land on the documentation for the latest version of Python.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/image-154.png" alt="Image" width="600" height="400" loading="lazy">
<em>Python Documentation (<a target="_blank" href="https://docs.python.org/">https://docs.python.org/</a>)</em></p>
<p>At the time of writing, the latest version of Python is 3.11.4 however I still have version 3.10.11 installed on my computers.</p>
<p>Right from the get go, you can see lots of different links other pages and to be honest, you're not going to need all of them right away.</p>
<p>The best way to find out which link to what page is to to have a look at whichever looks interesting to you.</p>
<p>I'll talk about three links from this page that have helped me immensely. The first one is the "Tutorial" page.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/image-155.png" alt="Image" width="600" height="400" loading="lazy">
<em>The Python Tutorial (https://docs.python.org/3/tutorial/index.html)</em></p>
<p>Back when I was making my shift from C to Python, this is the tutorial I went through. The tutorial starts with an introduction to the Python interpreter.</p>
<p>Then it teaches you topics including but not limited to data types, control flow statements, data structures, modules, error handling, the standard library, and even object oriented programming.</p>
<p>The other page that's extremely useful is the "Glossary" page. It contains a list of all the important terminology that you may come across while working with Python.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/image-156.png" alt="Image" width="600" height="400" loading="lazy">
<em>Glossary (https://docs.python.org/3/glossary.html)</em></p>
<p>So at any point if you feel like that you do not know the meaning of a word, take a look at the glossary.</p>
<p>Finally the "Library Reference" page is a detailed description of everything included in the standard Python library.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/image-158.png" alt="Image" width="600" height="400" loading="lazy">
<em>Library Reference (https://docs.python.org/3/library/index.html)</em></p>
<p>Say, for example, I'd like to learn about the context manager type (which is beyond the scope of this book). I can just look under the "Built-in Types" section.</p>
<p>Or if you want to know about something else such as the JSON package, you can search the library reference for JSON – and sure enough you'll find something on it.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/image-159.png" alt="Image" width="600" height="400" loading="lazy">
<em>JSON is under the Internet Data Handling section ()</em></p>
<p>Following the link will land you on the page describing how the JSON package works.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/image-160.png" alt="Image" width="600" height="400" loading="lazy">
<em>JSON encoder and decoder (https://docs.python.org/3/library/json.html)</em></p>
<p>The page not only contains text but also contains practical and very useful code examples.</p>
<p>The official documentation is going to be your most reliable and in-depth source of learning, so the sooner you get used to it the better.</p>
<h2 id="heading-whats-next">What's Next?</h2>
<p>As I've said, this text is not a definitive guide to Python – which means there is still a lot to learn. In this section I'll list out a number of different resources.</p>
<h3 id="heading-object-oriented-programming">Object Oriented Programming</h3>
<p>The first thing that you may want to learn right after finishing this handbook is object oriented programming with Python.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/Ej_02ICOIgs" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p>This comprehensive video course is hosted on the freeCodeCamp YouTube channel. It's a little over 2 hours long and covers the essential concepts nicely.</p>
<p>Object Oriented Programming is not just about learning about concepts like classes, objects, and inheritance.</p>
<p>Writing good object oriented code takes a lot of practice and it all begins with the basics. Take your time with this one and make sure to understand everything.</p>
<h3 id="heading-algorithms-and-data-structures">Algorithms and Data Structures</h3>
<p>The second item on the list that you should absolutely learn if you're serious about being an efficient programmer is data structures and algorithms.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/8hly31xKli0" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p>Fortunately, the freeCodeCamp YouTube channel hosts a very comprehensive video produced by some of the finest teachers out there on the topic.</p>
<p>The video is a little over 5 hours long and will teach everything you need to know about data structures and algorithms as beginner.</p>
<p>This course is not going to turn you into a better programmer instantly, but it'll teach you a better and more efficient way of thinking about problems.</p>
<h3 id="heading-django">Django</h3>
<p>If you'd like to get into web development using Python, Django is among the most popular choices out there.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/o0XbHvKxw7Y" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p>The freeCodeCamp YouTube channel hosts this massive 18 hour long course taught by Dr. Chuck, one of the best teachers in the world.</p>
<p>The course not only teaches Django from the ground up but also a long list of concepts around the web itself.</p>
<p>Having a good understanding of object oriented programming is important before you jump into the world of Django, so make sure you have that.</p>
<h3 id="heading-qt">Qt</h3>
<p>Python may not be the most popular languages for building graphical user interfaces, but it's surprisingly capable on that end, too.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/Z1N9JzNax2k" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p>Qt is a very popular cross-platform UI framework and PySide6 is the official Python bindings for Qt 6.</p>
<p>In this 5 hour long course, you'l learn all the fundamentals of creating user interfaces using Qt and create cross-platform, robust software in no time.</p>
<h3 id="heading-pygame">PyGame</h3>
<p>Just like cross-platform graphical user interfaces, Python is not the most popular choice when it comes to game programing.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/R9apl6B_ZgI" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p>However, the PyGame library is a very powerful and easy to use library for writing 2D games in Python.</p>
<p>In this almost 7 hour long course on game programming with Python, you'll learn about writing a game that mimicks the very popular Stardew Valley.</p>
<p>Undoubtedly, this is a very challenging video to go through but so is making games. So if you're into gamedev and Python, this may be the course you need.</p>
<h3 id="heading-data-science">Data Science</h3>
<p>Data science is arguably the most popular field where Python plays a huge role. Becoming a data scientist can take years but you gotta start somewhere.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/LHBE6Q9XlzI" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p>This 12 hour long course on the freeCodeCamp YouTube channel teaches you a lot about how to use your Python knowledge in data science.</p>
<p>Although the course doesn't go very deep into the realm of data science, it teaches you about a number of very important libraries used regularly in data science.</p>
<p>Near the end of the course, you'll also create a project by applying everything you learn throughout the course.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>I would like to thank you from the bottom of my heart for the time you've spent reading this article.</p>
<p>Although I've listed only a small number of courses here, the <a target="_blank" href="https://www.youtube.com/c/Freecodecamp/search?query=python">freeCodeCamp YouTube channel</a> is just filled with excellent Python learning resources.</p>
<p>Keep in mind that this handbook is a living document and I'll update it with from time to time. So bookmarking it maybe a great idea.</p>
<p>I also have a personal blog where I write about random tech stuff, so if you're interested in something like that, checkout <a target="_blank" href="https://farhan.dev">https://farhan.dev</a>.</p>
<p>If you have any questions or are confused about anything – or just want to get in touch – I'm available on <a target="_blank" href="https://twitter.com/frhnhsin">Twitter</a> and <a target="_blank" href="https://www.linkedin.com/in/farhanhasin/">LinkedIn</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ JavaScript Closure Tutorial – With JS Closure Example Code ]]>
                </title>
                <description>
                    <![CDATA[ By Anchal Nigam Closures – many of you JavaScript devs have probably heard this term before. When I started my journey with JavaScript, I encountered closures often. And I think they're one of the most important and interesting concepts in JavaScript... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-closure-tutorial-with-js-closure-example-code/</link>
                <guid isPermaLink="false">66d45d9ba44b8bb91150f655</guid>
                
                    <category>
                        <![CDATA[ closure ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Closure with example ]]>
                    </category>
                
                    <category>
                        <![CDATA[ example ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Lexical Scoping ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Wed, 27 May 2020 07:07:44 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2020/05/closure-1.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Anchal Nigam</p>
<p><strong>Closures –</strong> many of you JavaScript devs have probably heard this term before. When I started my journey with JavaScript, I encountered closures often. And I think they're one of the most important and interesting concepts in JavaScript. </p>
<p>You don't think they're interesting? This often happens when you don’t understand a concept – you don’t find it interesting. (I don’t know if this happens to you or not, but this is the case with me). </p>
<p>So in this article, I will try to make closures interesting for you.</p>
<p>Before going into the world of closures, let’s first understand <strong>lexical scoping</strong>. If you already know about it, skip the next part. Otherwise jump into it to better understand closures.</p>
<h2 id="heading-lexical-scoping">Lexical Scoping</h2>
<p>You may be thinking – I know local and global scope, but what the heck is lexical scope? I reacted the same way when I heard this term. Not to worry! Let’s take a closer look. </p>
<p>It’s simple like other two scopes:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greetCustomer</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">var</span> customerName = <span class="hljs-string">"anchal"</span>;
    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greetingMsg</span>(<span class="hljs-params"></span>) </span>{
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hi! "</span> + customerName); <span class="hljs-comment">// Hi! anchal</span>
    }
   greetingMsg();
}
</code></pre>
<p>You can see from the above output that the inner function can access the outer function's variable. This is lexical scoping, where the scope and value of a variable is determined by where it is defined/created (that is, its position in the code). Got it? </p>
<p>I know that last bit might have confused you. So let me take you deeper. Did you know that lexical scoping is also known as <strong>static scoping</strong>? Yes, that's its other name. </p>
<p>There is also <strong>dynamic scoping</strong>, which some programming languages support. Why have I mentioned dynamic scoping? Because it can help you better understand lexical scoping.</p>
<p>Let’s look at some examples:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greetingMsg</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(customerName);<span class="hljs-comment">// ReferenceError: customerName is not defined</span>
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greetCustomer</span>(<span class="hljs-params"></span>) </span>{
   <span class="hljs-keyword">var</span> customerName = <span class="hljs-string">"anchal"</span>;
   greetingMsg();
}

greetCustomer();
</code></pre>
<p>Do you agree with the output? Yes, it will give a reference error. This is because both functions don’t have access to each other’s scope, as they are defined separately.</p>
<p>Let’s look at another example:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addNumbers</span>(<span class="hljs-params">number1</span>) </span>{
  <span class="hljs-built_in">console</span>.log(number1 + number2);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addNumbersGenerate</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">var</span> number2 = <span class="hljs-number">10</span>;
  addNumbers(number2);
}

addNumbersGenerate();
</code></pre>
<p>The above output will be 20 for a dynamically scoped language. Languages that support lexical scoping will give <code>referenceError: number2 is not defined</code>. Why?</p>
<p>Because in dynamic scoping, searching takes place in the local function first, then it goes into the function that <em>called</em> that local function. Then it searches in the function that called <em>that</em> function, and so on, up the call stack. </p>
<p>Its name is self explanatory – “dynamic” means change. The scope and value of variable can be different as it depends on from where the function is called. The meaning of a variable can change at runtime. </p>
<p>Got the gist of dynamic scoping? If yes, then just remember that lexical scoping is its opposite.</p>
<p>In lexical scoping, searching takes place in the local function first, then it goes into the function inside which <em>that</em> function is defined. Then it searches in the function inside which <em>that</em> function is defined and so on. </p>
<p>So, <strong>lexical</strong> or <strong>static scoping</strong> means the scope and value of a variable is determined from where it is defined. It doesn’t change. </p>
<p>Let’s again look at the above example and try to figure out the output on your own. Just one twist – declare <code>number2</code> at the top:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> number2 = <span class="hljs-number">2</span>;
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addNumbers</span>(<span class="hljs-params">number1</span>) </span>{
  <span class="hljs-built_in">console</span>.log(number1 + number2);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addNumbersGenerate</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">var</span> number2 = <span class="hljs-number">10</span>;
  addNumbers(number2);
}

addNumbersGenerate();
</code></pre>
<p>Do you know what the output will be? </p>
<p>Correct – it’s 12 for lexically scoped languages. This is because first, it looks into an <code>addNumbers</code> function (innermost scope) then it searches inwards, where this function is defined. As it gets the <code>number2</code> variable, meaning the output is 12.</p>
<p>You may be wondering why I have spent so much time on lexical scoping here. This is a closure article, not one about lexical scoping. But if you don’t know about lexical scoping then you will not understand closures. </p>
<p>Why? You will get your answer when we look at the definition of a closure. So let’s get into the track and get back to closures.</p>
<h2 id="heading-what-is-a-closure">What is a Closure?</h2>
<p>Let’s look at the definition of a closure:</p>
<blockquote>
<p>Closure is created when an inner function has access to its outer function variables and arguments. The inner function has access to –   </p>
<ol>
<li>Its own variables.  </li>
<li>Outer function's variables and arguments.  </li>
<li>Global variables.</li>
</ol>
</blockquote>
<p>Wait! Is this the definition of a closure or lexical scoping? Both definitions look the same. How they are different? </p>
<p>Well, that's why I defined lexical scoping above. Because closures are related to lexical/static scoping. </p>
<p>Let’s again look at its other definition that will tell you how closures are different.</p>
<blockquote>
<p>Closure is when a function is able to access its lexical scope, even when that function is executing outside its lexical scope.</p>
</blockquote>
<p>Or,</p>
<blockquote>
<p>Inner functions can access its parent scope, even after the parent function is already executed.</p>
</blockquote>
<p>Confused? Don't worry if you haven't yet gotten the point. I have examples to help you better understand. Let’s modify the first example of lexical scoping:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greetCustomer</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> customerName = <span class="hljs-string">"anchal"</span>;
  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greetingMsg</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hi! "</span> + customerName);
  }
  <span class="hljs-keyword">return</span> greetingMsg;
}

<span class="hljs-keyword">const</span> callGreetCustomer = greetCustomer();
callGreetCustomer(); <span class="hljs-comment">// output – Hi! anchal</span>
</code></pre>
<p>The difference in this code is that we are returning the inner function and executing it later. In some programming languages, the local variable exists during the function’s execution. But once the function is executed, those local variables don’t exist and they will not be accessible. </p>
<p>Here, however, the scene is different. After the parent function is executed, the inner function (returned function) can still access the parent function's variables. Yes, you guessed right. Closures are the reason. </p>
<p>The inner function preserves its lexical scope when the parent function is executing and hence, later that inner function can access those variables. </p>
<p>To get a better feel for it, let’s use the <code>dir()</code> method of the console to look into the list of the properties of <code>callGreetCustomer</code>:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.dir(callGreetCustomer);
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/05/closure.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>From the above image, you can see how the inner function preserves its parent scope (<code>customerName</code>) when <code>greetCustomer()</code> is executed. And later on, it used <code>customerName</code> when <code>callGreetCustomer()</code> was executed.</p>
<p>I hope this example helped you better understand the above definition of a closure. And maybe now you find closures a bit more fun. </p>
<p>So what next? Let’s make this topic more interesting by looking at different examples.</p>
<h2 id="heading-examples-of-closures-in-action">Examples of closures in action</h2>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">counter</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">let</span> count = <span class="hljs-number">0</span>;
  <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> count++;
  };
}

<span class="hljs-keyword">const</span> countValue = counter();
countValue(); <span class="hljs-comment">// 0</span>
countValue(); <span class="hljs-comment">// 1</span>
countValue(); <span class="hljs-comment">// 2</span>
</code></pre>
<p>Every time you call <code>countValue</code>, the count variable value is incremented by 1. Wait – did you think that the value of count is 0? </p>
<p>Well, that would be wrong as a closure doesn’t work with a value. It stores the <strong>reference</strong> of the variable. That’s why, when we update the value, it reflects in the second or third call and so on as the closure stores the reference. </p>
<p>Feeling a bit clearer now? Let’s look at another example:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">counter</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">let</span> count = <span class="hljs-number">0</span>;
  <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> count++;
  };
}

<span class="hljs-keyword">const</span> countValue1 = counter();
<span class="hljs-keyword">const</span> countValue2 = counter();
countValue1();  <span class="hljs-comment">// 0</span>
countValue1();  <span class="hljs-comment">// 1</span>
countValue2();   <span class="hljs-comment">// 0</span>
countValue2();   <span class="hljs-comment">// 1</span>
</code></pre>
<p>I hope you guessed the right answer. If not, here is the reason. As <code>countValue1</code> and <code>countValue2</code>, both preserve their own lexical scope. They have independent lexical environments. You can use <code>dir()</code> to check the <code>[[scopes]]</code> value in both the cases.</p>
<p>Let’s look at a third example.</p>
<p>This one's a bit different. In it, we have to write a function to achieve the output:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> addNumberCall = addNumber(<span class="hljs-number">7</span>);
addNumberCall(<span class="hljs-number">8</span>) <span class="hljs-comment">// 15</span>
addNumberCall(<span class="hljs-number">6</span>) <span class="hljs-comment">// 13</span>
</code></pre>
<p>Simple. Use your newly-gained closure knowledge:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addNumber</span>(<span class="hljs-params">number1</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">number2</span>) </span>{
    <span class="hljs-keyword">return</span> number1 + number2;
  };
}
</code></pre>
<p>Now let’s look at some tricky examples:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">countTheNumber</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">var</span> arrToStore = [];
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">var</span> x = <span class="hljs-number">0</span>; x &lt; <span class="hljs-number">9</span>; x++) {
    arrToStore[x] = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
      <span class="hljs-keyword">return</span> x;
    };
  }
  <span class="hljs-keyword">return</span> arrToStore;
}

<span class="hljs-keyword">const</span> callInnerFunctions = countTheNumber();
callInnerFunctions[<span class="hljs-number">0</span>]() <span class="hljs-comment">// 9</span>
callInnerFunctions[<span class="hljs-number">1</span>]() <span class="hljs-comment">// 9</span>
</code></pre>
<p>Every array element that stores a function will give you an output of 9. Did you guess right? I hope so, but still let me tell you the reason. This is because of the closure's behavior. </p>
<p>The closure stores the <strong>reference</strong>, not the value. The first time the loop runs, the value of x is 0. Then the second time x is 1, and so on. Because the closure stores the reference, every time the loop runs it's changing the value of x. And at last, the value of x will be 9. So <code>callInnerFunctions[0]()</code> gives an output of 9. </p>
<p>But what if you want an output of 0 to 8? Simple! Use a closure. </p>
<p>Think about it before looking at the solution below:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">callTheNumber</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getAllNumbers</span>(<span class="hljs-params">number</span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
      <span class="hljs-keyword">return</span> number;
    };
  }
  <span class="hljs-keyword">var</span> arrToStore = [];
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">var</span> x = <span class="hljs-number">0</span>; x &lt; <span class="hljs-number">9</span>; x++) {
    arrToStore[x] = getAllNumbers(x);
  }
  <span class="hljs-keyword">return</span> arrToStore;
}

<span class="hljs-keyword">const</span> callInnerFunctions = callTheNumber();
<span class="hljs-built_in">console</span>.log(callInnerFunctions[<span class="hljs-number">0</span>]()); <span class="hljs-comment">// 0</span>
<span class="hljs-built_in">console</span>.log(callInnerFunctions[<span class="hljs-number">1</span>]()); <span class="hljs-comment">// 1</span>
</code></pre>
<p>Here, we have created separate scope for each iteration. You can use <code>console.dir(arrToStore)</code> to check the value of x in <code>[[scopes]]</code> for different array elements.</p>
<p>That’s it! I hope you can now say that you find closures interesting.</p>
<p>To read my other articles, check out my profile <a target="_blank" href="https://www.freecodecamp.org/news/author/anchal">here</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
