<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Dorcas Olajide on Medium]]></title>
        <description><![CDATA[Stories by Dorcas Olajide on Medium]]></description>
        <link>https://medium.com/@dorcas2017?source=rss-b69eac0a6820------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*WT-w-2K8ylnD0k9KM0ttVQ.jpeg</url>
            <title>Stories by Dorcas Olajide on Medium</title>
            <link>https://medium.com/@dorcas2017?source=rss-b69eac0a6820------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 05:05:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dorcas2017/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Emotional Intelligence 101: Transforming Work Emotions into Career Triumphs]]></title>
            <link>https://medium.com/@dorcas2017/transforming-work-emotions-into-career-triumphs-2b3161c31f95?source=rss-b69eac0a6820------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b3161c31f95</guid>
            <category><![CDATA[careers]]></category>
            <category><![CDATA[emotions]]></category>
            <category><![CDATA[emotional-intelligence]]></category>
            <category><![CDATA[stress]]></category>
            <category><![CDATA[work]]></category>
            <dc:creator><![CDATA[Dorcas Olajide]]></dc:creator>
            <pubDate>Sat, 02 Mar 2024 21:51:35 GMT</pubDate>
            <atom:updated>2024-03-06T10:50:04.574Z</atom:updated>
            <content:encoded><![CDATA[<h3>Emotional Intelligence 101</h3><h3>Transforming Work Emotions into Career Triumphs</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*I4ZRfVyDsUlwIK-RZWgaUA.jpeg" /></figure><p><a href="https://crackworkemotions.carrd.co/">Get the ebook here</a></p><p>In the core of our professional lives, emotions play a pivotal role, influencing our decisions, relationships, and overall job satisfaction. However, emotions are often overlooked in the hustle and bustle of the modern workplace as we navigate through tasks, deadlines, and responsibilities.</p><p>It is important we bring the best version of ourselves to work. Although, some times it is imposible to avoid situations or emotions that set off the tune we wish to create for the day. We can harness the power of emotions and turn them into stepping stones for career triumphs.</p><p>But How?</p><p>1. Holistic Approach:<br><a href="https://crackworkemotions.carrd.co/">This ebook</a> adopts a holistic approach that goes beyond merely managing emotions at work. It delves into emotional intelligence, guiding you to understand, embrace, and leverage your feelings to thrive in your professional endeavors.</p><p>2. Actionable Strategies:<br><a href="https://crackworkemotions.carrd.co/">“Crack the Code”</a> is not only a theoretical discourse on emotions but a practical roadmap. Packed with actionable strategies, it provides tangible steps to help you navigate the complex terrain of workplace emotions, transforming challenges into opportunities for career growth.</p><p>3. Success Stories:<br>Drawing inspiration from success stories, <a href="https://crackworkemotions.carrd.co/">this ebook</a> illustrates how individuals have cracked the code to turn their work emotions into career triumphs. Learn from those who have walked the path and emerged stronger, wiser, and more successful.</p><p>4. Emotional Intelligence Unleashed:<br>Discover the power of emotional intelligence as we guide you through the principles of self-awareness, self-regulation, empathy, and social skills. Unleash the potential of these elements to elevate your career to new heights.</p><p>5. Building Resilience:<br>Navigate the ups and downs of your professional journey by building emotional resilience. Learn how setbacks and challenges can be stepping stones to your ultimate career triumphs.</p><p>As you embark on this transformative journey through “<a href="https://crackworkemotions.carrd.co/">Crack the Code</a>,” ensure you find the secrets that will revolutionize your approach to work emotions. <a href="https://crackworkemotions.carrd.co/">This ebook</a> is not just a guide; it’s your companion in the pursuit of a successful, emotionally intelligent, and fulfilling career. Let the journey begin — your path to career triumphs awaits!</p><p><a href="https://crackworkemotions.carrd.co/">Unveil “Crack the Code”: Your Passport to Transforming Work Emotions into Career Triumphs!</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b3161c31f95" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Python]]></title>
            <link>https://medium.com/@dorcas2017/introduction-to-python-2eb51cf91b83?source=rss-b69eac0a6820------2</link>
            <guid isPermaLink="false">https://medium.com/p/2eb51cf91b83</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Dorcas Olajide]]></dc:creator>
            <pubDate>Tue, 27 Dec 2022 10:48:14 GMT</pubDate>
            <atom:updated>2022-12-27T10:48:14.765Z</atom:updated>
            <content:encoded><![CDATA[<h4>Understanding the basics of python</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ruTiIORlh-B0XfZtXyvPnA.png" /><figcaption>Photo by Joshua Woroniecki on Unsplash</figcaption></figure><p>If you are new to programming or you want to learn how to write python then this is for you. I’ve added links to extra notes from Women in Datascience Ife Community library to give you better insight.</p><p>Before we begin, kindly note that we’ll be using Python 3 and in order to follow closely you need a Jupyter notebook. Your options are either you install Anaconda or use Google Colaboratory. I’ll advise you <a href="https://colab.research.google.com/#create=true">jump into coding without any installation with Google colaboratory</a>.</p><h4>For this tutorial, we’ll be looking at</h4><ol><li>Comments</li><li>Variables</li><li>Data types</li><li>If statement</li><li>While loop</li><li>For loop</li><li>Function</li></ol><p>So let’s begin</p><h3>1. Comments</h3><p>Making comments while coding is one crucial way to help viewers understand your code. You can make a single-line comment or a one that spans across many lines. Single-line comment are usually made at the end of a line of code. To make a single-line comment, type the hash symbol followed by your comments.</p><pre># This is a comment in Python<br></pre><p>To make multiple line comments, type three single quotes at the beginning and end of the comments. You can use this to explain the use of a function or class.</p><pre>&#39;&#39;&#39;This is a multiline string<br>This is the second line<br>This is the third line.&#39;&#39;&#39;<br></pre><h3>2. Variables</h3><p>A variable is a container that holds any value assigned to it until it is deleted. variables are mutable in nature, that is they are not constant. In Python you can declare an empty variable by giving it the value None.</p><pre>x = 5 # declearing a variable x and assigned it to value 5 <br>x = None # an empty variable</pre><h3>3. Data types</h3><p>Just like how a group of words makes a sentence. These can be used to create and hold data in python. Popular data types include; str, int, float, bool, list, tuple, range and dict.</p><ul><li>String</li></ul><p><em>str</em> is short for string in python. A string is a group of letters, usually enclosed with a double or single apostrophe.</p><pre>x = &quot;python&quot;<br></pre><p>You can have multiple line strings assigned to a variable. Just like the multiple line comments but this time assigned to a variable.</p><pre>x = &#39;&#39;&#39;This is a multiline string<br>This is the second line<br>This is the third line.&#39;&#39;&#39;<br><br>print(x)<br></pre><p>You can modify strings into upper or lower case. The upper() method returns the string in upper case and lower() returns the string in lower case.</p><pre>a = &quot;Hello World&quot;<br>print(a.upper())<br><br># Try this <br>print(a.lower())<br># and this<br>print(a.capitalize())<br></pre><p>Check out other ways to modify strings.</p><ul><li>Integer, Float</li></ul><p><em>int</em> is short for integer. <em>int</em> and <em>float</em> are Numeric types. An integer is a number and floats are decimal values or fractional numbers.</p><pre>x= 100 #int<br>z = 33.33333 # float<br></pre><p>You might want to directly cast your variable, for example, you might want to declare a integer as a string in a variable. You can do this with int(), float() or str(). These methods convert the data to the desired and add or remove the excesses if there is.</p><pre>myint = int(33.3333) # 33 an integer<br>myfloat = float(33) # 33.0 a float<br>mystr = str(33) # &#39;33&#39; a string<br></pre><ul><li>Boolean</li></ul><p><em>bool</em> is short for Boolean. A Boolean is either true or false. To better understand these types, <a href="https://docs.google.com/document/d/1-wbNQRsBtjQz0zX4t2dT_08fcH_oQMAT/edit?usp=drivesdk&amp;ouid=112020469209150714221&amp;rtpof=true&amp;sd=true">check out this note on Strings, Integers and Booleans</a>.</p><p>Next we’ll be looking at data types that can hold the above data types in python.</p><ul><li>List, Tuple</li></ul><p>List, tuple are sequence types. Their data are indexed starting from zero. Lists are arrays, they are like empty shelves where you can keep your books, but this time you keep values or variables.</p><pre>myList = [5,7, &#39;any&#39;, x]<br><br># Try this<br>fruits = [&quot;orange&quot;, &quot;mango&quot;, &quot;pineapple&quot;, &quot;banana&quot;]<br><br>print(fruits)<br>print(fruits[0]) # print the valued indexed at zero<br># try pring other values with their index numbers<br><br># let&#39;s print the last value in the fruits array<br>print(fruits[-1])<br>print(fruits[len(fruits)-1]) # len(fruits) indicate the length of the array fruits<br></pre><p>Tuples works like lists in a way, it is use to store multiple data in a variable for example, longitude and latitude, and you use a parentheses instead.</p><pre>x = 5<br>myTuple = (1,7,8,5,8,9, x)<br>print(myTuple[1])<br></pre><ul><li>Range</li></ul><p>Range are also sequence type. It is an inbuilt method used to create range of numbers.</p><pre>print(range(0,10))<br>print(range(5,9))<br>print([i for i in range(5)]) # convert range to list<br></pre><ul><li>Dictionary</li></ul><p><em>dict</em> is short for dictionary. A dict is a mapping type, use to map key to values. Dictionaries work like a real dictionary, it creates a key-value pair relationship where each key is unique and values can vary.</p><pre>myDict = {‘integer’:5, &#39;string&#39;: &#39;hello&#39;}<br>print(myDict)<br>print(myDict[&#39;integer&#39;])<br></pre><p>Learn <a href="https://docs.google.com/document/d/1ItQvX3ZOrZ944zoAwfMbSHM8QKas5O8z/edit?usp=drivesdk&amp;ouid=112020469209150714221&amp;rtpof=true&amp;sd=true">more on dictionary, list and tuple</a>.</p><p>You can get the data type of any object by using the syntax <em>type().</em></p><pre>x = 5<br>print(type(x))<br></pre><h3>4. If statement</h3><p>The if statement is a conditional statement that only runs if the condition attached to it is true. it can also include an else statement that runs when the condition is false.</p><pre>x=5<br>if x==5:<br>    print(&quot;this is true&quot;)<br>else:<br>    print(&quot;this is false&quot;)<br><br># What happens if we use if True or if False?, Try it.<br></pre><h3>5. While Loop</h3><p>While loop is used to execute a set of statements while the condition is still true.</p><pre><br># Print x as long as x is less than 10<br>x = 1<br>while x&lt; 6:<br>    print(x)<br>    x += 1 # increment x by 11<br>print(&quot;done&quot;)<br></pre><h3>6. For Loop</h3><p>For loop execute statements while iterating over a sequence, this can be a list, tuple or string.</p><pre># print elements in a list<br>numbers = [2,7,9,6,20]<br>for x in numbers:<br>    print(x)<br># Try iterating over a string<br>for x in &#39;python&#39;:<br>    print(x)<br><br># Try using the for loop with the if statement<br>fruits = [&#39;orange&#39;, &#39;pineapple&#39;, &#39;banana&#39;, &#39;apple&#39;]<br><br>if (fruits != None):<br>    for fruit in fruits:<br>        print(fruit)<br>else:<br>    print(&#39;No fruit&#39;)<br></pre><p>Learn <a href="https://docs.google.com/document/d/1vqnfxERyXF__w731EolFbY0L2l-F5tpR/edit?usp=drivesdk&amp;ouid=112020469209150714221&amp;rtpof=true&amp;sd=true">more on if statement, for and while loop</a>.</p><h3>7. Function</h3><p>A Function is a block of code made to perform a specific task. It is declared once and can be called as many times as possible. It can accept also parameters.</p><pre>&#39;&#39;&#39;<br>def functionName (parameter):<br>    block of code<br>&#39;&#39;&#39;<br><br>def square(x):<br>    return (x ** 2)<br><br>print(square(5))<br>print(square(10))<br></pre><p>Learn <a href="https://drive.google.com/file/d/1tadnYGip9BXghzo4-g8bRTDJUWm1kZd2/view?usp=drivesdk">more on functions</a>.</p><h3>Instead of a conclusion</h3><p>Go ahead and take on the <a href="https://drive.google.com/file/d/1xnUOiweWSIMDf6Q3Qd-xWbYGxTlgPQp4/view?usp=drivesdk">exercise here</a> and <a href="https://drive.google.com/file/d/16wHNOF-9Tj85cMqo4USnEWaUPYELllSO/view?usp=drivesdk">here</a>. It covers all we’ve treated.</p><p>This tutorial is enough to get you started but I’ll advise you not to stop here, learn more and don’t forget to practice. As they say, practice makes one perfect.</p><p>If you enjoyed this, follow me and give me a clap.</p><p>Thanks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2eb51cf91b83" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using the Command-Line and Shell Scripting]]></title>
            <link>https://blog.devgenius.io/using-the-command-line-and-shell-scripting-1f0e84d76a8e?source=rss-b69eac0a6820------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f0e84d76a8e</guid>
            <category><![CDATA[bash]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[command-line]]></category>
            <category><![CDATA[shell]]></category>
            <dc:creator><![CDATA[Dorcas Olajide]]></dc:creator>
            <pubDate>Wed, 27 Apr 2022 13:13:00 GMT</pubDate>
            <atom:updated>2022-08-02T16:24:06.676Z</atom:updated>
            <content:encoded><![CDATA[<p>Whether you are a Mac, Windows or Linux user, understanding how to use the command line will help your daily coding experience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EPLo89SynUdb8qbN" /><figcaption>Photo by <a href="https://unsplash.com/@mohamed_m?utm_source=medium&amp;utm_medium=referral">Mohamed M</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>A Command Line Interface (CLI) helps you interact with your system by enabling you to run commands or scripts. These commands (or command-line utilities) are mostly located in your system as binary files and therefore can be used without any installation. The Command Line Interface (also known as the Command Prompt in Windows) is less of a graphical interface and allows you to enjoy easy navigation between your directories (directories refer to folders).</p><p>The command-line utilities are used to navigate, search, open, and list files, among others. Towards the end of this article, you will be introduced to shell scripting and we‘ll be creating a game with Bash. So let’s get into it.</p><p><strong>1. </strong><strong>mkdir</strong> (Make directory): This is used to make a new directory within the current directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*jgchyZmK5Balfp5NFQOnrg.png" /><figcaption>Creating a directory called example</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*jnGA92vF0kwI6wye8ZowUg.png" /><figcaption>Creating a new directory in the example directory</figcaption></figure><p><strong>2. </strong><strong>cd</strong>(Change Directory): This is used to change the current directory to another. You can specify more than one directory by adding the forward-slash /after each directory. You can also move a level up with cd .. and to the previous directory with cd -.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*wkGO65MbtsGHLLrYjKSQ3Q.png" /><figcaption>Changing the current directory to the another called example</figcaption></figure><p><strong>3. </strong><strong>pwd</strong> (Print Working Directory): This is used to check your current working directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*fbtgc-Gkr2o_n8HcZCPbrQ.png" /></figure><p><strong>4. </strong><strong>touch</strong>: This is used for creating new files in your current directory and also to modify file timestamps.</p><p>touch -m &lt;filename&gt; — Modifying the timestamp of a file to the current date</p><p>touch &lt;filename&gt; — Creating a new file</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*UKmXbYiRIAEQ_GhxvX11Sw.png" /><figcaption>Creating a new file called hello.txt</figcaption></figure><p><strong>5. </strong><strong>cat </strong>(Concatenate): This is used to print the content of a file to the command line screen. It is also used to append file contents in a new or existing file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*zGU490JL3lWIGvDUnuWOoQ.png" /><figcaption>Here, the cat command is used to print the text in random.txt</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*Iud2n6D0_6m8MYcaHXeefQ.png" /><figcaption>Here, the cat command is used to create and append three files (text1, text2 and text3) into a new file (reports)</figcaption></figure><p><strong>6. </strong><strong>ls</strong> (List): This is used for listing all content within a specified directory. ls would usually list all files and directories in the current folder unless a directory is specified.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*UKmXbYiRIAEQ_GhxvX11Sw.png" /><figcaption>The only file listed in the example directory is what we’ve created with the touch command</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*JDBQm9D3Dm8eqBV0dnV8lg.png" /><figcaption>Here, more files and a directory is listed in the same directory</figcaption></figure><p>ls can also be used with unique options or tags, they include;</p><ul><li>-l: this means the long listing format. It gives more information about the content in the directory, whether it is; a file or directory, writeable or a read-only life, etc.</li><li>-a: this means all. That is, also includes hidden files. Note that hidden files begin with a dot(.).</li><li>-h: this means human-readable format and it is usually used with -l. It prints the size of the files. For example ls -lah.</li><li>-r: this means a reserve-order sorting.</li><li>-t: this means a sort by modified time. For example ls -trh.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*dEtZFouyTUsGTmv4leKRjA.png" /><figcaption>Playing around with ls and its options</figcaption></figure><p><strong>7. </strong><strong>echo</strong>: This is more like a print syntax. It is used to print characters to the screen. This is also used to append words to a file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*qh4g_q-dTL3eJQAj_Ieu_w.png" /><figcaption>Here, the echo command is used to append words to a file called index and we can view the content of the file with the cat command</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*VNCmia9B4zZ2-n6tFcQFVw.png" /><figcaption>echo is used to print words to the command line screen</figcaption></figure><p><strong>8. </strong><strong>less</strong>: Use this command when you want to view a large text file on the command line. Use the format less [filename] , the arrow keys to move and type q to exit.</p><p><strong>9. </strong><strong>rm</strong> (Remove): This is used to delete specified files in the current directory or the directory specified. To remove a directory, add the option -r, this would delete the directory even if it is not empty.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*QmJPYxBaeHsUpsNYVgwl7A.png" /><figcaption>The rm command here is used to delete the file hello.txt</figcaption></figure><p><strong>10. </strong><strong>rmdir</strong> (Remove Directory): Use this to delete a specified empty directory.</p><p>Note: Be careful while using rm and rmdir as you can not retrieve the file or directory you deleted with these commands.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*Zg1jzK82U2_8TfYvVHz_vg.png" /><figcaption>A directory called cat was created and deleted with <em>rmdir </em>command</figcaption></figure><p><strong>11. </strong><strong>cp</strong> (Copy): This command is used to copy the context of one file to another file or duplicate a file. When copying to an existing file, it overwrites the previous text to the new one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*67p3zAxyRPGJlNqJsTerBw.png" /><figcaption>Here cp command is used to duplicate random.txt</figcaption></figure><p><strong>12. </strong><strong>mv</strong> (Move): This is used for cutting the content of one file to another. It can also be used to rename a file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*2JV-wLtijsgkPoo8TYgrQg.png" /><figcaption>The file was renamed from reports to AllReport with the mv command</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*e9150P2CRnhOCGXQF-rfFw.png" /><figcaption>AllReport has moved a level up with the mv command</figcaption></figure><p><strong>13. </strong><strong>wc</strong> (Word Count): Use this command to count lines, words or characters in a file. Use -w to specify word count.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*It7OPiJnKQQCqqOywy9Vrg.png" /><figcaption>the file contains 1 line, 31 words and 194 reports</figcaption></figure><p><strong>14. </strong><strong>grep</strong> (Global Regular Expression Print): This is used to search for strings within a specified file. Use grep as follows; grep [options] [string] [specified file].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*C6qseZz97c9T2nKTZS0lkA.png" /><figcaption>The word index is contained in the index file, having 2 occurrences in that file.</figcaption></figure><p><strong>15. </strong><strong>which</strong>: This command points to where an application, command or binary is located on your system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*mo3gJD8TnujBGfs6_Pfetw.png" /></figure><p><strong>16. </strong><strong>history</strong>: This is not a command but a built-in keyword of your shell. It gives you a list of all the commands you ran during the terminal session. To search for a specific command, use the grep command with history . For example, history | grep ls.</p><p><strong>17. </strong><strong>alias</strong>: This is used to replace a length of code to what you refer. It serves as a shortcut for commands. You can check all your alias by typing the command alias. Use alias in the format alias [option] [name] = “[value]”.</p><p><strong>18. </strong><strong>chmod (</strong>Change Mode<strong>)</strong> : This command is used to change a file mode to read -r , write -wor executable -x. It is mostly used to make a file executable.</p><p><strong>19. </strong><strong>ping (</strong>Packet Internet Groper<strong>)</strong>: This command is used to manually test the network connection. For example pink <a href="http://www.google.com/">www.google.com</a>.</p><p><strong>20. </strong><strong>tail</strong> : This command is used to print the last ten lines of a text file in the command terminal. Use -n to specify the number of lines, for example, tail -n 4 [filename].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*IVVTR6xQgOqcpCqeUj_R2g.png" /></figure><p><strong>21: </strong><strong>head</strong> : This is a command-line utility that is used to print the first ten lines of a text file in the command interface. You can specify the number of lines with -n . For example head -n 4 [filename].</p><p><strong>22: </strong><strong>whoami</strong> : This is short for who am I. It prints the user name associated with the system.</p><p><strong>23: </strong><strong>unzip</strong> : This is a command-line utility that is used to unzip zipped files. To get more information on how to use this command, type unzip in your terminal and press the enter key.</p><h3>Shell Scripting</h3><p>The shell is an interpreter that allows you to connect to a kernel to execute your programs. A kernel is an important part of your operating system. It is a low-level language that makes for interaction between the software and hardware components.</p><p>A Shell script is a file that contains programs that are executed by the command-line interpreter. They are usually used for operations that are system related. Bash is a type of shell, also known as Bourne Again shell.</p><p>For this tutorial, we will create a script that allows you to log in and play a guessing game. You can use any other editor of your choice.</p><p>To start with, create a directory, then change your current directory to the just created one and create a file called <em>game.sh</em>.</p><p>After coding, make the file an executable file with the chmod command and run the script withbash game.sh</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*v4C8NUMBDHCtctaD7XZTRQ.png" /><figcaption>step-by-step to creating a guessing game with bash</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/992bf1787cc90af43f32f3676a4a206e/href">https://medium.com/media/992bf1787cc90af43f32f3676a4a206e/href</a></iframe><p>At the beginning of the script, add the shebang (sharp exclamation). This means the script should run in bash. The syntax read is used for standard input in bash, read -p allows for a placeholder in the standard input and read -sp allows for a placeholder and a silent-type input for passwords. Then next is the <em>if clause</em> to verify that the username and password both contain the string <em>admin</em>, otherwise, the process with exit. If this is passed, then we initiate the game by defining three variables; guess, count and answer then use the <em>which loop</em> to read in guess input and check if it is equal to the system guess (answer).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*CBuJD_65Lv-yrg5LUZ04lA.png" /><figcaption>Results of game.sh</figcaption></figure><p>I hope you learned a few things. If you encountered any difficulties in the commands, simply type the command followed by (double hyphens and the string ‘help’) — help to check on the use case of that command. For example cp — help. Remember to practice to improve your coding experience.</p><p>Please follow me and leave a clap.</p><p>God bless!</p><h3>Reference</h3><p>The Linux Shell and Commands — <a href="https://www.cs.dartmouth.edu/~campbell/cs50/shell.html">https://www.cs.dartmouth.edu/~campbell/cs50/shell.html</a></p><p>Use of Shell Scripting — <a href="https://www.educba.com/uses-of-shell-scripting/">https://www.educba.com/uses-of-shell-scripting/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f0e84d76a8e" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/using-the-command-line-and-shell-scripting-1f0e84d76a8e">Using the Command-Line and Shell Scripting</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting up Nestjs with PostgreSQL]]></title>
            <link>https://blog.devgenius.io/setting-up-nestjs-with-postgresql-ac2cce9045fe?source=rss-b69eac0a6820------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac2cce9045fe</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[servers]]></category>
            <dc:creator><![CDATA[Dorcas Olajide]]></dc:creator>
            <pubDate>Wed, 16 Mar 2022 10:52:31 GMT</pubDate>
            <atom:updated>2022-11-21T17:15:41.202Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UYEU0kBJB9srtdQm" /><figcaption>Photo by <a href="https://unsplash.com/@casparrubin?utm_source=medium&amp;utm_medium=referral">Caspar Camille Rubin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>NestJS is a framework used to create server-side NodeJS applications. I recently started working with NestJs and I would like to share how you can connect a simple server-side application with a running PostgreSQL database. We will also be creating routes to run the post and get requests from our database. You can view the full <a href="https://github.com/DorcasOJ/nestjs-with-progreSQL">GitHub code here</a>.</p><p>PostgreSQL is one of the popular SQL used in the testing and deployment phase. If you haven&#39;t installed PostgreSQL, go ahead and <a href="https://www.postgresql.org/download/">download it here</a>. After installation, you will provided a new server and database but you’ll need to create a new database for this project.</p><h4>Steps on how to create a new database in Postgres</h4><ul><li>First, open pgAdmin (this is a GUI installed with PostgreSQL), when opening the server you’ll be prompted for a password for your servers, make sure you remember it.</li><li>Then create a new database in your current running server, let’s call it <em>work_db</em>, the default database is <em>postgres</em>, but you’ll have to change it to work_db</li><li>To change it, right-click on the server, click on <em>Disconnect Server</em> and follow the prompt.</li><li>Then right-click again and click <em>Properties, </em>go to the <em>Connection</em> tab and edit <em>Maintenance Database</em> field to <em>work_db</em> or the name of your new database and click save</li><li>Lastly right-click the server again and click <em>Connect Server</em></li></ul><p>Now that your PostgreSQL setup is complete, we need to set up NestJs.</p><p>i. To start with, download and install <a href="https://nodejs.org/en/download/">NodeJs</a>. This will also install Node Package Manager (npm) and we will be using that to install NestJs and other packages.</p><p>ii. In your command-line interface install NestJs with the following code, replace project-name to your preference</p><pre>npm i -g @nestjs/cli</pre><pre>nest new project-name</pre><p>We&#39;ll be installing other packages that we need soon</p><p>iii. To start the server, open your new project in vs code, navigate to the terminal, make sure you are in the project directory and type</p><pre>npm run start:dev</pre><p><strong>Note: we’ll be using typescript for this tutorial.</strong></p><p>Let’s quickly understand a few concepts in NestJs. These are crucial to understanding the project.</p><h3>Controllers</h3><p>Controllers are charged with receiving requests from clients and giving responses depending on what was programmed. They are used for routing, defining endpoints with resources, defining routes with parameters, redirecting, defining status code for different endpoints, and so on. To use the controller in typescript, you need to use the nest controller decorator @Controller() followed by its associated class, you can also add an optional route path to a controller, for example@Controller(‘users’). A controller can have as many endpoints or resources as possible. For instance, we can use the Get decorator attached to a method to fetch all customers in a database, and a post decorator with the endpoint <em>create</em> to create a new user.</p><pre>@Controller(‘users’)</pre><pre>export class UsersController { </pre><pre>constructor(private readonly userService: UsersService) {} </pre><pre>@Get() <br>getUsers() { return this.userService.getUsers(); }</pre><pre>@Post(&#39;create&#39;)  <br>createUsers(@Body() createUserDto: CreateUserDto) { return this.userService.createUser(createUserDto); }</pre><pre>}</pre><p>More about controllers are in the NestJs documentation <a href="https://docs.nestjs.com/controllers">here</a>.</p><h3>Providers</h3><p>Providers are most of the time classes, that can be injected as a dependency to other classes such as the controller class. They are used as services for controller resources. In the code above, <em>UserService</em> was injected into the user&#39;s controller, this served as a dependency for the user&#39;s controller and we can therefore use<em> userService</em> methods in the controller&#39;s class.</p><h3>DTOs</h3><p>DTOs are short Data Transfer Objects. They can be interfaces objects that determine how data will be sent in a post request body and response, thereby adding structure to your code. In the code above, <em>CreateUserDto</em> was used to structure the request body of <em>create</em> endpoint.</p><h3>Configuration</h3><p>The workings of NestJs configuration module is quite similar to that of NodeJs dotenv package. It helps you use environment variables for sensitive data. It enables you to create a <em>.env </em>file where you can store sensitive variables and use them in your code. You have to add the <em>.env</em> path to the <em>.gitignore</em> file before pushing it to your git repository.</p><h3>TypeOrm</h3><p>TypeOrm is an Object Relational Mapper (ORM) typescript package that allows you to use both SQL such as PostgreSQL, MySQL and NoSQL databases. More about typeorm is in its <a href="https://typeorm.io/#/">documentation</a>.</p><h3>Modules</h3><p>Both the controllers are provider classes are defined in the module. You can decide to create a different module for different functions, for example, the <em>users’ module </em>for all users’ functions<em>.</em> These sub-modules would be imported to the app module which is the main app module for our project. Other needed modules are also imported in the <em>module.ts</em> file, such as the typeorm module, configuration module, and so on.</p><p>By now you should have created your PostgreSQL database and have your NestJS project running.</p><p>In the <a href="https://github.com/DorcasOJ/nestjs-with-progreSQL">GitHub code</a>, two modules were created, the user’s module and the customer’s module. But in this article, we’ll be creating a module, <em>users module</em>, which will have its database table that we will be creating soon. Then we will define functions to send and get information from the database through our service (provider) typescript file and inject them into the controller. At the end of this, you should have a functioning database setup and routes to post and get structured information.</p><h3>Step By Step Guide</h3><p>This is how your code will be structured after creating your NestJs project</p><pre>nest new project-name</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lDVXx2xLJ_-9IFvdoDj0jw.png" /><figcaption>vscode nestjs setup</figcaption></figure><p>If you have something like this, then you can follow this step-by-step procedure. Don&#39;t forget to start your NestJs server</p><pre>npm run start:dev</pre><p><strong>1. Restructuring your code — Deleting and adding needed files to your project directory</strong></p><p>We’ll be creating a new module that will have a controller and a service so delete <em>app.controller.ts, app.controller.spec.ts </em>and<em> app.service.ts</em></p><p>Make sure your <em>app.module.ts </em>file in your <em>src </em>folder looks like this</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c2356d508ee1c372ff4e0738e35188c/href">https://medium.com/media/5c2356d508ee1c372ff4e0738e35188c/href</a></iframe><p>Then in your vscode terminal, move to the project directory and run each line of code below.</p><pre>nest generate module users</pre><pre>nest g controller users/controllers/users</pre><pre>nest g service users/services/users</pre><p>If you check your <em>app.module.ts </em>in your <em>src</em> directory you will see that <em>usersModule </em>has been added to your imports. Making use of the command line ensures all necessary imports are done.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1c4e8b53b2b0d428f43710ca2729bdd2/href">https://medium.com/media/1c4e8b53b2b0d428f43710ca2729bdd2/href</a></iframe><p><strong>2. Connecting to PostgreSQL with typeORM</strong></p><p>In our app.module.ts, we need to import the typeOrmModule, but before that, we have to set up our dotenv file, to do so install the following in your terminal.</p><pre>npm install @nestjs/config</pre><p>In the project’s directory add a <em>.env</em> file and add database variables in this format. Make sure the variables conforms to your settings in pgAdmin. This is where you use the password you set in pgAdmin.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/90e291f15fdfd3758c76a51be61e6d6a/href">https://medium.com/media/90e291f15fdfd3758c76a51be61e6d6a/href</a></iframe><p>Then add ConfigModule to your <em>app.module.ts</em> imports, don’t forget to import it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/54ec764b82f765cc648786dbb0058ca8/href">https://medium.com/media/54ec764b82f765cc648786dbb0058ca8/href</a></iframe><p><em>ConfigModule.forRoot()</em> will load and parse your <em>.env</em> file. The setting <em>isGlobal: true </em>will automatically import ConfigModule to all other modules, which means you do not need to import it in <em>Users.module.ts</em> file. Instead of using process.env.variableName, we’ll be using</p><pre>configService.get(‘VariableName’)</pre><p>Then let’s move ahead to typeorm, install the packages stated below in your terminal.</p><pre>npm install @nestjs/typeorm typeorm</pre><pre>npm install pg</pre><p>TypeOrm connection configuration options include;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a933c8c99262e2b3748558e3f649ebab/href">https://medium.com/media/a933c8c99262e2b3748558e3f649ebab/href</a></iframe><p>In the code above, <em>type </em>specifies what type of database you want to use, <em>host</em>, <em>port</em>, <em>username</em>, <em>password</em> and <em>database</em> are all enquires about the database that you need to provide. <em>Entities are used</em> to create tables from your project to your database, <em>synchronize</em> help you to effect changes being made in your code immediately to your database. However, you need to turn this off during production. Now let&#39;s import TypeOrmModule in <em>app.module.ts</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/44751b35a0a7b6623b455d231f362229/href">https://medium.com/media/44751b35a0a7b6623b455d231f362229/href</a></iframe><p>We could use TypeOrmModule.forRoot({…}) and enter the configuration options but because we are loading environment variable from the <em>.env </em>file we need to import ConfigModule and inject ConfigService first. We have not defined any entity so we leave it empty for now. If you didn’t get an error you can move to the next step or check <a href="https://github.com/DorcasOJ/nestjs-with-progreSQL">the GitHub repository</a>.</p><p><strong>3. Creating tables or entities</strong></p><p>We’ll be creating tables classes with @Entity decorators. Create a new folder in your <em>src</em> directory called <em>typeorm</em> then create a user entity file <em>user.entity.ts</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a27732b72f1044cf304d7b1b8c46b9ea/href">https://medium.com/media/a27732b72f1044cf304d7b1b8c46b9ea/href</a></iframe><p>This entity would create a User table of four columns, a primary generated Id with the name <em>user_id</em> and type <em>bigint, </em>username, email and password with the nullable option of <em>false</em> and default set to empty string.</p><p>Then create an index file and export <em>User</em> and <em>entities</em>. We need <em>entities </em>to be an array of entities.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/97ac263cb1383e6832560d6abb0d67f1/href">https://medium.com/media/97ac263cb1383e6832560d6abb0d67f1/href</a></iframe><p>We can now replace the <em>entities</em> option in app.module.ts with the <em>entities</em> described above.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d2db75185d84ef71dbc201585f21408/href">https://medium.com/media/7d2db75185d84ef71dbc201585f21408/href</a></iframe><p><strong>4. Posting and getting data from tables</strong></p><p>Here we’ll be connecting the users’ table to the users&#39; module.</p><p>In <em>users.module.ts </em>imports,<em> add TypeOrmModule.forFeature([User]). </em>This will allow us<em> to </em>use typeOrmModule as well as the user’s table in this module. The <em>User</em> entity has its in-built repository, which we would be accessing to send and get information in the database table.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b40be36cad6b13f648c84a59ea306c2/href">https://medium.com/media/0b40be36cad6b13f648c84a59ea306c2/href</a></iframe><p>We also need to create a dto for our user endpoint request body. In users directory, create dto folder, in it a file called <em>users.dtos.ts.</em> Then install class-validator.</p><pre>npm install class-validator </pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7cb38e31048cb3bad0ad7e57b9225185/href">https://medium.com/media/7cb38e31048cb3bad0ad7e57b9225185/href</a></iframe><p>Nestjs allows us to use validation decorators for dtos such as @IsNotEmpty, @IsEmail, this class validators will serve as validation for our request body and response.</p><p>Now that typeOrm has been added to the users’ module, we can now access <em>User</em> repository to post and get data from our <em>User</em> table in our <em>users.service.ts</em> file (under your services/user directory).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/319dcb9d7e8af12b256b7bfaf0b7e23d/href">https://medium.com/media/319dcb9d7e8af12b256b7bfaf0b7e23d/href</a></iframe><p>This service injectable class can be added as a dependency in the class constructor of our controller.ts file, therefore we can use the methods specified in <em>UserService</em> in <em>controller.ts</em>.</p><p>Finally, In <em>users.controller.ts</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9dd157a53883b2169f26f8c111bed69d/href">https://medium.com/media/9dd157a53883b2169f26f8c111bed69d/href</a></iframe><p>in the code above, <em>UsePipes</em> decorator is an injectable that allows you to transform and validate input data to your desired format. <em>ValidatePipe</em> allows us to validate our request body, ensuring that our json data is in the <em>CreateUserDto</em> format.</p><p>To get properties of request, for instance, the request body, you need to specify the property from request (that is request.body) but nestjs have dedicated decorators that you can use instead such as @Param(), @Body(). These allow us to get and parse information specific to our request.</p><h3>Results</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-0MVVNg-oS-72Otz7miU8g.png" /><figcaption>Get /users</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*Ff8yaA_l58smhpYMrMNDVQ.png" /><figcaption>Post /users/create</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*XRP2ndqHrFttn4P7yGVPOg.png" /><figcaption>Get users/:id</figcaption></figure><p>I hope you learned a few things. If you encountered any errors or need to add one more module to your project you can <a href="https://github.com/DorcasOJ/nestjs-with-progreSQL">check the GitHub repository</a>.</p><p>You can also connect with me on <a href="https://www.linkedin.com/in/dorcas-olajide-a914b814b">LinkedIn </a>or <a href="https://twitter.com/Aydorcas/">Twitter</a>.</p><p>Please leave a clap or a comment.</p><p>God bless!</p><h3>References</h3><p>NestJs Tutorial Series — <a href="https://youtube.com/playlist?list=PL_cUvD4qzbkw-phjGK2qq0nQiG6gw1cKK">https://youtube.com/playlist?list=PL_cUvD4qzbkw-phjGK2qq0nQiG6gw1cKK</a></p><p>NestJs Documentations— <a href="https://docs.nestjs.com/">https://docs.nestjs.com/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac2cce9045fe" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/setting-up-nestjs-with-postgresql-ac2cce9045fe">Setting up Nestjs with PostgreSQL</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Closures in Python]]></title>
            <link>https://blog.devgenius.io/understanding-closures-in-python-1b128dde1407?source=rss-b69eac0a6820------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b128dde1407</guid>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[closures-functions]]></category>
            <category><![CDATA[function]]></category>
            <category><![CDATA[nested-functions]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Dorcas Olajide]]></dc:creator>
            <pubDate>Sat, 04 Dec 2021 21:16:02 GMT</pubDate>
            <atom:updated>2024-03-10T16:41:46.184Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DMg34HTiqRLoogYA" /><figcaption>Photo by <a href="https://unsplash.com/@agforlclassic?utm_source=medium&amp;utm_medium=referral">Tai Bui</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Closures are nested function(s) where the inner functions can access variables declared in the outer function and the outer functions keeps reference to the inner function memory space location as well as other objects defined in its local scope.</p><p>Before further explanation, there are prerequisites to better understand closures. They include:</p><ol><li>Namespace</li><li>Scope</li><li>Function</li><li>Reference</li><li>Nonlocal keyword</li></ol><h4>1. Namespace</h4><p>Namespace in python is a system or structure that are use to assign declared functions or any object to unique names. You can think of a python dictionary that stores unique keys to different values or think of your computer’s file system, where two files in the same directory cannot share one unique name. The keys or filenames represent unique names and the values or files represent object.</p><p>We can further divide namespace into:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/1*62gm0TfYM4LwnpQ214qUUQ.png" /></figure><p>i. Built-in Namespace: these are namespace built-in with python and created when the python interpreter runs. Some of the bultins unique namespaces include; ‘__name__’, ‘enumerate’, ‘globals’, ‘input’, ‘isinstance’, ‘len’, ‘license’, ‘list’, ‘locals’, ‘map’, ‘max’, ‘min’, ‘next’, ‘print’, ‘range’, ‘round’, ‘set’, ‘sorted’, ‘str’, ‘sum’, and ‘type’. You can view all the builtins by printing <em>dir(__builtins__)</em> in your python terminal. In a python module, within the built-in namespace, we have the global namespace.</p><p>ii. Global Namespace: This include variables, functions, classes, dictionaries etc., and their respective unique names defined in the global scope of a module. When a module programs begins, python creates a global namespace for your current and imported modules. The global namespace can be seen by printing <em>globals()</em> in your python terminal. Within the global namespace we have local namespace.</p><p>iii. Local Namespace: This include variables and methods declared within a function, classes, loops, or any object in a module. They are created when the object (that is the function, loop, or class) is being executed. They can be access by printing <em>locals()</em> in any function scope.</p><h4>2. Scope</h4><p>Scope is an aspect of a program where an object name or variable name is relevant. We have the global scope which is the body of the module or script and is thus attributed to the global namespace, and the local scope which is a discrete space in memory for object or variables defined within an object. Variables in scope are only relevant in descending order (as listed under namespace section) and not the reverse. So a variable declared in a local namespace is not relevant in the global namespace except if such is returned by a function to the global scope.</p><p>Because a variable declared in a scope is unique, if such name is use to bind a new variable, the object attributed to the old variable is replaced unless if it was previously assigned to another variable. In this way all object in a scope has a unique name.</p><h4>3. Function</h4><p>A function is a block of code that only runs when it is called. It begins with the syntax <em>def.</em></p><h4>4. Reference</h4><p>A reference in python is a variable that stores the memory address of an already existing object. A reference, when called, is automatically dereference (as oppose to pointers) thereby returning the value at such address.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0a6c69f82d52928f3d94e2d8601d012b/href">https://medium.com/media/0a6c69f82d52928f3d94e2d8601d012b/href</a></iframe><p>In the script above, variable <em>x</em> and <em>a</em> are defined in the global scope as global variables and are therefore added to the global namespace. We can see this by printing the function <em>globals</em> (line 6 — 16). Functions contains variables which are in local to it scope, and as local variables they are added to the local namespace (line 29). In <em>my_func </em>(line 20), it was possible to print a global variable but impossible to modify it except with the <em>global </em>keyword as seen in <em>my_func_global </em>(line 33). With the <em>global</em> keyword it was possible to update the global variable in the global namespace from a local scope, as the variable <em>x</em> has now been updated from integer 50 to integer 100 from the from <em>my_func_global </em>(line 34 — 35)<em>.</em></p><h4>5. Nonlocal keyword</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/00935b48ab676a4f07609fc73ff2998b/href">https://medium.com/media/00935b48ab676a4f07609fc73ff2998b/href</a></iframe><p>The nonlocal keyword is used in a nested function. It is use to render variable(s) that belong the outer function for modification in an inner function. Because outer functions variables do not belong to the inner function therefore the nonlocal keyword are use give access to modify such variables. In the example above, a local variable (<em>number</em>) to the outer function <em>calculator </em>was modified in the inner function <em>add </em>without an error because the nonlocal keyword was used on the variable <em>number</em></p><h3><strong>Back to closures</strong></h3><p>A nested function only becomes a closure if it returns it inner function and it inner function contains a free variable. A <strong>free variable</strong>, in closures, is a variable that reference values of objects that are local to its outer function. Such variable are not local to the inner function but used by it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f85ff6fa3f18d899b06baa6b6babfe0/href">https://medium.com/media/4f85ff6fa3f18d899b06baa6b6babfe0/href</a></iframe><p>At the function definition of <em>calculator</em>, python creates a function object in the memory space which stores reference to the object variables that would be created at the execution. These variables are local to it scope.</p><p>At execution, python creates a new local scope for <em>calculator</em> function by creating a stack frame to contain it local variables. A <strong>stack</strong> here is a segment of the computer memory use to store information on functions and local variables. A <strong>stack-frame</strong> is use to create a function scope for the execution of a function body, it is a portion of the stack set aside for one function and it live until the complete execution of the function body.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/185/1*EUIOcZxxoSgLtZu_l6w8jw.png" /><figcaption>Stack-frame for calculator function</figcaption></figure><p>Therefore <em>calculator </em>function<em> </em>gets its own stack frame. In that frame it stores reference to objects defined in its local scope, for example, {number: 10, add: 0x7f9820bb1a50}. This is synonymous to local namespace of unique names and its corresponding objects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*Eo1OF0tzuOuApTKUkweh0g.png" /><figcaption>The workings of calculation function</figcaption></figure><p>While <em>number</em> stores a unique reference to the integer, <em>add</em> stores a unique reference to another function object in some memory space (at this point, <em>add</em> function is not yet executed).</p><p>The reference <em>number</em> variable points to (both in the outer and inner function) can also be known as <strong>cell object</strong>. This makes it easier for any inner function to access and update its free variable(s). The cell object is an intermediary memory address that stores a reference to the to the free variable object located in the memory, so whenever the free variable is updated, the cell object points to its new address (line 13).</p><p>Usually, after the execution of a function, usually the stack frees the function from memory, but in closures instead of freeing the memory, if there is any object in the outer function referenced by the inner function, it keeps that object in the stack frame for future use.</p><p>In the first example above, <em>add_cal </em>is the return value of calculation function, that is, it gets the value of what is being return by the outer function <em>calculator</em> which is inner function <em>add</em>. Remember that at the execution of the outer function <em>calculator</em>, <em>add, </em>though not yet executed<em>,</em> stores a references to its object function. This is now contained in <em>add_cal </em>after the execution of <em>calculator</em> function(line 10).</p><p>Also, <em>add_cal</em> does not only contain its local variables (<em>numb_to_add</em>), but also a free variable (<em>number</em>) which is not local to it but used by it (line 12 &amp; 14). Though the outer function (<em>calculator</em>) execution is completed and out of memory, the free variables are stored and can now be updated within the inner function. If the inner functions of a nested function contain free variables and these inner functions are return values of the outer functions, then closure exist.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c8a4d327a2384a1ecf368184b62da125/href">https://medium.com/media/c8a4d327a2384a1ecf368184b62da125/href</a></iframe><p>Again, at the execution of the outer function, its local values can no longer be reinitialized in that same instance (line 10), and at every execution of the inner function the variable local to it are reinitialized but not the free variable. Free variables at this point can only be updated or modified. Because free variables can not be initialized but modified by closures, closures can be said to be a function that stores data (line 16 — 17).</p><p>For every new instances of closure we create (line 10 &amp; 19), the program created a new free variable that can only be accessible within the different particular instance (line 20 — 22).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d6faf01b146ac604f05a3496089bb489/href">https://medium.com/media/d6faf01b146ac604f05a3496089bb489/href</a></iframe><p>In the script above, both the inner functions have access to modify the free variable. This is a concept of shared free variables, where free variables can be used and modified by both inner functions.</p><p>In the script below, <em>grocery_list </em>is a variable local to the outer function, after the use of nonlocal keyword in the inner function, it becomes a free variable and is therefore modified by inner function even after the complete execution of the outer function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dab4c761c3404341d0fc521023b25613/href">https://medium.com/media/dab4c761c3404341d0fc521023b25613/href</a></iframe><h3>Closures and Classes</h3><p>Though closures and classes are different in syntax, in term of functionality they are the same. In deciding what to use, it depends on what you think it’s best for what you are trying to program in python.</p><h3>Conclusion</h3><p>I hope you have been able to learn few things on closures in python. You can try it out on your own project. If you have existing program that contains classes with one or two method, you can choose to write them with closures instead. Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b128dde1407" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/understanding-closures-in-python-1b128dde1407">Understanding Closures in Python</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>