<?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 Emmanuel Adebanjo on Medium]]></title>
        <description><![CDATA[Stories by Emmanuel Adebanjo on Medium]]></description>
        <link>https://medium.com/@adebanjoemmanuel01?source=rss-fc2aede653be------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*-AHF9Jfg3RZQN3HftIuvZg.jpeg</url>
            <title>Stories by Emmanuel Adebanjo on Medium</title>
            <link>https://medium.com/@adebanjoemmanuel01?source=rss-fc2aede653be------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 01:34:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@adebanjoemmanuel01/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[Synchronous Asynchrony]]></title>
            <link>https://medium.com/@adebanjoemmanuel01/synchronous-asynchrony-244226cea9b9?source=rss-fc2aede653be------2</link>
            <guid isPermaLink="false">https://medium.com/p/244226cea9b9</guid>
            <category><![CDATA[await]]></category>
            <category><![CDATA[asynchronous-programming]]></category>
            <category><![CDATA[async]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[asyncawait]]></category>
            <dc:creator><![CDATA[Emmanuel Adebanjo]]></dc:creator>
            <pubDate>Sun, 27 Sep 2026 13:12:21 GMT</pubDate>
            <atom:updated>2026-09-27T13:12:21.200Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oGPEanHVrRDDUQPTE830Fg.png" /></figure><h3>When await Makes Asynchronous Code Run Sequentially in C#</h3><p>One of the most common misunderstandings about asynchronous programming in C# is:</p><blockquote><em>“If I use </em><em>async and </em><em>await, my code runs concurrently.&quot;</em></blockquote><p>Not necessarily.</p><p>async and await allow asynchronous operations to be performed without blocking a thread, but <strong>the placement of </strong><strong>await can cause operations to execute sequentially</strong>.</p><p>Understanding this distinction is essential when working with asynchronous C# code.</p><h3>The sequential case</h3><p>Consider:</p><pre>async Task DoWork()<br>{<br>    await Task1();<br>    await Task2();<br>    await Task3();<br>}</pre><p>It is tempting to look at this and think:</p><blockquote><em>“All three tasks are asynchronous, so they should run at the same time.”</em></blockquote><p>But that’s not what this code says.</p><p>The code creates a dependency:</p><pre>Start Task1<br>     |<br>     v<br>Wait for Task1<br>     |<br>     v<br>Task1 completes<br>     |<br>     v<br>Start Task2<br>     |<br>     v<br>Wait for Task2<br>     |<br>     v<br>Task2 completes<br>     |<br>     v<br>Start Task3</pre><p>If each operation takes approximately one second, the total time could be around three seconds.</p><p>The operations are asynchronous, but they are being <strong>awaited sequentially</strong>.</p><h3>What does await actually mean?</h3><p>When you write:</p><pre>await Task1();</pre><p>you’re essentially telling the method:</p><blockquote><em>“Start this asynchronous operation, and don’t continue executing this method past this point until the operation has completed.”</em></blockquote><p>Importantly, this does <strong>not</strong> necessarily mean:</p><blockquote><em>“Block the current thread.”</em></blockquote><p>That’s a different concept.</p><p>While the asynchronous operation is in progress, the thread can be released to perform other work.</p><p>So:</p><pre>Sequential operations<br>        ≠<br>Blocking a thread</pre><p>This is a very important distinction.</p><h3>How do we start operations concurrently?</h3><p>Suppose we have:</p><pre>Task Task1()<br>Task Task2()<br>Task Task3()</pre><p>Instead of immediately awaiting each one:</p><pre>await Task1();<br>await Task2();<br>await Task3();</pre><p>we can start them first:</p><pre>var task1 = Task1();<br>var task2 = Task2();<br>var task3 = Task3();</pre><pre>await Task.WhenAll(task1, task2, task3);</pre><p>Now the operations have all been started before we wait for their completion.</p><p>Conceptually:</p><pre>┌── Task1 ──────────────┐<br>             │                        │<br>Start ───────┼── Task2 ──────────────┼──&gt; All complete<br>             │                        │<br>             └── Task3 ──────────────┘</pre><p>If each operation takes approximately one second, the total time may be closer to one second rather than three.</p><h3>Task.WhenAll</h3><p>This pattern is particularly useful when the operations are independent.</p><p>For example:</p><pre>var customerTask = GetCustomerAsync();<br>var ordersTask = GetOrdersAsync();<br>var paymentsTask = GetPaymentsAsync();</pre><pre>await Task.WhenAll(<br>    customerTask,<br>    ordersTask,<br>    paymentsTask);</pre><p>There is no reason to wait for the customer request before starting the orders request if the three operations don’t depend on one another.</p><p>Starting them first allows their waiting time to overlap.</p><h3>When should you use sequential awaits?</h3><p>Sometimes sequential execution is exactly what you want.</p><p>Suppose:</p><pre>var customer = await GetCustomerAsync();</pre><pre>var orders = await GetOrdersAsync(customer.Id);</pre><p>Here, GetOrdersAsync() requires the customer&#39;s ID.</p><p>Therefore, we cannot start the second operation until the first one has completed.</p><p>The dependency looks like:</p><pre>GetCustomerAsync()<br>       |<br>       v<br>Customer ID<br>       |<br>       v<br>GetOrdersAsync(customer.Id)</pre><p>Trying to make these concurrent wouldn’t make sense because the second operation depends on the result of the first.</p><h3>The key distinction: concurrency vs asynchronous execution</h3><p>This is where many explanations of async/await become confusing.</p><p>These are different concepts:</p><h3>Asynchronous</h3><p>An operation can be started without blocking the calling thread while it waits for completion.</p><h3>Concurrent</h3><p>Multiple operations can make progress during overlapping periods of time.</p><p>You can have asynchronous code that is still sequential:</p><pre>await A();<br>await B();<br>await C();</pre><p>And you can have asynchronous code where independent operations overlap:</p><pre>var a = A();<br>var b = B();<br>var c = C();</pre><pre>await Task.WhenAll(a, b, c);</pre><h3>A simple analogy</h3><p>Imagine ordering three meals.</p><h3>Sequential</h3><p>You order meal A and wait until it’s ready.</p><p>Then you order meal B and wait.</p><p>Then you order meal C and wait.</p><pre>Meal A ──────&gt;<br>             Meal B ──────&gt;<br>                          Meal C ──────&gt;</pre><h3>Concurrent</h3><p>You place all three orders first:</p><pre>Meal A ──────&gt;<br>Meal B ──────&gt;<br>Meal C ──────&gt;</pre><p>Then you wait until all three are ready.</p><p>That’s essentially the difference between:</p><pre>await A();<br>await B();<br>await C();</pre><p>and:</p><pre>var a = A();<br>var b = B();<br>var c = C();</pre><pre>await Task.WhenAll(a, b, c);</pre><h3>The important takeaway</h3><p>async does not mean:</p><blockquote><em>“Run everything concurrently.”</em></blockquote><p>And await does not mean:</p><blockquote><em>“Block the thread.”</em></blockquote><p>Instead, think of await as introducing a <strong>point at which the current asynchronous method needs the result before it can continue</strong>.</p><p>Therefore:</p><pre>await A();<br>await B();</pre><p>means:</p><pre>A must complete before this method continues to B.</pre><p>Whereas:</p><pre>var a = A();<br>var b = B();</pre><pre>await Task.WhenAll(a, b);</pre><p>means:</p><pre>A and B can be started independently,<br>and we wait until both have completed.</pre><p>Once you understand that distinction, async/await becomes much easier to reason about.</p><p>If you got to this point, you’re simply amazing. Understanding <strong>asynchronous programming</strong> can be confusing at first, especially when you realize that writing async and await doesn’t automatically mean your operations are running concurrently.</p><p>But once you understand how await works, when an operation actually starts, and how Task.WhenAll() can be used to handle independent operations, asynchronous programming becomes a lot less stressful.</p><p>You can check the documentation for <a href="https://learn.microsoft.com/en-us/dotnet/csharp/asynchronous-programming/">async and </a><a href="https://learn.microsoft.com/en-us/dotnet/csharp/asynchronous-programming/">await</a> and <a href="https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.task.whenall">Task.WhenAll</a> to understand these concepts better.</p><p>Don’t forget to hit the <strong>clap</strong> 👏🏿 and <strong>follow</strong> button to be notified when I write about many more interesting topics.</p><p>You can connect with me on:</p><p><strong>LinkedIn:</strong> <a href="https://www.linkedin.com/in/adebanjo-emmanuel/">linkedin.com/in/adebanjo-emmanuel/</a></p><p><strong>Twitter / X:</strong> <a href="https://twitter.com/Deolamma">twitter.com/Deolamma</a></p><p>Stay Positive and Productive. 👌🏿</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=244226cea9b9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Observability: The Holy Trinity]]></title>
            <link>https://medium.com/@adebanjoemmanuel01/observability-the-holy-trinity-88c1abefa0bb?source=rss-fc2aede653be------2</link>
            <guid isPermaLink="false">https://medium.com/p/88c1abefa0bb</guid>
            <category><![CDATA[metrics]]></category>
            <category><![CDATA[traceability]]></category>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[opentelemetry]]></category>
            <category><![CDATA[logs]]></category>
            <dc:creator><![CDATA[Emmanuel Adebanjo]]></dc:creator>
            <pubDate>Fri, 16 Jan 2026 10:43:06 GMT</pubDate>
            <atom:updated>2026-01-16T10:43:06.603Z</atom:updated>
            <content:encoded><![CDATA[<p>Despite the title, this is not a religious piece. It is an exploration of the three pillars that define modern observability: metrics, logs, and traces, and why they matter for building reliable and debuggable systems.</p><p>When building credible and reliable systems, it is important to be able to observe how the system behaves using the data it generates. This ability allows engineers to detect issues early, understand failures, and make informed decisions about system improvements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IK6fwBe9m47IBAdwmSCx1w.png" /><figcaption>Image Credit: ChatGpt</figcaption></figure><h3>Metrics, Traces, and Logs</h3><h4>Metrics</h4><ul><li><strong>What it is: </strong>Metrics are numerical data points that represent a system’s performance, such as CPU usage, latency, request count, and error rates.</li><li><strong>What it answers: </strong>Metrics answer questions like “How many?”, “How fast?”, and “How much?”, for example 100 requests per second or a 99th percentile latency of 200ms.</li><li><strong>What it is best for: </strong>Data generated from metrics are best for graphically representing behaviour of a system using dashboards, it is also very good for alerting based on trends picked up by the system and tracking overall system health over time.</li></ul><h4>Traces</h4><ul><li><strong>What it is: </strong>A trace is like a map showing the journey of a single request as it passes through different services in a distributed system, composed of “spans” (operations).</li><li><strong>What it answers: </strong>Traces answer questions such as “Where did the request go?” and “Which service caused the delay?”. This is achieved using identifiers like traceId and correlationId.</li><li><strong>What is is best for: </strong>Pinpointing bottlenecks, understanding dependencies in microservices, diagnosing slow transactions.</li></ul><h4>Logs</h4><ul><li><strong>What it is:</strong> Logs are detailed timestamped records of events happening within an application in chronological order e.g. an error message, a user logged in, etc.</li><li><strong>What it answers:</strong> Logs answer questions like “What happened?” e.g “user ‘JohnDoe’ failed to authenticate”</li><li><strong>What it is best for: </strong>Deep-dive debugging, root cause analysis, audit trails etc. As a matter of fact I personally believe you cannot over-log😂, some senior engineers in the field would disagree.</li></ul><h4>How do these three fundamental pillars work together?</h4><ul><li>You might see a <strong>metric</strong> (high latency) spike.</li><li>You use a <strong>trace</strong> to find which specific service in the chain is taking too long.</li><li>You then examine the <strong>logs</strong> from that slow service to find the specific error or detailed event causing the delay.</li></ul><h3>Observability vs OpenTelemetry</h3><p>I laughed a bit after writing this subtopic, because these two concepts are often compared when they are not competitors at all. Observability is the goal, and OpenTelemetry is one of the tools that helps make it possible. Let us take a closer look at what each one is and how they complement each other.</p><h3>What is Observability?</h3><p>Observability is a property of a system and a practice adopted by engineering teams. It describes how well a system can be understood and how quickly it is to grasp what is happening inside a system by examining the data it produces.</p><p>A system is considered observable when engineers can quickly answer questions such as:</p><ul><li>What is happening right now?</li><li>Why is this request failing or slow?</li><li>Where exactly is the problem coming from?</li></ul><p>Observability is not a single tool or product. It is a combination of good instrumentation, meaningful telemetry, effective dashboards, alerting strategies, and the ability of teams to reason about complex systems.</p><h3>What is OpenTelemetry?</h3><p>OpenTelemetry is an open source observability framework and standard for collecting telemetry data. It provides APIs, SDKs, and instrumentation libraries that make it easier to generate metrics, logs, and traces from applications and infrastructure.</p><p>OpenTelemetry also includes a collector that can receive, process, and export telemetry data to different backends such as Prometheus, Grafana, Datadog, New Relic, or Elastic.</p><p>Importantly, OpenTelemetry is vendor neutral. This allows teams to instrument their systems once and send telemetry data to multiple observability platforms without changing application code.</p><blockquote>The word <strong>OpenTelemetry</strong> is made up of two parts: <strong>Open</strong> and <strong>Telemetry</strong>.</blockquote><blockquote><strong>Telemetry</strong> refers to the automated collection and transmission of data from a system to another location for monitoring and analysis.</blockquote><h3>How they complement each other</h3><p>OpenTelemetry helps generate high quality telemetry data in a consistent and structured way. Observability uses that data to provide insight into system behavior.</p><blockquote>You can think of it this way: OpenTelemetry provides the data and Observability provides the understanding.</blockquote><p>Using OpenTelemetry without good observability practices can still leave teams confused. Practicing observability without proper instrumentation makes it difficult to answer important questions. Together, they form a powerful foundation for operating modern distributed systems.</p><p>If you got this far, you are amazing. Observability plays a critical role in building reliable and trustworthy systems, and it is something no modern system should ignore.</p><p>I could take this further by showing how to set up OpenTelemetry and export logs, traces, and metrics to an OpenTelemetry Collector. If that sounds interesting, leave a comment, clap, and subscribe so you do not miss it.</p><p>Follow for more content on backend engineering and system reliability.</p><p>Connect with me on:<br> LinkedIn: <a href="http://linkedin.com/in/adebanjo-emmanuel">linkedin.com/in/adebanjo-emmanuel</a><br> Twitter (X): <a href="http://twitter.com/Deolamma">twitter.com/Deolamma</a></p><p>Stay positive and productive 👌</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88c1abefa0bb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Running A Worker Service As A Windows Service]]></title>
            <link>https://medium.com/@adebanjoemmanuel01/running-a-worker-service-as-a-windows-service-c1d12a28a73c?source=rss-fc2aede653be------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1d12a28a73c</guid>
            <category><![CDATA[net-core]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[console-application]]></category>
            <category><![CDATA[windows-services]]></category>
            <dc:creator><![CDATA[Emmanuel Adebanjo]]></dc:creator>
            <pubDate>Sat, 01 Feb 2025 07:06:20 GMT</pubDate>
            <atom:updated>2025-02-01T07:06:20.200Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/351/1*J8h2AEjOYKwkTMoYrvqZ7w.png" /><figcaption><a href="https://www.google.com/url?sa=i&amp;url=https%3A%2F%2Fwww.vmignite.com%2F2016%2F02%2Flog-insight-how-to-monitor-any-windows-service%2F&amp;psig=AOvVaw15IhhrWOYlmhOwSyH0v2bh&amp;ust=1738479417201000&amp;source=images&amp;cd=vfe&amp;opi=89978449&amp;ved=0CBQQjRxqFwoTCIDgttTyoYsDFQAAAAAdAAAAABAE">Image Credit</a></figcaption></figure><p>A few weeks ago, I was tasked with creating a notification service to push notifications based on configurations retrieved from an <a href="https://learn.microsoft.com/en-us/azure/service-bus-messaging/service-bus-queues-topics-subscriptions">Azure Service Bus Topic</a>. Developing and testing the service in Visual Studio went smoothly — everything worked perfectly as expected.</p><p>However, the real challenge began after deploying the service to a Windows Server as a Windows Service. It stubbornly refused to start, repeatedly throwing <strong>Error 1053</strong>, as shown below:</p><blockquote>The service did not respond to the start or control request in a timely fashion.</blockquote><p>Trust me — my head was on fire! 😩 I had seen the service run flawlessly in Visual Studio, and I was quickly running out of time to deliver the task.</p><p>After extensive research, I discovered that <strong>Error 1053</strong> can have <a href="https://www.google.com/search?q=Worker+service+not+starting+as+a+windows+service&amp;oq=Worker+service+not+starting+as+a+windows+service&amp;gs_lcrp=EgZjaHJvbWUyCwgAEEUYChg5GKABMgkIARAhGAoYoAEyCQgCECEYChigAdIBCTE1MTQ0ajBqN6gCCLACAQ&amp;sourceid=chrome&amp;ie=UTF-8">multiple causes</a>. The first step to diagnosing the issue is to check the <strong>Event Viewer</strong> under <strong>Windows Logs -&gt; Application</strong> or <strong>System</strong> for detailed error messages.</p><p>In my case, the error log was:</p><blockquote><em>The &lt;Service Name&gt; service failed to start due to the following error:</em><br><em>The service did not respond to the start or control request in a timely fashion.</em></blockquote><p>Let’s delve right into how I resolved this…</p><h3>What is A Worker Service?</h3><p>A <a href="https://www.google.com/search?q=Waht+is+a+Worker+Service&amp;oq=Waht+is+a+Worker+Service&amp;gs_lcrp=EgZjaHJvbWUyBggAEEUYOTIJCAEQABgNGIAEMgkIAhAAGA0YgAQyCAgDEAAYFhgeMggIBBAAGBYYHjIICAUQABgWGB4yCAgGEAAYFhgeMggIBxAAGBYYHjIICAgQABgWGB4yCAgJEAAYFhge0gEJMTMxMTdqMGo3qAIIsAIB&amp;sourceid=chrome&amp;ie=UTF-8"><strong>Worker Service</strong></a> is a long-running background service designed for tasks that do not require direct user interaction. It is ideal for scenarios where actions need to be performed continuously, at intervals, or in response to events, such as listening to message queues, processing data, or scheduling tasks. I like to think of it as a tool for automation — a “fire and forget” solution. It’s important to note that a Worker Service will not terminate unless explicitly instructed to do so.</p><h3>The Problem</h3><p>After building an excellent implementation of my task and testing it in Visual Studio, everything worked perfectly. My service ran as expected and didn’t terminate unless I explicitly stopped it via the console.</p><p>Hmm, the console… There’s a part I haven’t mentioned yet. Up until this project, I didn’t know anything about Worker Services, so I initially created the application as a Console application. To keep it running indefinitely, I used a simple trick: Console.ReadKey(). This kept the application alive until I pressed a key in the console.</p><p>However, when I deployed it as a Windows Service, I hit my first major issue: services can’t interact with the Console. As a result, the service failed to run. After much research and guidance from senior engineers, I realized I had two options:</p><ol><li>Instrument my current Console app as a Worker Service by adding a Worker.cs class.</li><li>Create a new Worker Service project and migrate my existing solution.</li></ol><p>Interestingly, I tried both approaches. For the sake of this write-up, I’ll walk you through how to create a Worker Service project and deploy it as a Windows Service.</p><blockquote>A Windows Service cannot interact with the console…</blockquote><h3>Creating A Worker Service</h3><h4>Step 1: Open Visual Studio</h4><ul><li>Launch <strong>Visual Studio</strong> (preferably 2019 or newer).</li></ul><h4>Step 2: Create a New Project</h4><ol><li>Select <strong>Create a new project</strong> from the startup window.</li><li>In the search bar, type <strong>Worker Service</strong>.</li><li>Select <strong>Worker Service (.NET)</strong> from the results and click <strong>Next</strong>.</li></ol><h4>Step 3: Configure the Project</h4><ol><li>Enter a <strong>Project Name</strong> (e.g., WorkerServiceTutorial).</li><li>Choose a <strong>Location</strong> to save your project.</li><li>Optionally, provide a <strong>Solution Name</strong>.</li><li>Click <strong>Next</strong>.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*el189e7RHnWqv7JqNkUqlw.png" /><figcaption>Base Project</figcaption></figure><p>Notice the worker.cs in the solution explorer, that’s your guy…That’s the core component where the background task logic resides. It inherits from the BackgroundService class, which provides the necessary structure for creating long-running background tasks in .NET applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6am-F9m1yTjl9SyEBmscZA.png" /><figcaption>Worker.cs</figcaption></figure><p>The ExecuteAsync method is where the core logic of the Worker Service resides, making it the entry point for your implementation. In the example shown, the conditional !stoppingToken.IsCancellationRequested ensures that the background service continues to run until a cancellation request is received (such as when the service is stopped).</p><p>What happens in this ExecuteAsync method is that, as long as no cancellation request is made, the service executes its tasks and waits for 1 second between executions (Task.Delay(1000)). This keeps the application alive without restarting the entire service every second; instead, it loops continuously within the same service instance.</p><blockquote>You can always adjust the timer to suit your needs… And also in a production application you might want to pay attention to lifecycle i.e AddSingleton(), AddHosted(), AddTransient(), AddScoped()</blockquote><p>You can optionally override the StopAsync method for clean up of resources.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9J-O3yQWVyvgpJLfmj7mEg.png" /><figcaption>Adding optional StopAsync</figcaption></figure><p>A quick look at the Program.cs file shows that minimal configuration is required to set up a Worker Service. We simply need to:</p><ol><li>Create the application builder.</li><li>Register the worker class as a hosted service using AddHostedService&lt;Worker&gt;().</li><li>Build the application and its dependencies.</li><li>Call Run() to start the service.</li></ol><p>The call to .Run() triggers the execution of the ExecuteAsync method in the worker class, which ideally should contain the core logic for the background service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eRSUwHqTNcVDoXYFD4Ji3w.png" /><figcaption>Program.cs</figcaption></figure><p>If you run this application, you should see the logs from ExecuteAsync written to the console every second (or based on the time interval you set). Additionally, if you&#39;ve overridden the StopAsync method, you&#39;ll notice your cleanup process or logs being triggered when you explicitly stop the application by pressing <strong>Ctrl + C</strong> or closing the console window.</p><p>Since a Windows Service doesn’t interact with the console, you’ll need to configure your application to log to a file instead. This ensures that you can still capture and review your logs even when the service is running without a visible interface.</p><p>For my application, I also implemented observability using <strong>OpenTelemetry</strong>. Stay tuned for my upcoming article on integrating OpenTelemetry!</p><h3>Deploying Your Application As A Service</h3><p><strong>Create a Precompiled Folder:</strong><br>First, add a <em>Precompiled</em> folder in your solution directory. This folder will store the publish profile and contain the generated DLLs and executables.</p><p><strong>Publish Your Project:</strong></p><ol><li>Right-click on your project in Visual Studio and select <strong>Publish</strong>.</li><li>Select <strong>Folder</strong> as the target and browse to select your <em>Precompiled</em> folder.</li><li>Click <strong>Publish</strong>.</li></ol><p><strong>Verify the Output:</strong><br>If the publishing is successful, you should see a confirmation screen and a bunch of DLLs and executable files generated in the <em>Precompiled</em> folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iQnzuLFlhMdYnQjU8x8ytQ.png" /></figure><p><strong>Create the Windows Service:</strong><br>Open <strong>Command Prompt </strong>or <strong>Powershell </strong>with administrator privileges and run the following command to create your Windows Service:</p><pre>sc.exe create &quot;YourServiceName&quot; binPath= &quot;C:\Path\To\YourExecutable.exe&quot; DisplayName= &quot;Worker Service Tutorial&quot; start= auto</pre><p><strong>Important Notes:</strong></p><ul><li>Replace &quot;YourServiceName&quot; with the desired name for your service.</li><li>For the binPath, locate the .exe file in your <em>Precompiled</em> folder and copy the full path. Ensure that the path is correctly enclosed in double quotes.</li><li>The DisplayName is the name that will be shown on services.msc which is where we manage our services</li><li>Add start= auto if you want the Windows Service to start automatically on system boot.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*N3HGSAYKWuC9V5woYLCSig.png" /></figure><h4>Start The Windows Service</h4><p>To start the service we would need to do the following</p><ol><li>click windows + r then type services.msc. You should see the screen below, scroll through the list for your newly created service display name, the services are ordered alphabetically.</li><li>Right click on the service and start</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i5Py8poKEBQJrHk9FIGnlg.png" /></figure><p>ooopsss, why wouldn’t the service start. It was running perfectly, when we ran in visual studio… what is wrong? these were the thoughts flowing through my mind. To troubleshoot this, you’ll need to open Event Viewer and under Windows logs check System or Application logs for the error causing the service to crash. In our case:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*9FLIG5dBTgqpnNuK3Z-t7Q.png" /></figure><h3>Resolving the Issue</h3><p>To resolve the issue where the Windows Service refuses to start, we need to ensure that the Service Manager recognizes our Worker Service as a legitimate Windows service.</p><h4>The Solution:</h4><p>There’s a package we need to add to our Worker Service project:<br><strong>Microsoft.Extensions.Hosting.WindowsServices. </strong>This can be downloaded from Nuget Manager.</p><h3>My Dilemma</h3><p>In my case, I was deploying the service to a <strong>Windows Server</strong>, not my local device. My concern was:</p><p>💭 <em>What happens if we move to a Linux server? Would my service become obsolete or simply refuse to start?</em></p><p>If you’re curious about how I resolved this challenge, feel free to ask in the chat section, and I’ll gladly share my solution! 😉</p><p>To resolve our problem, we would need to add this line of code to our program.cs, imagine struggling for days only to realize that all I needed to add was a line of code and my problems would be gone.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-1rlQ1fv970ty7si_gTW8w.png" /></figure><p>Focus on line 5, that is the important piece of code that puts you out of your miseries😂😂😂.</p><p>Next step is to republish your application, so that your .exe file can be updated with the changes and start the service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*dtd-LDwV7d-YoLMV7Y6JYg.png" /><figcaption>Worker Service Tutorial running</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*febON-wXfLjmVFNBaVOppw.png" /><figcaption>Logging to file</figcaption></figure><p>If you got to this point you’re simply amazing. Creating a <strong>Windows Service</strong> from a <strong>Worker Service</strong> or <strong>Console App</strong> can be herculean and sometimes confusing but if you follow my guide in this tutorial it’ll be a lot less stressful. You can check the documentation for <a href="https://www.google.com/search?q=what+is+a+windows+service&amp;oq=What+is+a+Windows+Service&amp;gs_lcrp=EgZjaHJvbWUqBwgAEAAYgAQyBwgAEAAYgAQyBwgBEAAYgAQyBwgCEAAYgAQyCAgDEAAYFhgeMggIBBAAGBYYHjIICAUQABgWGB4yCAgGEAAYFhgeMggIBxAAGBYYHjIICAgQABgWGB4yCAgJEAAYFhge0gEINzc5MGowajeoAgCwAgA&amp;sourceid=chrome&amp;ie=UTF-8">Windows Services</a> and <a href="https://www.google.com/search?q=Waht+is+a+Worker+Service&amp;oq=Waht+is+a+Worker+Service&amp;gs_lcrp=EgZjaHJvbWUyBggAEEUYOTIJCAEQABgNGIAEMgkIAhAAGA0YgAQyCAgDEAAYFhgeMggIBBAAGBYYHjIICAUQABgWGB4yCAgGEAAYFhgeMggIBxAAGBYYHjIICAgQABgWGB4yCAgJEAAYFhge0gEJMTMxMTdqMGo3qAIIsAIB&amp;sourceid=chrome&amp;ie=UTF-8">Worker Services</a> to understand it better.</p><p>Don’t forget to hit the clap and follow button to be notified when I write about many more interesting topics.</p><p>You can connect with me on:<br>LinkedIn: <a href="https://www.linkedin.com/in/adebanjo-emmanuel/">linkedin.com/in/adebanjo-emmanuel/</a><br>Twitter or X: <a href="https://twitter.com/Deolamma">https://twitter.com/Deolamma</a></p><p>Stay Positive and Productive👌.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1d12a28a73c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Promises and Asynchronous Programming in JavaScript]]></title>
            <link>https://medium.com/@adebanjoemmanuel01/promises-and-asynchronous-programming-in-javascript-c21eb5f95d86?source=rss-fc2aede653be------2</link>
            <guid isPermaLink="false">https://medium.com/p/c21eb5f95d86</guid>
            <category><![CDATA[javascript-event-loop]]></category>
            <category><![CDATA[promises-in-javascript]]></category>
            <category><![CDATA[promises]]></category>
            <category><![CDATA[asynchronous-javascript]]></category>
            <category><![CDATA[callbacks-vs-promises]]></category>
            <dc:creator><![CDATA[Emmanuel Adebanjo]]></dc:creator>
            <pubDate>Fri, 26 Jul 2024 08:08:50 GMT</pubDate>
            <atom:updated>2024-07-26T08:08:50.069Z</atom:updated>
            <content:encoded><![CDATA[<p>Before we delve into promises and asynchronous programming in JavaScript let’s take a detour and understand the fundamental concept of callbacks in JavaScript.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HGLg5iakV401GDidgzP4YQ.jpeg" /><figcaption>Img Credit: <a href="https://inspireski.com/request-a-callback/">https://inspireski.com/request-a-callback/</a></figcaption></figure><h4><strong>What is a Callback?</strong></h4><p>Simply put, A callback is a function passed into another function. This allows functions to call other functions after completing their execution.</p><blockquote>A callback is a function passed into another function</blockquote><pre>// How programs are run normally<br>function greet(name) {<br>  console.log(&quot;Hello, &quot; + name + &quot;!&quot;);<br>}<br><br>function sayGoodbye() {<br>   console.log(&quot;Goodbye!&quot;);<br>}<br><br>greet(&quot;Alice&quot;);<br>sayGoodbye();  </pre><p>Javascript is a single threaded programming language and runs programs synchronously i.e. a function would hold control and computer resources until it is done and explicitly yields control. In the example above, the greet function runs to completion before the sayGoodbye function begins to run.</p><p>So where do callbacks come in:</p><pre>function greet(name, callback) {<br>    console.log(&quot;Hello, &quot; + name + &quot;!&quot;);<br>    callback();<br>}<br><br>function sayGoodbye() {<br>    console.log(&quot;Goodbye!&quot;);<br>}<br><br>// Pass sayGoodbye as a callback to greet<br>greet(&quot;Alice&quot;, sayGoodbye);<br><br>//CREDIT: CHATGPT</pre><p>In the code snippet above we use a callback, and the benefit to this is that we do not have to call 2 functions to greet and say good bye to our user😊… Not soo interesting right? Let’s delve into more interesting use cases of callbacks.</p><pre>setTimeout(myFunction, 3000);<br><br>function myFunction() {<br>  console.log(&quot;Printing after 3secs&quot;);<br>}</pre><p>In the code snippet above, setTimeout is a JavaScript in-built asynchronous function, which takes a callback function in our case myFunction and executes the function after 3000 milliseconds. Callbacks are a powerful fundamental concept in JavaScript and is useful for Promises and Asynchronous codes. Let’s dive deeper 💪🏿</p><h4><strong>What is a Promise?</strong></h4><p>In simple and real word lingua, a promise is a promise😂, scratch that, a promise is a surety that a person gives to another guaranteeing that something would be done in the future. Now, this promise can either be fulfilled or fail, the person who made this promise died or simply doesn’t have the capacity to fulfill that promise anymore, this is exactly what happens in computing. Similarly in computing, a Promise is a mechanism to handle asynchronous operations — tasks that are performed in the background while the main code continues to run. A Promise is a placeholder for a value that is not yet known but will be resolved or rejected in the future.</p><blockquote>Promise is a mechanism to handle asynchronous operations — tasks that are performed in the background while the main code continues to run. A Promise is a placeholder for a value that is not yet known but will be resolved or rejected in the future.</blockquote><h3>Promise States</h3><p>A Promise can be in one of three states:</p><ol><li><strong>Pending</strong>: The initial state, neither fulfilled nor rejected.</li><li><strong>Fulfilled</strong>: The operation completed successfully, and the Promise has a resulting value.</li><li><strong>Rejected</strong>: The operation failed, and the Promise has a reason for the failure.</li></ol><p>Once a Promise is fulfilled or rejected, it becomes <strong>settled</strong>, and its state cannot change.</p><pre>// Creating a promise<br>const myPromise = new Promise((resolve, reject) =&gt; {<br>  // Asynchronous operation<br>  const success = true; // Simulating success or failure<br><br>  if (success) {<br>    resolve(&#39;Operation successful!&#39;);<br>  } else {<br>    reject(&#39;Operation failed.&#39;);<br>  }<br>});<br><br>//Handling a promise<br>myPromise<br>  .then((result) =&gt; {<br>    console.log(&#39;Success:&#39;, result);<br>  })<br>  .catch((error) =&gt; {<br>    console.log(&#39;Error:&#39;, error);<br>  });</pre><p>Once a Promise is created, you can handle its result using .then() and .catch() :</p><ul><li><strong>.then()</strong>: This method takes two arguments: a callback for a successful resolution and an optional callback for a rejection. If the Promise is fulfilled, the first callback executes with the resulting value.</li><li><strong>.catch()</strong>: This method handles errors and rejections. It&#39;s a cleaner way to handle errors without passing a second callback to .then().</li></ul><p>If we have Promises, what then is the need for Async/Await?</p><p>A simple answer to this is that the greatest pro of promises which is “Chaining” is also it’s biggest con because it becomes increasingly difficult to debug when you have multiple promises nested.</p><pre>const fs = require(&#39;fs&#39;);<br><br>const writeDataToFile = (data) =&gt; {<br>  return new Promise((resolve, reject) =&gt; {<br>    fs.writeFile(&#39;output.json&#39;, JSON.stringify(data), (err) =&gt; {<br>      if (err) {<br>        reject(err);<br>      } else {<br>        resolve(&#39;Data written to file successfully&#39;);<br>      }<br>    });<br>  });<br>};<br><br>// Chaining<br>const fetchData = () =&gt; {<br>//Using pokeapi for data<br>  return fetch(&#39;https://pokeap.co/api/v2/pokemon&#39;)<br>    .then(response =&gt; response.json())<br>    .then(data =&gt; {<br>      return writeDataToFile(data.results);<br>    });<br>};<br><br>/.chaining<br>fetchData()<br>  .then(result =&gt; console.log(result))<br>  .catch(error =&gt; console.error(error));</pre><p>It becomes increasingly difficult to track where errors are happening within the code snippet above. Infact, I introduced an error intentionally into the code and was debugging the error somewhere else, Can you figure out what the error is and what I could have done to aid easy debugging?? If you don’t spot the error, don’t be too hard on yourself, I made it ridiculously hard to spot it, I’ll provide the solution at the end👌.</p><p>Async/Await provides us a simpler way to write asynchronous code without having to bother about chaining and the callback hell. Asides from giving us more beautiful looking lines of code, it helps in handling errors by simply wrapping our codes in try…catch blocks.</p><pre>const fs = require(&quot;fs&quot;);<br><br>const writeDataToFile = async (data) =&gt; {<br>  try {<br>    await fs.promises.writeFile(&quot;output.json&quot;, JSON.stringify(data));<br>    return &quot;Data written to file successfully&quot;;<br>  } catch (err) {<br>    throw err;<br>  }<br>};<br><br>const fetchData = async () =&gt; {<br>  try {<br>    const response = await fetch(&quot;https://pokeapi.co/api/v2/pokemon&quot;);<br>    const data = await response.json();<br>    const result = await writeDataToFile(data.results);<br>    console.log(result);<br>  } catch (error) {<br>    console.error(error);<br>  }<br>};<br><br>fetchData();</pre><p><strong>Key differences between Promise chaining and Async/Await:</strong></p><ul><li><strong>Syntax:</strong> Promise chaining uses .then() and .catch(), while Async/Await uses await and try...catch.</li><li><strong>Readability:</strong> Async/Await is often considered more readable for sequential asynchronous operations.</li><li><strong>Error handling:</strong> Both methods can handle errors, but Async/Await’s try...catch is more concise.</li></ul><p>The solution to the error I introduced into the code above is to replace the url with this “https://pokeapi.co/api/v2/pokemon”. and what could have aided your debugging was to add a .catch to the end of the return on the api call. Replace this block of code with the one below:</p><pre>const fetchData = () =&gt; {<br>//Using pokeapi for data<br>  return fetch(&#39;https://pokeap.co/api/v2/pokemon&#39;)<br>    .then(response =&gt; response.json())<br>    .then(data =&gt; {<br>      return writeDataToFile(data.results);<br>    }).catch(err =&gt; (&quot;Fetching of data failed: &quot;, err));<br>};</pre><p>If you got to this point, then you are simply amazing and I believe you must have learnt something. Honestly, there’s a lot more to know and we’ve only just scratched the surface. Check out the videos in the links to augment the knowledge gained here: <a href="https://youtu.be/8aGhZQkoFbQ?si=7OSF5Dqskc2SIIRW">JS Event Loop</a> <a href="https://youtu.be/SrNQS8J67zc?si=G4G_kwRT8QXwhW7G">Asynchrony</a></p><p>Don’t forget to hit the clap and follow button to be notified when I write on interesting topics.</p><p>You can connect with me on: <a href="http://linkedin.com/in/adebanjo-emmanuel/">LinkedIn</a> <a href="https://twitter.com/Deolamma">Twitter or X:</a></p><p>Stay Positive and Productive👌.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c21eb5f95d86" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple and Fast Multimedia Library in Visual Studio]]></title>
            <link>https://medium.com/@adebanjoemmanuel01/simple-and-fast-multimedia-library-in-visual-studio-490bab9245de?source=rss-fc2aede653be------2</link>
            <guid isPermaLink="false">https://medium.com/p/490bab9245de</guid>
            <category><![CDATA[sfml]]></category>
            <category><![CDATA[c-programming]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[c-plus-plus-language]]></category>
            <category><![CDATA[programming-tips]]></category>
            <dc:creator><![CDATA[Emmanuel Adebanjo]]></dc:creator>
            <pubDate>Sun, 02 Jun 2024 15:00:35 GMT</pubDate>
            <atom:updated>2024-06-02T15:00:35.844Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*uG6rCufus9klXGxelJBaMg.jpeg" /><figcaption><a href="https://www.google.com/url?sa=i&amp;url=https%3A%2F%2Fdocumentation.help%2FSFML-1.6%2FImageLoader_8hpp-source.htm&amp;psig=AOvVaw0uBPEZ5umFNZtG5QRpVcNh&amp;ust=1717424266858000&amp;source=images&amp;cd=vfe&amp;opi=89978449&amp;ved=0CBQQjhxqFwoTCJCTz4yOvYYDFQAAAAAdAAAAABAE">Image Credit</a></figcaption></figure><p><strong>What is SFML?<br></strong>Simple and Fast Multimedia Library, SFML is a cross-platform software development library that provides a simple application interface for various multimedia components including graphics, audio, and network functionalities. It is written in C++ but also provides integration for other programming languages like C, .Net, Python, etc.</p><p>It is commonly used for game development but in my case, I’m trying to build Data Structure Visualizer using C++, and on research SFML was the go to amongst many others. I spent a whole day trying to integrate SFML into my Visual Studio C++ project, because I was making a simple mistake and the <a href="https://www.sfml-dev.org/tutorials/2.6/">official docs</a> wasn’t really helping(well, in all fairness it was from the doc I got a hint to fix the mistake I was making 😜).</p><h3><strong>Using SFML in Visual Studio</strong></h3><p>To use the SFML library in visual studio there are a few steps you need to take:</p><p><strong>Download the SFML library Package:<br></strong>Go to the SFML official page, download a package that meets your device specification and visual studio/compiler version. Once downloaded extract the zipped contents to a location of choice.</p><blockquote>While downloading, pay attention to the bit of your machine and warning on the site about downloading a package that matches your compiler version except you are using a newer version of Visual Studio, which I am.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*vCVJptuz4acEikgV2VBDDg.png" /><figcaption>Content of the SFML Package</figcaption></figure><p>If all goes well, you should have the folders and files in the image above in the SFML package just downloaded. This is where it gets interesting</p><p><strong>Create a C++ Project in Visual Studio:</strong> <br>Once your C++ project has been created, I know we are eager to jump right in and begin to code away, but there are a few more set up we must do. Well, not soo few😜.</p><ul><li><strong>Run the project in debug and release mode:</strong><br>Why this is important is because when our project is run in any of these modes a debug and release folder is generated for us depending on the mode the code was run in, this folders would contain our executable file(.exe), log files, Dynamic Link Libraries(.dll), Static Libraries(.lib) e.t.c. This is where we add the necessary dll’s and libs for the media we would be utilizing in the SFML library.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lBugUAxn7j1MHiGtHkYcRw.png" /></figure><p>After we’ve done this, we would notice that we now have two (2) new folders in our x64 folder in our project folder. To get to your project folder from Visual Studio:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wJYES6Brb7yGCuAGukTcmg.png" /></figure><p><strong>Add Libraries from Your SFML Package to your C++ Project:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VmXq59CA6VN5iHCb23BxBA.png" /></figure><p>Trust me I am laughing hard at my attempt to scribble the words “My C++ Project” and “SFML Package” on right and left FileExplorer in the image above. Going forward I would show snapshots of the changes in this folder for clarity as we add “things” from our SFML package folder to our C++ folder.</p><ul><li>First, we need to add the lib and include folder from our SFML package to our C++ project. Why? The include folder contains the header files (.h or .hpp files) of the library. These header files declare the functions, classes, and variables provided by the library. Also, the lib folder contains the compiled library files (.lib files on Windows) that are necessary for linking your application with the SFML library. During the linking phase of compilation, the linker needs to know where to find these .lib files so it can resolve references to SFML functions and classes that are used in your code. Phew, enough said, let’s add the necessary folders.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pc_1dvU3MHWE6LhnRprcFA.png" /></figure><p>Notice the newest additions, and that we added them in the same folder that contains our projects .sln file. There’s a reason why as we’ll see soon.</p><ul><li>Next, we need to add the necessary DLL’s to our project folder from the bin folder in our SFML package in the appropriate mode ( PathToTheFolder: x64 &gt;&gt; Debug or Release) we are working in. This is the reason why we needed to first run our project in release and debug mode. To locate the DLL’s, go to the bin folder in your SFML package and copy the appropriate .dll files you need to work with; -d for debug.</li></ul><blockquote>You don’t always need to work with all the libraries, for instance your project only needs the window and audio features then simply copy the dll’s for those features and add to your project in the appropriate mode (Debug or Release) you’re working in. However, note that you must copy the system sfml-system-2.dll (system library) and the openal32.dll for advanced audio capabilities.<br>Note: the dll’s with -dare for debug and the one’s without are for release mode.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7OEcH2wiNmIF0gmJ3RJ3AQ.png" /><figcaption>DEBUG MODE</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KR31ne3VHhvjOM-co8SIUA.png" /><figcaption>RELEASE MODE</figcaption></figure><p>Pay close attention to to the images above, they look similar but are infact different. Notice the kinds of files that were copied from the SFML package to the Project Folder for the appropriate modes?</p><p>Phew, that was a lot of work👏🏿, with this out of the way all that’s left is to tell Visual Studio how to locate these files we’ve just added and that we want to make use of the SFML library.</p><p><strong>Show Visual Studio How to Locate the DLL’s Added</strong></p><p>There are a few steps we need to take to inform Visual Studio that we want to use SFML library.</p><ul><li>Right Click on the name of your project&gt;&gt; scroll down and click on properties you should see the window in the image below:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HaEPHG-qWqOWasYqVgS4yQ.png" /></figure><p>Make sure that you have the same configuration settings as I have highlighted in the image above. If you don’t have it set to these by default it’s okay, simple click on the arrows and set it to the same configurations as I have.</p><ul><li>Next, clickC/C++ &gt;&gt; on the rigth side of the pane, click Additional Include Directories &gt;&gt; click on the small arrow and click on edit &gt;&gt; click on Macros. You should see the window in the image below:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xw_zzImmRKCRbY17nTkDRQ.png" /></figure><p>In the space highlighted with red type solutiondir, what this does is it always locates the path to where the project is located. Then you click on insert &gt;&gt; you’ll notice that the box highlighted with blue would have $(SolutionDir) inserted in &gt;&gt; double click on $(SolutionDir) and append /include now we have $(SolutionDir)/include click on ok. What we have done is to tell visual studio how to locate the include folder which contains the header files of our SFML library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*E4m_9dLUHr3Y7OsgSNRJCw.png" /></figure><p>If all is done well, we should have the highlighted in the previously empty space.</p><ul><li>Next, we click on the arrow beside Linker in the left pane &gt;&gt; click on General &gt;&gt; on the right pane, click on Additional Library Directories &gt;&gt; Click on Macros &gt;&gt; insert $(SolutionDir)/lib this add the necessary dll’s the linker needs.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*cOiJVdg6E_lj5a_il6QxMQ.png" /></figure><ul><li>Next, Where we had set our configuration to All Configurations and All Platforms change this setting to Debug and x64. Click on Linker &gt;&gt; click on Input &gt;&gt; on the right pane click Additional Dependecies &gt;&gt; then click the small arrow and click edit. What we want to do here is to add the specific dll’s of the features we’ll be using in our project, in this tutorial I would do only for the debug mode, you could try out how to set for the release mode. To set for the release mode, the only difference would be to add the lines below to your Additional Dependencies without the -d rememeber -d denotes Debug. Also, don’t forget to change your configurations to release and x64.</li></ul><pre>sfml-system-d.lib;<br>sfml-graphics-d.lib; <br>sfml-window-d.lib;<br>sfml-audio-d.lib;<br>sfml-network-d.lib;</pre><p>Add the lines above in the box highlighted below &gt;&gt; click ok &gt;&gt; click apply</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*MlbbWmxIs1vgLiGjx75LTA.png" /></figure><p>To test that your set up was correct, add these lines of code to the file you want to be the entry point to your application:</p><pre>#include &lt;SFML/Graphics.hpp&gt;<br><br>int main()<br>{<br>    sf::RenderWindow window(sf::VideoMode(200, 200), &quot;SFML works!&quot;);<br>    sf::CircleShape shape(100.f);<br>    shape.setFillColor(sf::Color::Green);<br><br>    while (window.isOpen())<br>    {<br>        sf::Event event;<br>        while (window.pollEvent(event))<br>        {<br>            if (event.type == sf::Event::Closed)<br>                window.close();<br>        }<br><br>        window.clear();<br>        window.draw(shape);<br>        window.display();<br>    }<br><br>    return 0;<br>}</pre><p>You would know you hadn’t made a mistake if you don’t see a red squiggly line under your first line of code. Another moment of truth would be after you run your code in the appropriate mode, in our case Debug mode, and you are greeted with a not so beautiful interface but with a bright green circle. Trust me I prayed earnestly everytime I wanted to run my setup until I finally got it right😂.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X0ALwDnVSLwe0qvAKAr9tw.png" /></figure><p><strong>What was my mistake?</strong></p><p>You most likely might not face this, what I had done wrong was I had added this line SFML_STATIC to my Preprocessor in project properties. What I was telling the compiler to do was to statically bind my project so that my libraries were linked and bound to the executable. This in itself is not bad, what was bad was that I wasn’t adding my libraries statically all I needed to do was add s to my libraries sfml-system-s-d.lib This way the compiler wouldn’t have been mad at me 😂. Not adding this SFML_STATIC to the preprocessor would mean that we want our libraries linked by the linker dynamically. This tutorial is not about Dynamic Linking or Static Linking, there are benefits and disadvantages to using any of them, but that is beyond the scope of this tutorial. Peace ✌🏿</p><p>If you got to this point you’re simply amazing. Integrating SFML library into Visual Studio can be herculean and sometimes confusing but if you follow my guide in this tutorial it’ll be a lot less stressful. You can check the <a href="https://www.sfml-dev.org/tutorials/2.6/">documentation</a> for SFML to get more knowledge of what is possible with the Simple and Fast Multimedia Library.</p><p>Don’t forget to hit the clap and follow button to be notified when I write on interesting topics.</p><p>You can connect with me on:<br>LinkedIn: <a href="https://www.linkedin.com/in/adebanjo-emmanuel/">linkedin.com/in/adebanjo-emmanuel/</a><br>Twitter or X: <a href="https://twitter.com/Deolamma">https://twitter.com/Deolamma</a></p><p>Stay Positive and Productive👌.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=490bab9245de" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[3 Months at Microsoft ]]></title>
            <link>https://medium.com/@adebanjoemmanuel01/3-months-at-microsoft-4aad637011d9?source=rss-fc2aede653be------2</link>
            <guid isPermaLink="false">https://medium.com/p/4aad637011d9</guid>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[alxafrica]]></category>
            <category><![CDATA[microsoftintern]]></category>
            <category><![CDATA[internships]]></category>
            <dc:creator><![CDATA[Emmanuel Adebanjo]]></dc:creator>
            <pubDate>Fri, 22 Dec 2023 10:05:25 GMT</pubDate>
            <atom:updated>2023-12-22T10:05:25.491Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DJ-Esz0YaD17JMv-0kLveA.jpeg" /></figure><p>Time really does fly! It feels like just yesterday when I joined 16 other incredible individuals on this thrilling journey at Microsoft ADC West Africa. These past three months have been a whirlwind of excitement and learning. Let me take you on a quick tour of my first quarter as a Microsoft intern.</p><p>The initial two weeks were mind-blowing! We had the privilege of meeting with Engineering, program, and principal managers from various teams within Microsoft ADC. What struck me was how young some of these leaders who were already driving innovation on a global scale were. We had candid conversations about work ethics, work-life balance, and the unique Microsoft culture. &quot;Mutual Respect&quot; echoed in every discussion, creating an inclusive and collaborative environment, even for us interns. Meeting Gafar Lawal, the Managing Director of Microsoft ADC West Africa, was the icing on the cake. His words, &quot;Do the things others shy away from; that&#39;s how you stand out,&quot; set the tone for the exciting journey ahead. At this time we were itching to get our hands dirty on the technical stuff and coding.</p><p>Then came the technical stuff! From Software Development Life Cycle (SDLC) with James Omitiran to diving into JavaScript, HTML, and CSS with Ugo Okoro and Olakunle Dosunmu, we were on a fast-paced learning curve. The highlight? Building a chat app using Microsoft&#39;s SignalR, C#, JavaScript, HTML, and CSS. Teamwork took center stage, and it was both challenging and rewarding. As the team lead of Team Athena—one of the three dynamic teams, alongside Zeus and Prometheus—we eagerly embraced the learning curve, engaging in collaborative tinkering and reaching mutual agreements on our approach to solving the problems at hand.</p><p>C# became our language of choice as Chidimma Okafor and Anthony Adebayo guided us through Object-Oriented Programming, design patterns, and SOLID principles. The interactive sessions kept us on our toes and deepened our understanding of C#.</p><p>Code refactoring and unit testing, led by Obinna Chikwendu, emphasized the importance of writing optimal code and conducting thorough testing for reliability. Pelumi Adebayo&#39;s debugging session showcased the power of Visual Studio in hunting down bugs using the call stack and watch window as well as handling exceptions using C#&#39;s inbuilt Exception class.</p><p>C++ Was another exciting session handled by my assigned mentor Inioluwa Adeleye(special shout out) and Samuel Odudimu. Together they took us through the intricacies of the C++ programming languages exploring the low-level concepts, climaxing at Data Structures and Algorithms. It was a bit confusing and daunting for many of us at first, but between the combined determination of Inioluwa and Samuel to make us understand this complex concepts in simple terms and our determination to actually grasp these difficult concepts we were able to pull through.</p><p>SQL opened a world of relational database management, led by mentor Peter Omolaiye. Hands-on SQL queries and database exploration were integral, offering practical insights.</p><p>Web API’s, a personal favorite, were demystified by mentors Babatunde Ojo and Augustine Ewurum. ExpressJS, RESTful API endpoints, and MongoDB were covered, empowering us to build meaningful projects. As practice I went a step further to build a backend data service using ExpressJS, and hooking it to non-relational database MongoDB using it’s ODM Mongoose. It was super exciting and I had the most fun. I look forward to building more meaningful projects with the knowledge gained.</p><p>The Microsoft Garage sessions, curated by mentor Idowu Asumah, were a hands-on delight. Arduino projects, including light sensors and a Weather Sensor app, added a creative touch. Laser cutting, 3D design, and printing sessions made our time at the garage truly amazing.</p><p>A shoutout to our program managers like Babatunde Vaugahn, Ilami Omodara, and Oladayomi Oladipupo for crafting an incredible learning experience and providing us with resources that have aided our growth. This piece would be incomplete without mentioning Oluwamuyemi Orimolade, your constant words of wisdom which seems to always come just in time to fan our fire to flame and dare us to want to do and be more. Thanks for always encouraging us to put ourselves out there, showcasing our talents to the world.</p><p>Beyond work, being part of team Script Squad and winning the Kings Tower Football tournament added a fun twist to my internship.</p><p>To team Inicio, my fellow interns, we are the pioneers of greatness, and our Peer Learning Sessions have been a blast, they been my most interesting time of this internship.</p><p>Special thanks to NJFP, and UNDP for this life-changing opportunity. Also to ALX Africa I&#39;ve come to appreciate the learnings and do hard things mantra during my time here at Microsoft. Microsoft, thank you for providing a platform for continuous learning and growth.</p><p>#MicrosoftInternship #LearningAndGrowing&quot;</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4aad637011d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Makefile]]></title>
            <link>https://medium.com/@adebanjoemmanuel01/makefile-fd5ee8ca3076?source=rss-fc2aede653be------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd5ee8ca3076</guid>
            <category><![CDATA[alxafrica]]></category>
            <category><![CDATA[make]]></category>
            <category><![CDATA[alx-blog]]></category>
            <category><![CDATA[makefile-basics]]></category>
            <category><![CDATA[what-is-makefile]]></category>
            <dc:creator><![CDATA[Emmanuel Adebanjo]]></dc:creator>
            <pubDate>Mon, 04 Dec 2023 09:34:26 GMT</pubDate>
            <atom:updated>2023-12-04T09:34:26.425Z</atom:updated>
            <content:encoded><![CDATA[<h4>What is a Makefile?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*YtDWvyuTVKSJJCF-J4xW7g.png" /></figure><p>This is a file created to enhance a project’s build or compilation time. I was almost tempted to think that Makefiles were only used by languages that were compiled, but on further research, I discovered that Makefiles are traditionally associated with compiled languages, where source code is translated into object code or an intermediate form before execution. However, makefiles are not strictly limited to compiled languages. They can be adapted to support a variety of project types, including those associated with interpreted languages or other types of build processes. For the sake of this article, I explore Makefiles using the C programming language, a compiled language.</p><p>I had earlier mentioned that Makefiles enhances a project’s build time, let’s delve into how the make utility helps us achieve this.</p><h4>How do Makefiles enhance build time?</h4><p>Imagine you were working on a project that had over three thousand (3,000) source files and each time you made a change to one file, to view the changes made, you would have to re-compile all three thousand (3,000) source files. Exhausting and time-wasting, right? This is where Makefiles come in handy. The make utility ensures that only the files that were modified and are a prerequisite for the executable end product are recompiled. How does it do this or know what files have been modified🤔?</p><blockquote>The Make utility determines which files to recompile by comparing timestamps (modification times) of source files and their corresponding object files. The process involves checking the dependencies or prerequisites specified in the Makefile and determining whether any of them have been modified since the last build.</blockquote><p>Makefiles consist of sets of rules that determine how a file is maintained or recompiled.</p><h4>What is a Rule?</h4><p>A rule is an important building block that specifies how a target is built. A rule consists of 3 main parts</p><ul><li><strong>Target:</strong> The target is the file or task that needs to be built. It is the result of the rule. It typically represents an executable, object file, or some other output of the build process.</li><li><strong>Dependency or Prerequisite: </strong>Dependencies are the files or tasks that the target depends on. If any of the dependencies are newer than the target, or if the target doesn’t exist, the rule is considered out-of-date, and the recipe will be executed.</li><li><strong>Command or Recipe: </strong>The recipe is a set of commands that are executed to build the target from the dependencies. These commands are typically shell commands or other build tool commands. Each command in the recipe must be preceded by a tab character.</li></ul><blockquote>A rule consists of one or more targets , zero or more dependencies , one or more recipes or commands.</blockquote><p>Syntax of a rule:</p><pre>target: dependency or prerequisite<br>       Command or recipe</pre><p>There are two types of rules, I wouldn&#39;t delve into their definitions, just to maintain the scope of this write-up. They are:</p><ul><li>Implicit rules</li><li>Explicit rules</li></ul><h4>Building a Simple Makefile</h4><p>We’ve spoken too much English 😂, necessary for our understanding, though. It’s time to get practical.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*17mX4k-lmSjlrHeO7lUYkg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*YtDWvyuTVKSJJCF-J4xW7g.png" /><figcaption>Makefile</figcaption></figure><p>I know a lot of things might seem confusing there, to understand how to use Makefiles, I’ll suggest we spend some time understanding the compilation process of whatever language we would be writing the Makefile for.</p><p>In the image above, we create our source files print.c and main.c which outputs our love for Makefiles to the screen while the other is the entry point to our code respectively.</p><p>Looking at our Makefile image we’ll find three rules which are somewhat dependent on each other.</p><h4>Rule 1:</h4><ul><li><strong>Target:</strong> printOut is the target here which is the name of the executable that we’ll be creating after our build is completed. In this case, the target is an actual file that’ll be created. This leads me to Phony Targets.</li></ul><blockquote>Phony Targets are targets 😁 that are not actual filenames, but are required to perform a task. Phony targets could include clean-up actions or a command to force the recompilation of all source files and not just modified files.</blockquote><ul><li><strong>Dependency: </strong>print.o and main.o are the prerequisites to creating the target which is our executable printOut.</li><li><strong>Command or Recipe: </strong>gcc -Wall -Werror -Wextra -pedantic print.o main.o -o printOut is the command or recipe to be executed on the dependencies to create the target, which is our executable program.</li></ul><p>The make utility runs the first rule it encounters in our Makefile if the timestamp on a prerequisite or dependency is more recent than the target then the target is recompiled.</p><p>Notice how when we tried to build our project again without any modification to our files it displayed the message “make: ‘printOut’ is up to date”. This is the beauty of Makefiles, there&#39;s no need for unnecessary rebuilds. Now let’s modify one of the files:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*WlPIB4Vj3CEoikOW36rFFQ.png" /><figcaption>Modified file</figcaption></figure><p>Notice how after modification of the print.c file and running the make command on our Makefile only the print.o was recompiled and nothing was done for main.o.</p><p>Let’s make our script cleaner:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/1*mpjPZfEdESsTa9nT_wtpcQ.png" /><figcaption>Modified Code</figcaption></figure><p>I know a lot of things are new there, please try to read my comments to understand the flow of the script.</p><p>In the Makefile above I created variables that would later be expanded into their assigned values. To shed more light:</p><ul><li>$^ — This is expanded to all prerequisites or dependencies passed.</li><li>$@ — This is expanded to the name of the target</li><li>$&lt; — This expands to the first prerequisite or dependency passed</li><li>%.o — This refers to any alphanumeric sequence of characters that end with a “.o” and is not a space.</li><li>%.c — This refers to any alphanumeric sequence of characters that end with a “.c” and is not a space.</li></ul><p>The “%.o: %.c” rule saves us the stress of writing a rule for every object target (.o) for our source files (.c).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*6UpSY4tX1ekQU7oot_OUOQ.png" /><figcaption>Phony Targets</figcaption></figure><p>If you got to this point you’re simply amazing. Writing Makefiles can be daunting but they save you a lot of wait time in the long run. You can check the <a href="https://www.gnu.org/software/make/manual/html_node/">documentation </a>for Makefiles to get more knowledge of what is possible with Makefiles.</p><p>Don’t forget to hit the clap and follow button to be notified when I write on interesting topics.</p><p>You can connect with me on:<br>LinkedIn: <a href="https://www.linkedin.com/in/adebanjo-emmanuel/">linkedin.com/in/adebanjo-emmanuel/</a><br>Twitter or X: <a href="https://twitter.com/Deolamma">https://twitter.com/Deolamma</a></p><p>Stay Positive and Productive👌.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd5ee8ca3076" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python’s Safety Net: Mastering the Art of Exception Handling]]></title>
            <link>https://python.plainenglish.io/pythons-safety-net-mastering-the-art-of-exception-handling-a9bfcf44b4d2?source=rss-fc2aede653be------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9bfcf44b4d2</guid>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[error-handling]]></category>
            <category><![CDATA[alx-blog]]></category>
            <category><![CDATA[exception-handling]]></category>
            <category><![CDATA[python-programming]]></category>
            <dc:creator><![CDATA[Emmanuel Adebanjo]]></dc:creator>
            <pubDate>Mon, 11 Sep 2023 07:43:09 GMT</pubDate>
            <atom:updated>2023-09-11T11:18:30.442Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PtPaEkRmFQKpEmuCN4NP6g.png" /><figcaption>Image Credit: <a href="https://www.datacamp.com/tutorial/exception-handling-python">https://www.datacamp.com/tutorial/exception-handling-python</a></figcaption></figure><p>It is every developer&#39;s nightmare to discover that their application crashes when users interact with the application. There are a plethora of reasons why an application could crash, this could be due to an invalid input by the user, a network problem, a bug, etc. Whatever the reasons might be, we want to know what caused the crash (<a href="https://www.geeksforgeeks.org/how-to-log-a-python-exception/">logging</a>) and gracefully perform clean-up processes, or relaunch the request if it was a network connection problem. However, gracefully handling errors that might occur in your application while writing the codes is imperative for a seamless user experience. Python offers an opportunity to handle this through exception handling.</p><p>Before we delve into what exceptions are, let&#39;s deal with the two basic kinds of errors we could encounter as developers:</p><h4>Syntax Errors</h4><p>Syntax errors occur at compile time and they are a result of violating Python’s syntax. I like to think of syntax errors as having to deal with the beauty (structure) of your code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*SRRX8GJ-5FWd0LKjsMMP9w.png" /></figure><p>Python as well as other programming languages have strict syntax rules and in fact, wouldn’t allow your codes to compile when these rules are violated. Like in the example above, I was immediately disallowed from continuing to write the code. This is because I was in interactive mode and had failed to indent properly — That is simply breaking syntax as Python expects each block of code to be properly indented. If I was writing a script I wouldn&#39;t be alerted until I was ready to compile then the Python interpreter would alert me of the error in the syntax. To know more about Python’s syntax you can visit the official <a href="https://docs.python.org/3/">Python Documentation</a>. Programming docs can be very boring, but they’ll save you a lot of tears🤣 while coding especially as a beginner. I’m sure you must have heard this often “Read the f***ing doc”. Trust me if you really want to understand what happens under the hood in whatever concept you’re trying to learn, then you should read the doc💯. That being said we move to the second kind of error we could encounter as developers.</p><h4>Exceptions</h4><p>Exceptions occur at runtime and they are a result of errors not handled properly in our codes. Exceptions deal with the functionality of our code and they occur at runtime. If a code is not properly tested for edge cases we could have our applications break in production which is not a good user experience.</p><p>Python has anticipated that there would be such occasions, where our users would not follow the instructions given by the application’s developer either intentionally or unintentionally, and has given us the opportunity to gracefully handle such scenarios without the application crashing through exception handling.</p><p>There are two types of Exceptions in Python:</p><ul><li><strong>User-defined Exceptions:</strong> User-defined exceptions are created by the programmer when specific error conditions unique to the program or application need to be handled. These exceptions are defined by creating custom exception classes that inherit from the built-in BaseException class or one of its subclasses. User-defined exceptions are tailored to the requirements of a particular program or module. They allow you to define and raise custom error conditions that may not be adequately covered by the built-in exceptions.</li></ul><p>I’m still doing some research on user-defined exceptions and will write in-depth on this once I&#39;ve mastered the concept. Anticipate! 😎</p><ul><li><strong>Built-in Exceptions: </strong>Built-in exceptions are provided by Python itself. They are part of the Python standard library and cover a wide range of common error conditions that can occur during program execution. Examples of built-in exceptions include TypeError, ValueError, ZeroDivisionError, and FileNotFoundError, among others. We’ll explore these concepts soon and discover what could result in the errors above. Built-in exceptions are designed to handle general error situations and are suitable for most common programming tasks. They allow you to catch and respond to errors like type mismatches, division by zero, file not found, and more.</li></ul><p>Before we write some codes to better understand built-in commands, let’s acquaint ourselves with some terminologies:</p><ul><li>try : Try simply “tries”😎 to execute a piece of code within its block, if it fails or any error occurs it goes into the except block and checks if the error is caught, if it is, it performs whatever implementation was specified in the block, else, our code crashes i.e. no error handling was put in place.</li><li>except : This is where errors are caught and the developer can decide what would be “done” or “not done” in such a scenario.</li><li>else : The else block is optional and is executed only if no exceptions are raised in the try block. It&#39;s used to specify code that should run when there are no exceptions.</li><li>finally : This is also optional and is executed regardless of whether an exception was raised or not. It&#39;s typically used for cleanup tasks that need to be performed no matter what.</li><li>raise : Used to call a certain type of built-in exception.raise manually raises an exception in your code. You can use it to signal exceptional conditions that you want to handle.</li></ul><p>Pheew, I feel like we’ve been speaking too much English🤣. Let’s get our hands dirty, writing some codes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*j4B1XzmaHseftXHVxUTn8w.png" /></figure><p>This is how error handling is done in its most basic form. I’ll take a detour and explain some of the keywords in the code above that I had not previously explained.</p><ul><li>BaseException : Using the BaseException is like throwing a super large net into the sea and drawing out all living things in the water. BaseException is the BaseClass of all exceptions and would catch any and all errors. It is super useful and comes in handy as a safety net after specifying the specific kinds of errors (we’ll delve into this a little later in the article) we anticipate from the user. We can useBaseExceptionto catch any errors that might sneak past the specific errors we anticipated from the user, after all as developers we should never trust the user to interact with our application as we had specified.</li></ul><p><em>The </em><em>BaseException class is a superclass for both user-defined(They do not do this directly, they inherit from the </em><em>Exception class, which is a subclass of </em><em>BaseException) and built-in exceptions. Visit this </em><a href="https://www.tutorialspoint.com/python-exception-base-classes#:~:text=The%20BaseException%20is%20the%20base,need%20to%20use%20Exception%20class."><em>article</em></a><em> to understand better.</em></p><ul><li>e &amp; str(e) : Remember how importing is done “from … import … as …”. That’s exactly what is happening here, we try to bundle the BaseException class into the object e . When an exception is caught the error messages can be very verbose, most of the time we only want to see the error message, and str(e) is an attribute of a class that gives us a human-readable string representation of the object of the class, or in this case, a human-readable string informing us about the error encountered. I’ll explain this in more detail when I write an article on Python’s Classes and Objects.</li><li>Lastly, the if block only checks if the script is being run as the main script and not being imported to be used in another script. If it is being imported into another script the lines beyond the if check will not be executed.</li></ul><p>Let’s take a look at the output of the code in the image above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*VFKxYiVMwUYFYv-iAQGOpg.png" /></figure><p>In this case, the BaseException class helped catch the ZeroDivisionError and has given us a very readable error message. As an exercise try printing out e not str(e)</p><p>As I said it’s good practice to anticipate errors from the user and raise them appropriately. For instance, if you expect to open a file from a user&#39;s device we could anticipate “What if the file does not exist on the user’s device?”. In such a case, we want to raise an exception by ourselves and print a message to the user, that “we expect a file and it was not found”. In the next image, I’ll depict how we could raise exceptions when the user doesn’t do what we expect or the resource we need to work with, in our code is not provided. I’ll also show you how to add your own message to be displayed to the user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*45iOSqNWRRBsa75G_hQ1rw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/659/1*F3Qcs_Nhsu7bZZX61D1PmA.png" /></figure><p>In the code above, I show one way to print an error message when an exception is caught. Let’s take a look at the next example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*rGj-BeCqqHpT3OOJb35cpQ.png" /></figure><p>Here we raise exceptions if our conditions are not met and display a custom message to the user to enlighten them on what they’re doing wrong. Perhaps they already knew and wanted to test us😂. You’ll also see something interesting if you have tried the str(e)exercise I mentioned earlier. Printing e doesn’t spew the verbose message you had experienced earlier, this is because we specified the error message to be displayed to the user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*mgklo5jsx9MXMjJCEwJ-BQ.png" /></figure><p>It is important to use the BaseException as the last except block to catch any exceptions that might have sneaked past your anticipated errors. It is always best to log this error, because as a developer you want to know what happened and deal with it appropriately.</p><p>Spend some time playing around with these concepts, that’s the most effective way to understand any programming language you want to explore.</p><p>If you got here, you’re amazing👏 and on your way to becoming a top-rated developer. I have been exploring Test Driven Development(TDD) in Python. As soon as I grasp the concept fully, you’ll be the first to read about it. Anticipate!😎</p><p>Feel free to connect with me:</p><p><strong>LinkedIn</strong>: <a href="https://www.linkedin.com/in/adebanjo-emmanuel/">linkedin.com/in/adebanjo-emmanuel/</a><br><strong>X</strong>: <a href="https://twitter.com/Deolamma">https://twitter.com/Deolamma</a></p><p>Stay Positive and Productive👌.</p><h3>In Plain English</h3><p><em>Thank you for being a part of our community! Before you go:</em></p><ul><li><em>Be sure to </em><strong><em>clap</em></strong><em> and </em><strong><em>follow</em></strong><em> the writer! 👏</em></li><li><em>You can find even more content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><strong><em> 🚀</em></strong></li><li><em>Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. 🗞️</em></li><li><em>Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a><strong><em>(X</em></strong>), <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a>, <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a>, and <a href="https://discord.gg/GtDtUAvyhW"><strong><em>Discord</em></strong></a><strong><em>.</em></strong></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9bfcf44b4d2" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/pythons-safety-net-mastering-the-art-of-exception-handling-a9bfcf44b4d2">Python’s Safety Net: Mastering the Art of Exception Handling</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python’s Brackets, Parentheses, and Curly Braces]]></title>
            <link>https://python.plainenglish.io/pythons-brackets-parentheses-and-curly-braces-60cdc236cdd6?source=rss-fc2aede653be------2</link>
            <guid isPermaLink="false">https://medium.com/p/60cdc236cdd6</guid>
            <category><![CDATA[dictionaries-in-python]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[lists-in-python]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[tuples-in-python]]></category>
            <dc:creator><![CDATA[Emmanuel Adebanjo]]></dc:creator>
            <pubDate>Mon, 21 Aug 2023 09:25:06 GMT</pubDate>
            <atom:updated>2023-08-22T03:14:29.984Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*S8cZ1gKkJLWBPskuL1i_-A.jpeg" /></figure><p>Brackets — [], parentheses — (), &amp; curly braces — {} are fundamental concepts that should be understood when dealing with the Python programming language. To a large extent, these paradigms if adequately understood and properly used would help you handle complex scenarios when writing codes in Python. I know you can’t wait to delve into these exciting concepts 😁 and I would keep you waiting no longer 😎.</p><h3>Brackets []</h3><p>In the Python programming language whenever we see this symbol “[]” it indicates that we are dealing with the List data structure.</p><h4>What Is A List?</h4><p>A List in the Python programming language is a mutable data structure that contains an ordered collection of heterogenous data types. Let’s break this down:</p><ul><li>Mutable — This means that the elements or data in a List data structure can be changed. This can be done using indexing or slicing. To understand what indexing or slicing means, please check out my <a href="https://medium.com/python-in-plain-english/a-beginners-guide-to-python-9eec0c5ac15">previous article</a> where I explained these concepts.</li></ul><pre>my_list = [1, 2, 3, 4]<br>my_list[2] = 5<br>print(my_list) //Output should be [1, 2, 5, 4]</pre><p>In the example above I only illustrate how indexing can be used to change data at a certain index, taking advantage of Python’s list mutable ability. Isn’t it amazing??</p><ul><li>Ordered — This indicates that the elements or data can be retrieved or accessed based on their index. Lists are “zero-indexed” and so long as the data at a certain index is not changed, every time we access that index we’ll always retrieve or get the same data.</li><li>Heterogenous data types — This simply means that the elements or data in a list can contain different data types.</li></ul><pre>my_list = [1 , 2.0, &quot;Hello&quot;, &quot;world&quot;, True]</pre><p>In the code above we can see that my_listis a list containing multiple data types which can all be accessed and manipulated based on their indexes.</p><h4>Operating On A List</h4><p>Various operations can be carried out on a list, which includes but is not limited to:</p><p><strong>Accessing Elements:</strong></p><ul><li>Indexing — Accessing or retrieving data from a list based on the position (index) which is “zero-indexed”.</li><li>Slicing — Accessing a sublist of a list by specifying a range of numbers.</li></ul><p>To fully understand slicing and indexing, I’ll encourage you to check out my <a href="https://medium.com/python-in-plain-english/a-beginners-guide-to-python-9eec0c5ac15">previous article</a> where I explained this in detail.</p><p><strong>Modifying Elements:</strong></p><ul><li>Assigning — Modifies elements by assigning new values to specific positions based on their index in the list.</li><li>Appending — Adds an element to the end of the list.</li><li>Concatenating — Appends another list to the end of the current list.</li><li>Inserting — Insert an element at a specific position in the list (same as indexing).</li><li>Removing — Deletes the first occurrence of a specific element from the list. It takes the data to be removed as an argument. my_list.remove(element_to_be_removed)</li><li>Popping — Deletes and returns (i.e. prints to STDOUT) the element to be removed from a specific position in the list. my_list.pop(index_of_element)</li></ul><p><strong>Listing Operations:</strong></p><ul><li>Concatenation — Combines two lists to create a new list. This is commonly done using the “+” operator.</li><li>Repetition — Creates a new list by repeating the elements of an existing list. Remember how we duplicated strings in our <a href="https://medium.com/python-in-plain-english/a-beginners-guide-to-python-9eec0c5ac15">previous article</a>? This is done the same way.</li></ul><p><strong>Searching and Counting:</strong></p><ul><li>index(element_to_find_index) — Finds the index of the first occurrence of a specific element.</li><li>count(element_to_be_counted) — Counts the number of occurrences of a specific element in the list.</li></ul><p><strong>Sorting:</strong></p><ul><li>sort() — Sorts the elements of the list in ascending order.</li></ul><p><strong>Other Operations:</strong></p><ul><li>len() — Gets the number of elements in the list.</li><li>in — Checks if an element is present in the list.</li><li>not in — Checks if an element is not present in the list.</li><li>min() — Finds the minimum element in the list.</li><li>max() — Finds the maximum element in the list.</li></ul><p>We’ve been speaking too much English 😂. Let’s write some codes 💪</p><pre>my_list = [1, 2, 3, 4, 5]<br><br># Accessing elements<br>print(my_list[0])  # Output: 1<br>print(my_list[1:4])  # Output: [2, 3, 4]<br><br># Modifying elements<br>my_list[2] = 10<br>print(my_list)  # Output: [1, 2, 10, 4, 5]<br><br>my_list.append(6)<br>print(my_list)  # Output: [1, 2, 10, 4, 5, 6]<br><br># List operations<br>new_list = my_list + [7, 8, 9]<br>print(new_list)  # Output: [1, 2, 10, 4, 5, 6, 7, 8, 9]<br><br>repeated_list = my_list * 2<br>print(repeated_list)  # Output: [1, 2, 10, 4, 5, 6, 1, 2, 10, 4, 5, 6]<br><br># Searching and counting<br>print(my_list.index(10))  # Output: 2<br>print(my_list.count(4))  # Output: 1<br><br># Sorting<br>my_list.sort()<br>print(my_list)  # Output: [1, 2, 4, 5, 6, 10]<br><br># Other operations<br>print(len(my_list))  # Output: 6<br>print(3 in my_list)  # Output: False<br>print(5 not in my_list)  # Output: False<br>print(min(my_list))  # Output: 1<br>print(max(my_list))  # Output: 10<br><br><br>#EXAMPLE CREDIT: CHATGPT</pre><p><strong><em>Please note:</em></strong><em> Even though a list accepts a heterogenous mix of data types, some operations can not be carried out on a heterogenous list. For instance, how can a list which contains string, int, and Boolean data be sorted using the </em><em>sort() operation? or how can the min or max value be found? If we attempt to run these operations on a heterogenous list, then the interpreter will spew errors at you 😆. Don’t do this!</em></p><p>I’ll encourage you to explore all possibilities you can think up, you might just be amazed at what the list data structure in Python is capable of.</p><h4>Traversing A List</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*korxy3hHdaMMmJjyvL9vDQ.png" /><figcaption>Traversing A List</figcaption></figure><p>In the first scenario, we loop through the my_list variable and print out the data contained in the list. But in the second scenario, using the enumerate() method we were able to also retrieve the index of each element as well as the data stored in that index. This can be used for endless purposes. Try playing around with this concept to understand it even better.</p><h3>Parentheses ()</h3><p>You must have noticed us using this symbol in the past or you might not have, and it’s fine… Remember our famous print() statement? We use parentheses to house the arguments or parameter list of a function.</p><pre>def my_name(name=&quot;&quot;):<br>print(f&quot;My name is: {name}&quot;) </pre><p>Notice how parentheses were used to receive the arguments to the print statement and the parameter expected by the my_name method.</p><p>Another use for the parentheses is to communicate to the interpreter that we know what we are doing and we want a certain operation to be done exactly the way we had specified(parenthesized).</p><p>Pro tip: Normally operations are run from left to right in Python based on operator precedence. Let’s take a look at what happens with the exponentiation operator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*aU9LxeyznYWQPd1vhziTyA.png" /></figure><p>OMG 😮… Is something wrong with my interpreter?<br>2**3 = 8 and 8**2 = 64. How am I getting 512? Nothing is wrong with your computer, the exponentiation operator is the only operator I can think of right now that breaks the left-to-right principle of handling operations in Python. what has happened is that the interpreter executed this order:<br>3**2 = 9 and 2**9 = 512.</p><p>We use parentheses in situations like this to inform the interpreter that we know what we’re doing and that we want the operation to be run in a certain order specified by us. To have our desired result, we have to do this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/981/1*5f1VrvtCUGKgZoYOlFF1gg.png" /></figure><p>All of the above-mentioned are other uses of the parentheses. The main use of the parentheses in the Python programming language in my opinion is to indicate that we are working with a <strong>tuple</strong>.</p><h4>What is a Tuple?</h4><p>A tuple in the Python programming language is an immutable data structure that contains an ordered collection of heterogenous data types.</p><p>It is important to note that tuples are immutable i.e. once it is created it remains constant until the end of the execution of the program. It is also important to note that whilst the tuple cannot be changed if it contains any mutable element, that element can be changed or altered. Take a look at the codes below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gDG9V8gMFpwT0UFW2a6sIQ.png" /></figure><p>Notice how when we tried to change the element of the tuple and we got an error message. To understand this error message take a look at my <a href="https://medium.com/python-in-plain-english/a-beginners-guide-to-python-9eec0c5ac15">previous article</a> where I explained this in detail. Now, notice how I was able to change the content of the last tuple. The tuple itself cannot be changed because a tuple is a constant list. The third element of the tuple is a mutable list, remember? So, we can modify the content of that element. If we try to change the list to some other data, we will get an error.</p><p><em>A tuple is a list but an immutable list</em></p><h4>Operating On A Tuple</h4><p>Various operations can be carried out on a tuple except attempting to change the data in a tuple. Here are a few:</p><p><strong>Accessing Elements:</strong></p><ul><li>Indexing — Accessing individual elements by their position (index) in the tuple.</li><li>Slicing — Extracting a sub-tuple by specifying a range of indices.</li></ul><p><strong>Tuple Operations:</strong></p><ul><li>Concatenation — Combines two tuples to <strong>create a new tuple. </strong>To create a “new” tuple not to update the existing tuple.</li><li>Repetition — Creates a <strong>new tuple</strong> by repeating the elements of an existing tuple.</li></ul><p><strong>Searching and Counting:</strong></p><ul><li>index(element_to_find_index_of) — Finds the index of the first occurrence of a specific element.</li><li>count(element_to_be_counted) — Counts the number of occurrences of a specific element in the tuple.</li></ul><p><strong>Tuple Unpacking:</strong></p><ul><li>Assigns the elements of a tuple to individual variables.</li></ul><p>I’m sure we must have noticed that the same operations carried out on a list can be carried out on a tuple. This is simply because a tuple is an immutable list.</p><pre>my_tuple = (1, 2, 3, 4, 5)<br><br># Accessing elements<br>print(my_tuple[0])  # Output: 1<br>print(my_tuple[1:4])  # Output: (2, 3, 4)<br><br># Tuple operations<br>new_tuple = my_tuple + (6, 7, 8)<br>print(new_tuple)  # Output: (1, 2, 3, 4, 5, 6, 7, 8)<br><br>repeated_tuple = my_tuple * 2<br>print(repeated_tuple)  # Output: (1, 2, 3, 4, 5, 1, 2, 3, 4, 5)<br><br># Searching and counting<br>print(my_tuple.index(3))  # Output: 2<br>print(my_tuple.count(4))  # Output: 1<br><br># Tuple unpacking<br>a, b, c = my_tuple<br>print(a, b, c)  # Output: 1 2 3<br><br><br># EXAMPLE CREDIT: CHATGPT</pre><h4>Traversing A Tuple</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9meMQ2gL2aewwIg0513agg.png" /><figcaption>Traversing A Tuple</figcaption></figure><p>You guessed right 👌. The Tuple data structure can be traversed the same way as the List data structure.</p><h3><strong>Curly Braces {}</strong></h3><p>Curly braces find usage in other contexts, I’ll let you find that out, we’ve used it in this article for reasons other than what I’m about to discuss. Curly braces denote a Dictionary in the Python programming language.</p><h4>What is a Dictionary?</h4><p>A dictionary is an unordered data structure of key-value pairs.</p><p><strong>Note:</strong> A dictionary is a key-value pair. The keys must be unique and of homogenous(same) data type, while the value can be of heterogenous data type and does not have to be unique. Before we look at how a dictionary data structure is represented…</p><p>Unordered — Indicates that the value of a dictionary cannot be accessed by indexing but by the key.</p><p>Structure of a dictionary:</p><pre>my_dict = {&quot;name&quot;: &quot;John&quot;, &quot;age&quot;: 30, &quot;is_student&quot;: False}</pre><h4><strong>Operating On A Dictionary:</strong></h4><p>Various operations can be carried out on a dictionary. Here, we highlight a few:<br><strong>Accessing Values:</strong></p><ul><li>Using Keys — Retrieves values associated with specific keys.</li><li>get(key) — Safely retrieves a value by key, handling missing keys without raising an error.</li><li>keys() — Gets a view object of all keys in the dictionary.</li><li>values() — Gets a view object of all values in the dictionary.</li><li>items() — Gets a view object of all key-value pairs in the dictionary.</li></ul><p><strong>Modifying Dictionaries:</strong></p><ul><li>Adding or Modifying Key-Value Pairs — Inserts new key-value pairs or update existing ones.</li><li>update() — Merges the content of another dictionary into the current dictionary.</li></ul><p><strong>Removing Elements:</strong></p><ul><li>del — Removes a key-value pair from the dictionary using the del statement.</li><li>pop(key) — Removes a key-value pair and returns the associated value.</li><li>clear() — Removes all key-value pairs from the dictionary.</li></ul><p><strong>Dictionary Operations:</strong></p><ul><li>len() — Gets the number of key-value pairs in the dictionary.</li><li>in — Checks if a key is present in the dictionary.</li><li>not in — Checks if a key is not present in the dictionary.</li></ul><pre>my_dict = {&quot;name&quot;: &quot;John&quot;, &quot;age&quot;: 30, &quot;is_student&quot;: False}<br><br># Accessing values<br>print(my_dict[&quot;name&quot;])  # Output: John<br>print(my_dict.get(&quot;age&quot;, &quot;N/A&quot;))  # Output: 30<br>print(my_dict.keys())  # Output: dict_keys([&#39;name&#39;, &#39;age&#39;, &#39;is_student&#39;])<br>print(my_dict.values())  # Output: dict_values([&#39;John&#39;, 30, False])<br>print(my_dict.items())  # Output: dict_items([(&#39;name&#39;, &#39;John&#39;), (&#39;age&#39;, 30), (&#39;is_student&#39;, False)])<br><br># Modifying dictionaries<br>my_dict[&quot;city&quot;] = &quot;New York&quot;<br>print(my_dict)  # Output: {&#39;name&#39;: &#39;John&#39;, &#39;age&#39;: 30, &#39;is_student&#39;: False, &#39;city&#39;: &#39;New York&#39;}<br><br>my_dict.update({&quot;is_student&quot;: True, &quot;gender&quot;: &quot;Male&quot;})<br>print(my_dict)  # Output: {&#39;name&#39;: &#39;John&#39;, &#39;age&#39;: 30, &#39;is_student&#39;: True, &#39;city&#39;: &#39;New York&#39;, &#39;gender&#39;: &#39;Male&#39;}<br><br># Removing elements<br>del my_dict[&quot;city&quot;]<br>print(my_dict)  # Output: {&#39;name&#39;: &#39;John&#39;, &#39;age&#39;: 30, &#39;is_student&#39;: True, &#39;gender&#39;: &#39;Male&#39;}<br><br>value = my_dict.pop(&quot;age&quot;)<br>print(value)  # Output: 30<br><br>my_dict.clear()<br>print(my_dict)  # Output: {}<br><br># Dictionary operations<br>print(len(my_dict))  # Output: 0<br>print(&quot;name&quot; in my_dict)  # Output: False<br>print(&quot;gender&quot; not in my_dict)  # Output: False<br><br><br>#EXAMPLE CREDIT: CHATGPT</pre><h4>Traversing A Dictionary</h4><p>The items() provides us access to the key and value when looping through a dictionary. Let’s take a look at the code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RHRy_ST00cvbAyfxSTVDHg.png" /><figcaption>Traversing a Dictionary</figcaption></figure><p>Pheew… It’s been a long but rewarding read. If you got to this point then you’re amazing 😎. There are a lot more concepts to explore in the world of Lists, Tuples, and Dictionaries, some of which are <a href="https://www.programiz.com/python-programming/list-comprehension#:~:text=Points%20to%20Remember-,List%20comprehension%20is%20an%20elegant%20way%20to%20define%20and%20create,that%20code%20is%20user%2Dfriendly.">List</a> and <a href="https://www.programiz.com/python-programming/dictionary-comprehension">Dictionary</a> Comprehension. Also, take out some time to explore in-depth some of the concepts already explored here.</p><p>If you have a question or suggestion about what I should write next, use the comment section and I’ll be happy to respond.</p><p>You can connect with me on:<br>LinkedIn: <a href="https://www.linkedin.com/in/adebanjo-emmanuel/">linkedin.com/in/adebanjo-emmanuel/</a><br>X: <a href="https://twitter.com/Deolamma">https://twitter.com/Deolamma</a></p><p>Stay Positive and Productive👌.</p><h3>In Plain English</h3><p><em>Thank you for being a part of our community! Before you go:</em></p><ul><li><em>Be sure to </em><strong><em>clap</em></strong><em> and </em><strong><em>follow</em></strong><em> the writer! 👏</em></li><li><em>You can find even more content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><strong><em> 🚀</em></strong></li><li><em>Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. 🗞️</em></li><li><em>Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a>, <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a>, <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a>, and <a href="https://discord.gg/GtDtUAvyhW"><strong><em>Discord</em></strong></a><strong><em>.</em></strong></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60cdc236cdd6" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/pythons-brackets-parentheses-and-curly-braces-60cdc236cdd6">Python’s Brackets, Parentheses, and Curly Braces</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Beginners’ Guide to Python]]></title>
            <link>https://python.plainenglish.io/a-beginners-guide-to-python-9eec0c5ac15?source=rss-fc2aede653be------2</link>
            <guid isPermaLink="false">https://medium.com/p/9eec0c5ac15</guid>
            <category><![CDATA[alxafrica]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[alx-blog]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Emmanuel Adebanjo]]></dc:creator>
            <pubDate>Mon, 07 Aug 2023 06:24:28 GMT</pubDate>
            <atom:updated>2023-08-10T01:16:46.815Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E4od0LKRNcYZ6ueDyfSqIQ.png" /></figure><h4>Is Python A Scripting or Programming Language 🤔?</h4><p>Before we answer the important question above, let’s give honor to who honor is due: <a href="https://en.wikipedia.org/wiki/Guido_van_Rossum">Guido Van Rossum</a> — The creator of the powerful Python programming language, oops… I guess we have to clarify now 🙂</p><p>Python is a general-purpose, high-level programming language used by developers for various purposes such as Web Development, Data Science, Artificial Intelligence, &amp; Automation, etc. It would interest you to note that Python is also referred to as a scripting language because it is commonly used for writing scripts. A script is a set of instructions that can be run directly on an interpreter without the need for compilation.</p><p>Python is both a programming language used for creating complex applications through its rich range of features and libraries, and a scripting language that can be used for automating processes.</p><p><em>Fun fact: Python wasn&#39;t named after a snake, it was named after the famous TV show “Monty Python’s Flying Circus”.</em></p><h4>Installing Python IDE</h4><p>There are two main kinds of Python: Python2 and Python3. The improvement of Python2 has been discontinued and Python3 is not backward compatible with Python2, i.e. If you previously had a script in Python2 and you needed to execute in a Python3 interpreter, it wouldn&#39;t run and you’ll simply need to rewrite your code in Python3.</p><p><em>There are other kinds of Python which include </em><a href="https://en.wikipedia.org/wiki/CPython#:~:text=CPython%20can%20be%20defined%20as,a%20language%20other%20than%20Python."><em>CPython</em></a><em>, </em><a href="https://en.wikipedia.org/wiki/Jython"><em>JPython</em></a><em>, </em><a href="https://en.wikipedia.org/wiki/PyPy"><em>PyPy,</em></a><em> etc. PyPy is mainly used by developers who intend to write a new variant of Python.</em></p><p>If you’re using a Linux Ubuntu OS, then you are in luck as you should have the latest Python3 already installed. Simply type the following command in your terminal.</p><pre>Python3 --version</pre><p>Perhaps, you do not have it already installed or you don’t use Ubuntu. Simply run the following commands:</p><pre>sudo apt install Python3 Python3-pip</pre><p>Running the command above goes into the Linux package manager, gets, and installs the Python3 and Python3-pip package, I’ll explain what the pip package is used for later on in this article. For now, let’s write our first script 😉</p><h4>Writing Your First Python Script</h4><p>For a script to be recognized as a Python script it is imperative to end the name of the script or file as “.py” i.e. name_of_file.py. This automatically qualifies the file to be a Python script. Let’s write some codes 💪</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1007/1*2pp93MUUNlh-vlWHUHjG2A.png" /></figure><p>For now, forget about the codes or script in the image above we’ll deal with that in depth in a short while. Instead, let’s focus on how Python scripts are Executed. Remember how <a href="https://www.geeksforgeeks.org/shell-scripting-interactive-and-non-interactive-shell/">interactive</a> and <a href="https://www.geeksforgeeks.org/shell-scripting-interactive-and-non-interactive-shell/">non-interactive</a> modes are implemented in a <a href="https://www.geeksforgeeks.org/shell-scripting-interactive-and-non-interactive-shell/">shell</a> 💡? The <a href="https://www.datacamp.com/tutorial/data-science-python-ide">Python IDE (Integrated Development Environment)</a> works exactly the same. It can run in both interactive and non-interactive mode. Pay attention to how the script was run in a non-interactive mode in the image below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*9TRW6PeW2o7JGcXyz9uRfg.png" /></figure><p>The Python IDE can also work in an interactive mode(REPL) just like a UNIX terminal does and I will illustrate this with a core feature of the Python IDE which is calculating. The Python IDE can be used as a calculator. check the image below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zlO1Vl3zaLCw4GSLtpDLEA.png" /></figure><p>By simply typing the command “Python3&quot; on our UNIX terminal we launch the Python IDE in interactive mode. Notice how it would always prompt for a new input until you exit the IDE by explicitly typing “exit()” or “Ctrl + D”. This launches me into operators and numeral operations in Python.</p><h4>Operators and Numeral Operations in Python</h4><p>In this write-up, I will explain only the operators that were used in the image above, take note that there are a host of others, at a glance, we would notice that the subtraction “-” operator wasn&#39;t used in the examples in the image above.</p><ul><li>Plus “+” — sums up two or more <a href="https://www.google.com/search?q=operands&amp;oq=operands&amp;aqs=chrome..69i57j0i512j0i20i263i512j0i512l7.2962j0j9&amp;sourceid=chrome&amp;ie=UTF-8">operands</a></li><li>Multiplication “*” — Multiplies two or more <a href="https://www.google.com/search?q=operands&amp;oq=operands&amp;aqs=chrome..69i57j0i512j0i20i263i512j0i512l7.2962j0j9&amp;sourceid=chrome&amp;ie=UTF-8">operands</a></li><li>Division “/” — Divides two <a href="https://www.google.com/search?q=operands&amp;oq=operands&amp;aqs=chrome..69i57j0i512j0i20i263i512j0i512l7.2962j0j9&amp;sourceid=chrome&amp;ie=UTF-8">operands</a>.</li></ul><p><em>Python is intuitive and prints out the result of the division as a </em><a href="https://www.google.com/search?q=floating+point+number+python&amp;oq=floating+poi&amp;aqs=chrome.1.0i512j0i20i263i512j69i57j46i199i465i512j0i512l6.4635j0j7&amp;sourceid=chrome&amp;ie=UTF-8"><em>floating point number</em></a><em> despite the fact that the </em><a href="https://www.google.com/search?q=operands&amp;oq=operands&amp;aqs=chrome..69i57j0i512j0i20i263i512j0i512l7.2962j0j9&amp;sourceid=chrome&amp;ie=UTF-8"><em>operands</em></a><em> were </em><a href="https://www.google.com/search?q=integers&amp;oq=integers&amp;aqs=chrome..69i57j0i20i263i512j0i512l8.2900j0j9&amp;sourceid=chrome&amp;ie=UTF-8"><em>integers</em></a><em>.</em></p><ul><li>Modulo “%” — Returns the remainder after a division between two operands</li><li>Floor Division “//” — Returns the nearest whole number, lower than the division of the operands. Take a look at the division operator, and compare it with the result of the floor division</li><li>“-” — Unofficially I’ll call this “previous result” operator 😁. Python is smart and when you use this operator it gives you the last result that was printed on the IDE and you can make use of it as you wish.</li><li>Exponential “**” — This raises the left operand to the power of the right operand.</li></ul><h4>String Operation in Python</h4><p>There are various String operations that could be carried out in Python, such as:</p><ul><li>Quoting — This deals with how to use the single quotation (‘ ’) or double quotation (“ “) appropriately and effectively. See the example below:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*-tq3Y_voWWovzV3Gv0OVIQ.png" /><figcaption>Script</figcaption></figure><p>The line in blue was commented out because it is an incorrect way to quote in Python.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gQHeWqeOJBbGffEVE0eyCg.png" /><figcaption>Output</figcaption></figure><p>As an exercise try to quote this in one line. tip you can make use of <a href="https://www.google.com/search?q=newline+in+programming&amp;oq=newline&amp;aqs=chrome.0.69i59j69i57j0i67i650j0i512l3j0i10i457i512j0i402i650j0i512l2.1519j0j7&amp;sourceid=chrome&amp;ie=UTF-8">“\n”</a><br>“I’m”<br>“”learning””<br>“””Python”””</p><ul><li>Concatenation — This is the act of joining two or more strings together</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v-EaT6ko6bZatOobAj0koQ.png" /><figcaption>Concatenation</figcaption></figure><p>Pay attention to how concatenation was done using the arithmetic operator “+”, also pay attention to how the multiplication “*” operator was used to duplicate strings. Remember those three gigantic arrows I created above, the multiplication trick was what was used. There are endless possibilities on how to concatenate in Python. Keep practicing to discover correct or incorrect syntaxes while concatenating.</p><ul><li>Slicing and Indexing — These are two concepts in Python that allow you to carry out operations such as accessing specific elements or a range of elements in a sequence, <a href="https://www.w3schools.com/python/python_lists.asp">lists</a>, <a href="https://www.w3schools.com/python/python_tuples.asp">tuples</a>, or <a href="https://www.w3schools.com/python/python_strings.asp">strings</a>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EI9-SrME-xbVzvKUNVXphA.png" /><figcaption>Slicing and Indexing</figcaption></figure><p>Notes from the image above:</p><ul><li>Strings are zero-indexed, i.e. the first letter of the string has an index number of ‘0’.</li><li>Slicing occurs when we specify a range of numbers in a bracket separated by a double colon “:”, the range specified would be printed to <a href="https://www.google.com/search?q=stdout&amp;oq=STDOUT&amp;aqs=chrome.0.0i512l10.1960j0j4&amp;sourceid=chrome&amp;ie=UTF-8">STDOUT</a> starting at and including the character at the index of the number on the left of the double colon, up to but excluding the character at the number specified on the right side of the double colon. If no number is specified after the double colon, Python understands to keep printing till the end of the string.</li></ul><p><em>Slicing handles “index out of range” gracefully by outputting a ‘ ’ if an index outside the range of the string is specified. However, indexing doesn’t have this feature, that’s why we encounter the error message after the last input in the image above.</em></p><ul><li>When a number is specified inside brackets, indexing helps us get the particular character at that index, if the index is out of the range of the string then an error message is returned.</li></ul><h4>Python and CLI Args</h4><p>Did you know that command line (CLI) arguments can be passed and used in our Python script? Remember this concept in C? This is done with the help of a built-in module from Python. Let’s see how this works:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P02SS4-Vjgd2swpvZqZ8dw.png" /><figcaption>CLI Implementation</figcaption></figure><p>To use arguments passed to the command line (CLI) we must import the “sys” built-in module in Python. Please note:</p><ul><li>To access the arguments passed to the command line (CLI), we use sys.argv[index]. Please note that sys.argv[0] would always hold the name of our Python script.</li><li>Arguments passed to the command line (CLI) are read as strings. Hence, if we intend to pass any other type through the CLI we must <a href="https://www.google.com/search?q=type+casting+in+general+programming&amp;sxsrf=AB5stBgDud6a_AdHnnOxHU9MkkyJoKiAUQ%3A1691318748890&amp;ei=3HnPZIr5NfTD8gKS4pWwCQ&amp;ved=0ahUKEwiK1-qp7ceAAxX0oVwKHRJxBZYQ4dUDCA8&amp;uact=5&amp;oq=type+casting+in+general+programming&amp;gs_lp=Egxnd3Mtd2l6LXNlcnAiI3R5cGUgY2FzdGluZyBpbiBnZW5lcmFsIHByb2dyYW1taW5nMgoQABhHGNYEGLADMgoQABhHGNYEGLADMgoQABhHGNYEGLADMgoQABhHGNYEGLADMgoQABhHGNYEGLADMgoQABhHGNYEGLADMgoQABhHGNYEGLADSLskUKUHWLcTcAF4AJABAJgBuwygAdIrqgEFNy0zLjG4AQPIAQD4AQHiAwQYACBBiAYBkAYH&amp;sclient=gws-wiz-serp">type cast</a> our sys.argv[index] to the appropriate data type.</li><li>If we do not pass the required number of arguments to the CLI, then an error is printed to <a href="https://www.google.com/search?q=stdout&amp;oq=STDOUT&amp;aqs=chrome.0.0i512l10.1960j0j4&amp;sourceid=chrome&amp;ie=UTF-8">STDOUT</a>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4qJFkSpQhYjR-TV_y0b9OA.png" /></figure><h4>Understanding Error Messages</h4><p>In Python, when an error occurs during the execution of a program, Python generates an error message called a “traceback.” This traceback provides information about the sequence of function calls that led to the error, starting from the point where the error occurred and going back through the call stack to the initiating end of the error. Analyzing the Error in a down-up order, The traceback typically includes the following components:</p><ol><li>The error type and description: The first line of the traceback usually shows the kind of error that occurred (e.g., SyntaxError, TypeError, NameError, etc.) followed by a brief description of the error. In our case, it is an IndexError and the error message tells us that we are trying to access an index in the script which is out of range.</li><li>The traceback information: Following the error type and description, you’ll see a series of lines representing the call stack. Each line shows the function or method call that led to the error. The line with the phrase “most recent call last” indicates the location in your code where the error actually occurred. The line above shows the function that called the function where the error occurred, and so on. In our case, since we didn’t specify a function so it gave us the name of our script and &lt;module&gt; because we didn&#39;t specify a function or module.</li><li>The error location: The last line of the traceback typically shows the specific line number and file name where the error happened. In our case, it is line 2, where we try to access the CLI argument at index 1 and 2, but we did not specify those in our execution.</li></ol><h4>Python Linting</h4><p>This should be a whole write-up, but I’ll try to summarise it;</p><p>Remember our famous friend and enforcer of standard best practices while writing codes in C — “Aunty” Betty, “Uncle” Pycodestyle is our enforcer and friend in Python.</p><p>pycodestyle is a tool to check your Python code against some of the style conventions in <a href="https://peps.python.org/pep-0008/">PEP8</a>. Actually, pycodestyle used to be called <a href="https://peps.python.org/pep-0008/">PEP8</a> until Guido Van Rossum’s request for the name to be changed.</p><p>Remember when we installed “Python3-pip”, this is the first step to installing our Python code linter. We need to run the following commands on our CLI:</p><pre>pip install pycodestyle</pre><p>For some reason when I was trying to do this, I kept receiving a message “Requirement already satisfied” yet pycodestyle wasn’t working until I ran this command</p><pre>sudo apt install pycodestyle</pre><p>Let’s run pycodestyle on the script we’ve been working with so far.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*acYVRmq24mRSlsiX4-Sl8A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*cVnFq5xXc1KG94gEXKzP6Q.png" /></figure><p>Let us examine the error message, from left to right:</p><ul><li>test2.py:1:6: — this is the name of our Python script, followed by the line number, and the exact position on the line where the warning is signaling from.</li><li>E211: This is the current error code for the warning being displayed. pycodestyle has a host of them. Feel free to check them out <a href="https://pycodestyle.pycqa.org/en/latest/intro.html#error-codes">here</a>.</li><li>Finally, we have the description of the error code.</li></ul><p>If the checks were successful, we simply do not get any errors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*G9OefJCvo-dHOp0ggNdFiw.png" /></figure><p>Run the command pycodestyle -h to familiarize yourself with a list of flags that can be used with pycodestyle to check your codes and ensure that you are adhering to the guidelines of Python.</p><p>Finally, did you know that the Python IDE could be used as an editor?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*AJNghu-GDbbMfa9KVVDENQ.png" /></figure><p>Oops, this is why it’s advisable and preferable to work in script mode rather than working with the IDLE directly as an editor. I wasn’t able to print my fancy text because I didn’t indent my print statement properly. Also, notice how the IDLE changed from “&gt;&gt;&gt;” to “…” this showed that we were writing a continuous line of code and not trying to execute a separate new command. Let’s indent properly and I can then have my fanciful text 🙂.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*PZMHz-2tq-SoBxMisdg_Xw.png" /></figure><p>Yipee!😎😎, If you got to this point, you are amazing 👌 and you could print that too 😺. If you have a question or suggestion about what I should write next, use the comment section and I’ll be happy to respond.</p><p>You can connect with me on:<br>LinkedIn: <a href="https://www.linkedin.com/in/adebanjo-emmanuel/">linkedin.com/in/adebanjo-emmanuel/</a><br>Twitter or X: <a href="https://twitter.com/Deolamma">https://twitter.com/Deolamma</a></p><p>Stay Positive and Productive👌.</p><h3>In Plain English</h3><p><em>Thank you for being a part of our community! Before you go:</em></p><ul><li><em>Be sure to </em><strong><em>clap</em></strong><em> and </em><strong><em>follow</em></strong><em> the writer! 👏</em></li><li><em>You can find even more content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><strong><em> 🚀</em></strong></li><li><em>Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. 🗞️</em></li><li><em>Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a>, <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a>, <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a>, and <a href="https://discord.gg/GtDtUAvyhW"><strong><em>Discord</em></strong></a><strong><em>.</em></strong></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9eec0c5ac15" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/a-beginners-guide-to-python-9eec0c5ac15">A Beginners’ Guide to Python</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>