<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="4.4.1">Jekyll</generator><link href="https://blog.frend.pro/feed.xml" rel="self" type="application/atom+xml" /><link href="https://blog.frend.pro/" rel="alternate" type="text/html" /><updated>2026-11-22T16:56:32+00:00</updated><id>https://blog.frend.pro/feed.xml</id><title type="html">Cale Frend</title><subtitle>The journey is half the fun</subtitle><entry><title type="html">Putting it together: SQL, Python and Web</title><link href="https://blog.frend.pro/Django/" rel="alternate" type="text/html" title="Putting it together: SQL, Python and Web" /><published>2025-04-11T11:00:00+00:00</published><updated>2025-04-11T11:00:00+00:00</updated><id>https://blog.frend.pro/Django</id><content type="html" xml:base="https://blog.frend.pro/Django/"><![CDATA[<p>We will cover a web application framework called Django, frameworks are effectively a library for a programming language that combines several other programming languages; allowing them to communicate to each other and perform complex operations, each framework will have its own syntax to learn.</p>

<p>To get the most out of this it is recommended you have read my previous posts introducing Python and SQL.
Django is used to run many big sites, such as Instagram, Spotify, Pinterest, The Washington Post, The Onion and Mozilla.</p>
<h1 id="django">Django</h1>
<p>Django combines a stack of languages such as Python, SQL, HTML and more into an application - in our use-case we will create a website that uses a simple Python loop to iterate over a dictionary extracted from our SQL database and display it dynamically on our self-hosted webpage.
It is much easier than it sounds and will only take 20-30 minutes of your time to setup.</p>
<h1 id="prerequisites">Prerequisites</h1>
<p><strong>A code editor of your choice</strong>
I highly recommend Microsoft’s Visual Studio code, its free, cross platform, has extensions to support just about any language and is very customisable.
https://code.visualstudio.com/</p>
<h1 id="installation">Installation</h1>
<p>Install <strong>Python</strong> over at <a href="https://www.python.org/downloads/">https://www.python.org/downloads/</a>
scroll down for specific instructions for your operating system</p>

<p><strong>Python / Python3 pip install</strong>
<a href="https://pip.pypa.io/en/stable/installation/">https://pip.pypa.io/en/stable/installation/</a>
Pip installs packages (PIP) usually comes with Python and is a tool used to download and install software packages for Python; you can check if it’s installed with;</p>

<figure class="highlight"><pre><code class="language-terminal" data-lang="terminal"><span class="go">\Python3 for some systems
Python -m pip --version</span></code></pre></figure>

<p><strong>Django</strong>
Django is easily installed using PIP with the command below, head to their official website for more detailed instruction at <a href="https://www.djangoproject.com/">https://www.djangoproject.com/</a></p>

<figure class="highlight"><pre><code class="language-terminal" data-lang="terminal"><span class="go">pip install django</span></code></pre></figure>

<p><img src="/images/Pasted image 20241103193818.png" alt="Select-name" /></p>

<p>Once Django is installed we can create our new project with the below syntax;</p>

<figure class="highlight"><pre><code class="language-terminal" data-lang="terminal"><span class="go">django-admin startproject sitename directoryname</span></code></pre></figure>

<p>Avoid names used by built-python or django components such as django or test.
We are going to make a very simple site to be used by a fictional medical clinic, we will place this inside a folder on our computer</p>

<p>First create the folder on your system using</p>

<figure class="highlight"><pre><code class="language-terminal" data-lang="terminal"><span class="go">mkdir djangotutorial</span></code></pre></figure>

<p>and then type</p>

<figure class="highlight"><pre><code class="language-terminal" data-lang="terminal"><span class="go">django-admin startproject mysite website</span></code></pre></figure>

<h1 id="django-hierarchy">Django Hierarchy</h1>
<p>Django will create a list of files in your directory;</p>

<p><img src="/images/Pasted image 20241114194153.png" alt="Select-name" /></p>

<p><strong>init.py</strong> is an empty file that tells python to treat this directory like a python package.</p>

<p><strong>asgi and wsgi</strong> are special configuration files  used by Django to communicate with ASGI or WSGI compatible web servers to serve your project - we will not need to deal with these files today.</p>

<p><strong>settings.py</strong> contains project settings - installs apps, plugin settings, middleware used and to modify database engines.</p>

<p><strong>urls.py</strong> This is the table of contents for our site; it contains our URL declarations used to configure routes to different Django applications.</p>

<p><strong>manage.py</strong> - special file that acts as a command line tool, allows user to make database migrations, run a python server, manage users via admin panel and more</p>

<h2 id="django-applications">Django applications</h2>
<p>A Django app is what executes code or serves a webpage.
An app could be a blog system, a database, an authentication system or a survey, Apps are standalone and plug and play.
A project can contain multiple apps, an app can be in multiple projects.</p>
<h1 id="creating-our-first-app">Creating our first app</h1>
<p>In the command line, head to your project directory (we have to be in the same directory as manage.py) and type the command;</p>

<figure class="highlight"><pre><code class="language-terminal" data-lang="terminal"><span class="go">python manage.py startapp clinic</span></code></pre></figure>

<p><strong>startapp</strong> - creates new app</p>

<p><strong>clinic</strong> - name of app</p>

<p>This creates a new directory for our app, the first step after creating our app is to link it to our project.</p>

<p>Go to settings.py in the main project directory (mysite) and scroll to installed applications and add our new app to the definitions, this will allow our Django project to view the code in the app.</p>

<p><img src="/images/Pasted image 20250407214828.png" alt="Select-name" /></p>

<p>While you’re editing settings.py, scroll further down and set the TIME_ZONE to your time zone.
Storing data and coding with UTC is good practice, this will account for daylight saving time for applicable countries; and will resolve errors when their clocks are moved forward or back.
You can display local time to the end user and still use UTC on the server side (This is best practice).</p>
<h2 id="app-hierachy">App hierachy</h2>
<p><img src="/images/Pasted image 20250407215023.png" alt="Select-name" /></p>

<p><strong><em>init</em></strong> - functions the same as in the main project, this filename tells python to treat this directory as a package.</p>

<p><strong>admin.py</strong> - Allows registration of database models so we can view them in the admin panel.</p>

<p><strong>apps.py</strong> - A place to store configuration specific to this app.</p>

<p><strong>models.py</strong> - Used to manage models, a model in Django is a table in your database.</p>

<p><strong>test.py</strong> - Used for automated test cases.</p>

<p><strong>views.py</strong> - Where we will do most of our work - creates views or routes accessible on our website.</p>

<h2 id="setting-up-our-clinic-app">Setting up our clinic app</h2>

<p>A view is a type of webpage, it usually has a specific function, this can be anything from a home page, comment action, index pages, redirect, image, error or many others.
A website using Django is full of views and each view has its own task and function.</p>

<p>Head over to views.py to set this up.</p>

<p>Import the HttpResponse function from django</p>

<p><img src="/images/Pasted image 20250407194643.png" alt="Select-name" /></p>

<p>This function takes in a request object created by Django (HttpRequest - contains query parameters and the body of requests) and then defines and returns an appropriate response - this will be in the form of our webpage.
It is up to you the writer to ensure each view instantiates, populates and returns a response.</p>

<p>Add the below code to return a string from the imported function.</p>

<p><img src="/images/Pasted image 20250407200017.png" alt="Select-name" /></p>

<p>You have now created the most basic view possible within Django but to be able to access it we need to map it to a URL.</p>

<p>Create a new file in the app; urls.py</p>

<p><img src="/images/Pasted image 20250407215521.png" alt="Select-name" /></p>

<p>Django will check this file and use it to place URL routes and connect them to our views.</p>

<p>add the following code to your clinic/urls.py file.</p>

<p><img src="/images/Pasted image 20250407201743.png" alt="Select-name" /></p>

<p><strong>from django.urls import path</strong> - needed.</p>

<p><strong>from . (current directory) import views</strong> - gives us access to functions from the views file that we just created.</p>

<p>We then create a list; urlpatterns.</p>

<p><strong>Path</strong> - this will match a URL pattern to a specific path or view.</p>

<p><strong>”“</strong> - This empty string denotes the base URL of site.</p>

<p><strong>views.index</strong> - We then call this function that we created in views.py; returning the HttpResponse and allowing us to view it.</p>

<p><strong>name=’index’</strong> - The name of the site</p>

<p>Now we need to connect the app URL to our main project - go to urls.py in our main project folder.</p>

<p>This contains all base routes for the entire project, Here we will create the URL that will link to our app.</p>

<p><img src="/images/Pasted image 20250407215636.png" alt="Select-name" /></p>

<p><strong>’‘</strong> - tells django to link the base URL to clinic.urls.</p>

<p><strong>name=’clinic’</strong> - defines a variable that we can use in other parts of our project to refer to this path.</p>

<p>Following the instructions in urls.py itself, be sure to import the include function from django.urls.</p>

<p>by including clinic.urls we pass on the handling of viewing the base URL to the URL list we created in doctors.</p>

<p>URLs by default will usually look something like website.com/projecturls/appurls.
By specifying a blank string we don’t have to go to 2 subdomains to reach our homepage.</p>

<p>We also have flexibility to have different prefixes for different applications; eg. /admin has been created by Django by default for us to use.</p>

<p>Head back to your Python terminal and run the command</p>

<figure class="highlight"><pre><code class="language-terminal" data-lang="terminal"><span class="go">python manage.py runserver</span></code></pre></figure>

<p><img src="/images/Pasted image 20250407203007.png" alt="Select-name" />
Ignore any errors for now, these will be resolved with a later step.
Navigate to the webpage and and you can now see your page in action. 
<img src="/images/Pasted image 20250407203039.png" alt="Select-name" /></p>

<p>Press Ctrl+C or Ctrl+Break/Pause in your python terminal to stop running the server.
This is good progress, but the page is bland.</p>
<h2 id="template-page---boiler-plate-navbar">Template page - boiler plate navbar</h2>
<p>Using a template is best practice for modern web design, making it easier to have a consistent style across whole website without having to copy paste code, this greatly reduces double handling and errors.</p>

<p>Re-usable HTML gives the page a fast appearance as it is stored in the clients cache and only needs to be loaded once.
Using Django we can have templates inherit from other templates - this can be powerful!</p>

<p>Create a new folder under doctors called templates and within this folder create a new html file called navbar.html.</p>

<p><img src="/images/Pasted image 20250407215840.png" alt="Select-name" /></p>

<p>For your own sanity it is best practice to store your templates in a folder within each app, creating subdirectories within the templates folder as needed. 
Storing all your templates in one folder will get messy and is not sustainable when working at scale.</p>

<p>Within a template there are blocks; these are what we will use to expand our templates in other pages.</p>

<p><img src="/images/Pasted image 20250407205405.png" alt="Select-name" /></p>

<p>blocks are overridable pieces of content, we can override this title block with other information in any page that inherits from this template.</p>

<p><img src="/images/Pasted image 20250407205501.png" alt="Select-name" /></p>

<p>copy the template below into your navbar.html file</p>

<figure class="highlight"><pre><code class="language-html" data-lang="html"> 
<span class="cp">&lt;!DOCTYPE html&gt;</span>

<span class="nt">&lt;html</span> <span class="na">lang=</span><span class="s">"en"</span><span class="nt">&gt;</span>

<span class="nt">&lt;head&gt;</span>

    <span class="c">&lt;!-- Meta tags for character set and responsive viewport --&gt;</span>

    <span class="nt">&lt;meta</span> <span class="na">charset=</span><span class="s">"UTF-8"</span><span class="nt">&gt;</span>

    <span class="nt">&lt;meta</span> <span class="na">name=</span><span class="s">"viewport"</span> <span class="na">content=</span><span class="s">"width=device-width, initial-scale=1.0"</span><span class="nt">&gt;</span>

    <span class="c">&lt;!-- Bootstrap CSS from CDN (Content Delivery Network) --&gt;</span>

    <span class="c">&lt;!-- Note: In production, it's better to download and host these files yourself --&gt;</span>

    <span class="nt">&lt;link</span> <span class="na">rel=</span><span class="s">"stylesheet"</span> <span class="na">href=</span><span class="s">"https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"</span><span class="nt">&gt;</span>
 <span class="c">&lt;!-- Title block - Django will inject content here --&gt;</span>
    <span class="nt">&lt;title&gt;</span>
     
      
      {% block Title %}

      {% endblock %}
	
    <span class="nt">&lt;/title&gt;</span>

<span class="nt">&lt;/head&gt;</span>

  

<span class="nt">&lt;body&gt;</span>

    <span class="c">&lt;!-- Navigation Bar --&gt;</span>

    <span class="nt">&lt;nav</span> <span class="na">class=</span><span class="s">"navbar navbar-expand-lg navbar-light bg-light"</span><span class="nt">&gt;</span>

        <span class="c">&lt;!-- Brand/logo link - points to home page --&gt;</span>

        <span class="nt">&lt;a</span> <span class="na">class=</span><span class="s">"navbar-brand"</span> <span class="na">href=</span><span class="s">"{% url 'index' %}"</span><span class="nt">&gt;</span>Medical Clinic<span class="nt">&lt;/a&gt;</span>

        <span class="c">&lt;!-- Hamburger menu button for mobile devices --&gt;</span>

        <span class="nt">&lt;button</span> <span class="na">class=</span><span class="s">"navbar-toggler"</span> <span class="na">type=</span><span class="s">"button"</span> <span class="na">data-toggle=</span><span class="s">"collapse"</span> <span class="na">data-target=</span><span class="s">"#navbarNav"</span>

<span class="err"> </span> <span class="err"> </span> <span class="err"> </span> <span class="err"> </span> <span class="err"> </span> <span class="err"> </span> <span class="err"> </span> <span class="err"> </span> <span class="na">aria-controls=</span><span class="s">"navbarNav"</span> <span class="na">aria-expanded=</span><span class="s">"false"</span> <span class="na">aria-label=</span><span class="s">"Toggle navigation"</span><span class="nt">&gt;</span>

            <span class="nt">&lt;span</span> <span class="na">class=</span><span class="s">"navbar-toggler-icon"</span><span class="nt">&gt;&lt;/span&gt;</span>

        <span class="nt">&lt;/button&gt;</span>

        <span class="c">&lt;!-- Navigation links - will collapse on small screens --&gt;</span>

        <span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">"collapse navbar-collapse"</span> <span class="na">id=</span><span class="s">"navbarNav"</span><span class="nt">&gt;</span>

            <span class="nt">&lt;ul</span> <span class="na">class=</span><span class="s">"navbar-nav ml-auto"</span><span class="nt">&gt;</span>  <span class="c">&lt;!-- ml-auto pushes items to the right --&gt;</span>

                <span class="nt">&lt;li</span> <span class="na">class=</span><span class="s">"nav-item"</span><span class="nt">&gt;</span>

                    <span class="c">&lt;!-- Note: Replace index href with Django URL tags when routes are defined for these pages --&gt;</span>

                    <span class="nt">&lt;a</span> <span class="na">class=</span><span class="s">"nav-link"</span> <span class="na">href=</span><span class="s">"{% url 'index' %}"</span><span class="nt">&gt;</span>Home<span class="nt">&lt;/a&gt;</span>

                <span class="nt">&lt;/li&gt;</span>

                <span class="nt">&lt;li</span> <span class="na">class=</span><span class="s">"nav-item"</span><span class="nt">&gt;</span>

                    <span class="nt">&lt;a</span> <span class="na">class=</span><span class="s">"nav-link"</span> <span class="na">href=</span><span class="s">"{% url 'index' %}"</span><span class="nt">&gt;</span>Doctors<span class="nt">&lt;/a&gt;</span>

                <span class="nt">&lt;/li&gt;</span>

                <span class="nt">&lt;li</span> <span class="na">class=</span><span class="s">"nav-item"</span><span class="nt">&gt;</span>

                    <span class="nt">&lt;a</span> <span class="na">class=</span><span class="s">"nav-link"</span> <span class="na">href=</span><span class="s">"{% url 'index' %}"</span><span class="nt">&gt;</span>Contact<span class="nt">&lt;/a&gt;</span>

                <span class="nt">&lt;/li&gt;</span>

            <span class="nt">&lt;/ul&gt;</span>

        <span class="nt">&lt;/div&gt;</span>

    <span class="nt">&lt;/nav&gt;</span>

  

    <span class="c">&lt;!-- Main content block - Django will inject content here --&gt;</span>
 
    {% block content %}

    {% endblock %}
      

    <span class="c">&lt;!-- JavaScript libraries required for Bootstrap --&gt;</span>

    <span class="c">&lt;!-- Loaded at bottom of page for better performance --&gt;</span>

    <span class="nt">&lt;script </span><span class="na">src=</span><span class="s">"https://code.jquery.com/jquery-3.5.1.slim.min.js"</span><span class="nt">&gt;&lt;/script&gt;</span>

    <span class="nt">&lt;script </span><span class="na">src=</span><span class="s">"https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.3/dist/umd/popper.min.js"</span><span class="nt">&gt;&lt;/script&gt;</span>

    <span class="nt">&lt;script </span><span class="na">src=</span><span class="s">"https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"</span><span class="nt">&gt;&lt;/script&gt;</span>

<span class="nt">&lt;/body&gt;</span>

<span class="nt">&lt;/html&gt;</span>
 </code></pre></figure>

<p>Create a new folder in your templates folder called clinic and then create a home.html file</p>

<p><img src="/images/Pasted image 20250407220302.png" alt="Select-name" /></p>

<p>and type the following code;</p>

<p><img src="/images/Pasted image 20250410141316.png" alt="Select-name" /></p>

<p>Keep in mind Django will choose the first template whose name it finds matches, if you have a template with the same name but in a different application, Django will be unable to distinguish them.</p>

<p>This makes it very important to use sub-folders when creating new templates such as clinic/home.html.</p>

<p>Head to views in our app and change the below code to render our new home.html webpage instead of returning a string response.</p>

<p><img src="/images/Pasted image 20250407220545.png" alt="Select-name" /></p>

<p>In your python terminal run the server once more using
python manage.py runserver (ignoring errors once again); head to the default URL and you will now see a slightly fancier homepage displayed.</p>

<p><img src="/images/Pasted image 20250407220719.png" alt="Select-name" /></p>
<h1 id="setting-up-our-database">Setting up our database</h1>

<p>Head to models.py; here we will create our database model for use.
Django provides us with a object relational mapping (ORM) allowing us to write python code to create different database models and have those models conform to database schema such as SQL.</p>

<p>Add the below to your Models.py file.</p>

<p><img src="/images/Pasted image 20250411205403.png" alt="Select-name" /></p>

<p>We have created a Doctor which is a model, this model has 3 different fields written as Python attributes, these are set as characters with a limit set out as per the max_length attribute.</p>

<p>We need to register this model through the admin panel then convert the model to a database.</p>

<p>Head over to admin.py; by referencing the model here and registering to the admin panel we can view and edit via said panel.</p>

<p><img src="/images/Pasted image 20250411205441.png" alt="Select-name" /></p>

<p>As we create models we will need do what is called a migration - this is pre-written code that will go and create the corresponding code in a language (such as SQL or MongoDB) effectively converting it into a database for our use.</p>

<p>Any time you make a change to your database model you need to make a migration, this allows Django to update your database while ensuring the data itself is not compromised while making changes to the schema.
Do this by typing</p>

<figure class="highlight"><pre><code class="language-terminal" data-lang="terminal"><span class="go">python manage.py makemigrations </span></code></pre></figure>

<p>into your terminal, and then apply the migration by typing</p>

<figure class="highlight"><pre><code class="language-terminal" data-lang="terminal"><span class="go">python manage.py migrate</span></code></pre></figure>

<p>this applies the migration and updates the database for you.</p>

<p><strong>To summarize you need to make your migration and then apply it</strong> - do this every time you make a change to your database!</p>

<p>Migrations let you change your models over time as you develop your project, without  needing to delete your database or tables and make new ones - You can upgrade and change your database live without losing data!</p>

<h3 id="viewing-our-database">Viewing our database</h3>
<p>Create a new html template in your templates folder to display your data.
<img src="/images/Pasted image 20250411204251.png" alt="Select-name" /></p>

<figure class="highlight"><pre><code class="language-html" data-lang="html"> 
     
{% extends "navbar.html" %}

  

{% block Title %}

    Doctors

{% endblock %}

  

{% block content %}

    <span class="nt">&lt;h1&gt;</span>Our Doctors<span class="nt">&lt;/h1&gt;</span>

{% for x in Doctors %}

    <span class="nt">&lt;h2&gt;</span> {{ x.name }}<span class="nt">&lt;/h2&gt;</span>

    <span class="nt">&lt;p&gt;&lt;b&gt;</span> {{ x.qualification }} <span class="nt">&lt;/b&gt;&lt;/p&gt;</span>

    <span class="nt">&lt;p&gt;</span>{{ x.aboutme }}<span class="nt">&lt;/p&gt;</span>

{% endfor %}

{% endblock %}
 
    </code></pre></figure>

<p>We have a loop; for each doctor in our database (Doctors) we use it to render different text items via HTML for each entry; this is a variable we can pass into this template.</p>

<p>We can use dot notation to access an attribute of this variable (doctor.name) which is treated as a python dictionary.
Variables in django are defined with double curly braces {{ variable.attribute }}</p>

<p>In our views.py add</p>

<figure class="highlight"><pre><code class="language-html" data-lang="html">from .models import Doctor</code></pre></figure>

<p>to reference the database.</p>

<p>Then we will add a reference to doctors.html by</p>

<p><img src="/images/Pasted image 20250411215533.png" alt="Select-name" /></p>

<p>We declare items in the function as a variable that we can pass to the request; it is set it equal to our database.
we return that variable as {“Doctors”: data}.</p>

<p>Our earlier created html template now has access to this database.</p>

<p>So that we can access this webpage we need to add a new path to urls.py</p>

<p><img src="/images/Pasted image 20250411215620.png" alt="Select-name" /></p>

<p>Head into your navbar.html template and amend the highlighted code now that we have a URL for our doctors page;</p>

<p><img src="/images/Pasted image 20250411220201.png" alt="Select-name" /></p>

<p>You can now view this via your web browser; you will notice there is no data to show, we will now create some data via the admin panel.</p>
<h1 id="admin-panel">Admin panel</h1>
<p>In terminal type</p>

<figure class="highlight"><pre><code class="language-terminal" data-lang="terminal"><span class="go">python manage.py createsuperuser</span></code></pre></figure>

<p>follow the prompts, you can skip email.
After creating a super user run the server and head to /admin on your webserver.</p>

<p>login with the credentials you just created; you will see your database models, click add and create some data!
<img src="/images/Pasted image 20250411220341.png" alt="Select-name" />
head back to /doctors and you will see the items are now rendered. these are now present in your SQL database which is running on your PC and has persistence.</p>

<p>In a real world scenario you can add user accounts for staff or clients so that they can perform CRUD actions on your SQL database, such as a medical clinic practice manager entering in the details of a new doctor.</p>

<p>This has just been the very basics to give you a simple understanding of how some websites work!</p>

<p>Check out the below for more guided tutorials that go into more detail!</p>

<ul>
  <li><em>Django Official Documentation - writing your first app  <a href="https://docs.djangoproject.com/en/5.1/intro/tutorial01/">https://docs.djangoproject.com/en/5.1/intro/tutorial01/</a></em></li>
  <li><em>W3 schools - <a href="https://www.w3schools.com/django/index.php">https://www.w3schools.com/django/index.php</a></em></li>
</ul>]]></content><author><name></name></author><summary type="html"><![CDATA[We will cover a web application framework called Django, frameworks are effectively a library for a programming language that combines several other programming languages; allowing them to communicate to each other and perform complex operations, each framework will have its own syntax to learn.]]></summary></entry><entry><title type="html">Introduction to Python</title><link href="https://blog.frend.pro/Intro-Python/" rel="alternate" type="text/html" title="Introduction to Python" /><published>2024-10-20T06:00:00+00:00</published><updated>2024-10-20T06:00:00+00:00</updated><id>https://blog.frend.pro/Intro-Python</id><content type="html" xml:base="https://blog.frend.pro/Intro-Python/"><![CDATA[<h2 id="what-is-python">What is Python?</h2>
<p>Python is a simple, widely-used programming language that doesn’t require compilation. It’s executed directly by an interpreter, making it easy to learn and use. Python has extensive documentation and a large community for support.</p>

<p>Before reading I recommend having basic programming language knowledge.</p>

<p>Compared to low level languages, Python is simpler and easier to write code in.</p>

<p>The trade-off is because things like memory management are handled for you, there is a cost under the hood - this may impact performance depending on code as this code is still run when you call built-in functions.
Although in the modern age this is rarely a consideration unless programming with very limited hardware.</p>

<p><a href="https://docs.python.org/3/library/functions.html">Python documentation</a></p>

<h2 id="variables">Variables</h2>

<p>You do not need to declare the type of variable, Python can infer this for you.
While each variable does have a type, we do not need to explicitly state which type it is when we create the variable.</p>

<figure class="highlight"><pre><code class="language-python" data-lang="python"><span class="nb">int</span> <span class="n">counter</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
<span class="c1">#becomes
</span><span class="n">counter</span> <span class="o">=</span> <span class="mi">0</span></code></pre></figure>

<p><strong>Common variable types</strong></p>

<p><strong>bool</strong> - A value that is either true of false
<strong>float</strong> - a decimal number
<strong>int</strong> - an integer
<strong>str</strong> - a string.</p>

<p>Long and double are automatically handled via int - Python knows what data type should be used for larger and smaller numbers.</p>

<p><strong>Python collections (Arrays)</strong></p>

<p><strong>list</strong> - Ordered, changeable and allow for duplicate values.
created with square brackets
Stores any variable type, elements can be referenced by index [0] starting from 0.</p>

<figure class="highlight"><pre><code class="language-python" data-lang="python"><span class="nb">list</span> <span class="o">=</span> <span class="p">[</span><span class="sh">"</span><span class="s">cale</span><span class="sh">"</span><span class="p">,</span> <span class="sh">"</span><span class="s">user</span><span class="sh">"</span><span class="p">,</span> <span class="sh">"</span><span class="s">admin</span><span class="sh">"</span><span class="p">]</span></code></pre></figure>

<p><strong>tuple</strong> - An ordered and unchangeable collection of data, allows for duplicate values.
Usually used to store just 2 or 3 values together, such as co-ordinates.
Created with round brackets.</p>

<figure class="highlight"><pre><code class="language-python" data-lang="python"><span class="nb">tuple</span> <span class="o">=</span> <span class="p">(</span><span class="mf">12.3</span><span class="p">,</span> <span class="mf">10.7</span><span class="p">)</span></code></pre></figure>

<p><strong>set</strong> - unordered, unindexed and unchangeable.
Stores each value only once.
Created with curly brackets</p>

<figure class="highlight"><pre><code class="language-python" data-lang="python"><span class="nb">set</span> <span class="o">=</span> <span class="p">{</span><span class="sh">"</span><span class="s">user</span><span class="sh">"</span><span class="p">,</span> <span class="sh">"</span><span class="s">admin</span><span class="sh">"</span><span class="p">}</span></code></pre></figure>

<p><strong>dict</strong> - Ordered and changeable, no duplicates.
Can be used to store data in key:value pairs.
written with curly brackets;</p>

<figure class="highlight"><pre><code class="language-python" data-lang="python"><span class="nb">dict</span> <span class="o">=</span> <span class="p">{</span>
<span class="sh">"</span><span class="s">username</span><span class="sh">"</span><span class="p">:</span> <span class="sh">"</span><span class="s">admin</span><span class="sh">"</span>
<span class="sh">"</span><span class="s">password</span><span class="sh">"</span><span class="p">:</span> <span class="sh">"</span><span class="s">123456</span><span class="sh">"</span>
<span class="sh">"</span><span class="s">created</span><span class="sh">"</span><span class="p">:</span> <span class="sh">"</span><span class="s">20241013</span><span class="sh">"</span>
<span class="p">}</span></code></pre></figure>

<p>Dictionaries cannot have two items with the same key; duplicate values will overwrite existing values.
Dictionariy values can be of any data type, including array data types.</p>

<figure class="highlight"><pre><code class="language-python" data-lang="python"><span class="nb">dict</span> <span class="o">=</span> <span class="p">{</span>
<span class="sh">"</span><span class="s">username</span><span class="sh">"</span> <span class="p">:</span> <span class="sh">"</span><span class="s">admin</span><span class="sh">"</span>
<span class="sh">"</span><span class="s">device_id</span><span class="sh">"</span> <span class="p">:</span> <span class="p">[</span><span class="sh">"</span><span class="s">pc_1</span><span class="sh">"</span><span class="p">,</span> <span class="sh">"</span><span class="s">mobile_phone</span><span class="sh">"</span><span class="p">,</span> <span class="sh">"</span><span class="s">laptop_3</span><span class="sh">"</span><span class="p">]</span> 
<span class="p">}</span></code></pre></figure>

<h2 id="comments">Comments</h2>

<p># (hashtag) - starts a line that contains a Python comment</p>

<figure class="highlight"><pre><code class="language-python" data-lang="python"><span class="c1">#prints approved usernames</span></code></pre></figure>

<p>Contains a comment that indicates that the purpose of the code that follows it is to print approved usernames.</p>

<p>””” (documentation strings)
starts and ends a multi line string that is used as a Python comment; multi line comments are used when you need more than the 79 character single line comment.</p>

<figure class="highlight"><pre><code class="language-python" data-lang="python"><span class="sh">"""</span><span class="s">
This program is designed to ask the user for input on a user name.
It then checks the approved_users data base to see if the entered name is present, 
If the name is found it returns a print statement declaring the user is valid, 
otherwise it will return an error message indicating the user has not been found in the approved list.
</span><span class="sh">"""</span></code></pre></figure>

<p>A multi line function that indicates the purpose of the program.</p>
<h2 id="conditional-statements">Conditional statements</h2>

<p><strong>if</strong> - starts a conditional statement</p>

<figure class="highlight"><pre><code class="language-python" data-lang="python"><span class="k">if</span> <span class="n">device_id</span> <span class="o">!=</span> <span class="sh">"</span><span class="s">fg314jh</span><span class="sh">"</span><span class="p">:</span></code></pre></figure>

<p>Starts a conditional statement that evaluates whether the device_id variable contains a value that is not equal to “fg314jh”.</p>

<figure class="highlight"><pre><code class="language-python" data-lang="python"><span class="k">if</span> <span class="n">user</span> <span class="ow">in</span> <span class="n">approved_users</span><span class="p">:</span></code></pre></figure>

<p>starts a conditional statement that evaluates if the user variable contains a value that is also found in the approved_users variable.</p>

<p><strong>elif</strong> - Only evaluated when previous conditions evaluate to false.</p>

<figure class="highlight"><pre><code class="language-python" data-lang="python"><span class="k">elif</span> <span class="n">status</span> <span class="o">==</span> <span class="mi">500</span><span class="p">:</span></code></pre></figure>

<p>when previous conditions return false, evaluates if the status variable contains a value equal to 500.</p>

<p><strong>else</strong> - If all conditions before it return false, this condition is used instead.</p>

<figure class="highlight"><pre><code class="language-python" data-lang="python"><span class="k">else</span><span class="p">:</span></code></pre></figure>

<p>when all previous conditions evaluate to false, Python executes the code within this else statement.</p>

<p><strong>and</strong> - requires both conditions on either side of the operator to evaluate to true.</p>

<figure class="highlight"><pre><code class="language-python" data-lang="python"><span class="k">if</span> <span class="n">username</span> <span class="o">==</span> <span class="sh">"</span><span class="s">cale</span><span class="sh">"</span> <span class="ow">and</span> <span class="n">login</span> <span class="n">attempts</span> <span class="o">&lt;</span> <span class="mi">5</span><span class="p">:</span></code></pre></figure>

<p>Returns true if the value in username is equal to “cale” and the value of login attempts is less than 5.</p>

<p><strong>or</strong> - requires only one of the conditions on either side of the operator to be true.</p>

<figure class="highlight"><pre><code class="language-python" data-lang="python"><span class="k">if</span> <span class="n">status</span> <span class="o">==</span> <span class="mi">100</span> <span class="ow">or</span> <span class="n">status</span> <span class="o">==</span> <span class="mi">102</span><span class="p">:</span></code></pre></figure>

<p>Returns true and executes indented code if the value in status variable is equal to 100 or 102.</p>

<p><strong>not</strong> - negates a condition so that it evaluates to false if the condition is true or vice-versa.</p>

<figure class="highlight"><pre><code class="language-python" data-lang="python"><span class="k">if</span> <span class="ow">not</span> <span class="n">account_status</span> <span class="o">==</span> <span class="sh">"</span><span class="s">removed</span><span class="sh">"</span></code></pre></figure>

<p>returns false if the value in account status is equal to “removed” and returns true if the value is not equal to removed.</p>
<h2 id="iterative-statements-loops">Iterative statements (Loops)</h2>

<p>There are no do-while loops in Python, while loop is convention.</p>

<p><strong>While</strong> - used to iterate based on a condition</p>

<figure class="highlight"><pre><code class="language-python" data-lang="python"><span class="k">while</span> <span class="n">login_attempts</span> <span class="o">&lt;</span> <span class="mi">5</span><span class="p">:</span></code></pre></figure>

<p>iterates as long as the condition that the value of login_attempts is less than 5 returns True.</p>

<p><strong>For</strong> - Used to iterate through a specified sequence.</p>

<figure class="highlight"><pre><code class="language-python" data-lang="python"><span class="k">for</span> <span class="n">username</span> <span class="ow">in</span> <span class="p">[</span><span class="sh">"</span><span class="s">cale</span><span class="sh">"</span><span class="p">,</span> <span class="sh">"</span><span class="s">admin</span><span class="sh">"</span><span class="p">,</span> <span class="sh">"</span><span class="s">user</span><span class="sh">"</span><span class="p">]:</span></code></pre></figure>

<p>iterates throught the lements in the list, using the loop variable username.</p>

<figure class="highlight"><pre><code class="language-python" data-lang="python"><span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nf">range</span><span class="p">(</span><span class="mi">10</span><span class="p">):</span></code></pre></figure>

<p>iterates through each number created by range(10) using the loop variable i.</p>

<p><strong>Break</strong> - used to break out of a loop.</p>

<p><strong>Continue</strong> - Skip a loop iteration and continue with the next one.</p>
<h2 id="user-defined-functions">User-defined functions</h2>

<p><strong>def</strong> - placed before a function name to define a function</p>

<figure class="highlight"><pre><code class="language-python" data-lang="python"><span class="k">def</span> <span class="nf">main</span><span class="p">():</span>
	<span class="nf">bark</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span>
<span class="c1">#bark some number of times
</span><span class="k">def</span> <span class="nf">bark</span><span class="p">(</span><span class="n">n</span><span class="p">):</span>
	<span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nf">range</span><span class="p">(</span><span class="n">n</span><span class="p">):</span>
		<span class="nf">print</span><span class="p">(</span><span class="sh">"</span><span class="s">bark</span><span class="sh">"</span><span class="p">)</span>
<span class="nf">main</span><span class="p">()</span></code></pre></figure>

<p>A function abstracts away the barking.
A main function is defined at the top of the file, at the bottom the main function is called.
It is convention to create a main function in Python, but not necessary.</p>

<p><strong>return</strong> - used to return information from a function, when executed, Python exits the function after returning the information</p>

<figure class="highlight"><pre><code class="language-python" data-lang="python"><span class="k">def</span> <span class="nf">calculate</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">):</span>
	<span class="n">total</span> <span class="o">=</span> <span class="n">x</span> <span class="o">+</span> <span class="n">y</span>
<span class="k">return</span> <span class="n">total</span></code></pre></figure>

<p>returns the value of the total variable from the calculate function.</p>
<h2 id="built-in-functions">Built-in functions</h2>

<p>Python is object orientated, properties, attributes and functions are known as objects.
Functions in python can belong to a specific object, this is known as a method.
For example, strings can have built-in methods;</p>

<figure class="highlight"><pre><code class="language-python" data-lang="python"><span class="n">s</span> <span class="o">=</span> <span class="n">washington</span><span class="p">.</span><span class="nf">upper</span><span class="p">()</span>
<span class="nf">print</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
<span class="c1">#returns WASHINGTON</span></code></pre></figure>

<p>the value of s is overwritten with the result of .lower(), a built in method of strings.</p>

<p>Lots of useful functions and methods are already built-in Python and ready to use.
Below are some commonly used functions, more can be found in the documentation.</p>

<p><strong>print()</strong> - outputs a specified object to the screen</p>

<p><strong>(f””) (formatted strings)</strong> - by adding f before the quotation mark we indicate we are using a formatted string, this allows embedded expressions using {} (curly braces)</p>

<figure class="highlight"><pre><code class="language-python" data-lang="python"><span class="nf">print</span><span class="p">(</span><span class="sa">f</span><span class="sh">"</span><span class="s">Username is </span><span class="si">{</span><span class="nb">input</span><span class="p">(</span><span class="sh">"</span><span class="s">User</span><span class="si">:</span> <span class="sh">"</span><span class="s">)</span><span class="si">}</span><span class="sh">"</span><span class="p">)</span></code></pre></figure>

<p><strong>type()</strong> - returns the data type of its input</p>

<p><strong>range()</strong> - generates a sequence of numbers</p>

<p><strong>max()</strong> - returns the largest numeric input passed into it.</p>

<p><strong>min()</strong> - returns the smallest numeric input passed into it.</p>

<p><strong>sorted()</strong> - sorts the components of a iterable.</p>

<p><strong>str()</strong> - converts the input object into a string</p>

<p><strong>len()</strong> - returns the number of elements in an object.</p>

<p>Average of three numbers using a list;</p>

<figure class="highlight"><pre><code class="language-python" data-lang="python">\<span class="c1"># logins per day
</span><span class="n">logins</span> <span class="o">=</span> <span class="p">[</span><span class="mi">6</span><span class="p">,</span> <span class="mi">7</span><span class="p">,</span> <span class="mi">7</span><span class="p">]</span>
\<span class="c1"># print the average
</span><span class="n">average</span> <span class="o">=</span> <span class="nf">sum</span><span class="p">(</span><span class="n">logins</span><span class="p">)</span> <span class="o">/</span> <span class="nf">len</span><span class="p">(</span><span class="n">logins</span><span class="p">)</span>
<span class="nf">print</span><span class="p">(</span><span class="sa">f</span><span class="sh">"</span><span class="s">Average: </span><span class="si">{</span><span class="n">average</span><span class="si">}</span><span class="sh">"</span><span class="p">)</span></code></pre></figure>

<p>The built in sum and len methods make this program simple.</p>

<h2 id="importing-modules-and-libraries">Importing modules and libraries</h2>

<p>As projects becomes larger, it will become useful to write functions in one file and run them in another.
We can create one file called functions.py with the below</p>

<figure class="highlight"><pre><code class="language-python" data-lang="python"><span class="k">def</span> <span class="nf">square</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
	<span class="k">return</span> <span class="n">x</span> <span class="o">*</span> <span class="n">x</span></code></pre></figure>

<p>and another file called square.py with the code</p>

<p><strong>import</strong> - searches for a module or library in a system and adds it to the local python environment.</p>

<figure class="highlight"><pre><code class="language-python" data-lang="python"><span class="kn">from</span> <span class="n">functions</span> <span class="kn">import</span> <span class="n">square</span>
<span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nf">range</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span>
	<span class="nf">print</span><span class="p">(</span><span class="sa">f</span><span class="sh">"</span><span class="s">the square of </span><span class="si">{</span><span class="n">i</span><span class="si">}</span><span class="s"> is </span><span class="si">{</span><span class="nf">square</span><span class="p">(</span><span class="n">i</span><span class="p">)</span><span class="si">}</span><span class="sh">"</span><span class="p">)</span></code></pre></figure>

<p>we could alternatively import the entire functions module and use dot notation to access the square function</p>

<figure class="highlight"><pre><code class="language-python" data-lang="python"><span class="kn">import</span> <span class="n">functions</span>
<span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nf">range</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span>
	<span class="nf">print</span><span class="p">(</span><span class="sa">f</span><span class="sh">"</span><span class="s">the square of </span><span class="si">{</span><span class="n">i</span><span class="si">}</span><span class="s"> is </span><span class="si">{</span><span class="n">functions</span><span class="p">.</span><span class="nf">square</span><span class="p">(</span><span class="n">i</span><span class="p">)</span><span class="si">}</span><span class="sh">"</span><span class="p">)</span></code></pre></figure>

<p>Many in-built libraries such as math or csv are available, additionally Python has many community libraries allowing for lots of complex functionality to be abstracted away from you as you work off the shoulders of those before you.</p>

<p>The sys library has built in methods that are very useful in the command line.
You can print all command line arguments using the below;</p>

<figure class="highlight"><pre><code class="language-python" data-lang="python"><span class="kn">from</span> <span class="n">sys</span> <span class="kn">import</span> <span class="n">argv</span>

<span class="k">for</span> <span class="n">arg</span> <span class="ow">in</span> <span class="n">argv</span><span class="p">:</span>
	<span class="nf">print</span><span class="p">(</span><span class="n">arg</span><span class="p">)</span></code></pre></figure>

<p>The first argument is the name that of the file that you are running.</p>

<figure class="highlight"><pre><code class="language-python" data-lang="python"><span class="kn">from</span> <span class="n">sys</span> <span class="kn">import</span> <span class="n">argv</span>

<span class="k">if</span> <span class="nf">len</span><span class="p">(</span><span class="n">argv</span><span class="p">)</span> <span class="o">==</span> <span class="mi">2</span><span class="p">:</span>
	<span class="nf">print</span><span class="p">(</span><span class="sa">f</span><span class="sh">"</span><span class="s">hello, </span><span class="si">{</span><span class="n">argv</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span><span class="si">}</span><span class="sh">"</span><span class="p">)</span>
<span class="k">else</span><span class="p">:</span>
	<span class="nf">print</span><span class="p">(</span><span class="sh">"</span><span class="s">hello</span><span class="sh">"</span><span class="p">)</span></code></pre></figure>

<p>Print hello to the first user argument (second arg value) if it exists.</p>

<p><strong>sys.exit()</strong> - exits the program with specified exit code.</p>

<figure class="highlight"><pre><code class="language-python" data-lang="python"><span class="kn">import</span> <span class="n">sys</span>

<span class="k">if</span> <span class="nb">len</span> <span class="n">sys</span><span class="p">.</span><span class="n">argv</span> <span class="o">!=</span> <span class="mi">2</span><span class="p">:</span>
	<span class="nf">print </span><span class="p">(</span><span class="sh">"</span><span class="s">missing command-line argument</span><span class="sh">"</span><span class="p">)</span>
	<span class="n">sys</span><span class="p">.</span><span class="nf">exit</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="nf">print</span><span class="p">(</span><span class="sa">f</span><span class="sh">"</span><span class="s">hello, </span><span class="si">{</span><span class="n">sys</span><span class="p">.</span><span class="n">argv</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span><span class="si">}</span><span class="sh">"</span><span class="p">)</span>
<span class="n">sys</span><span class="p">.</span><span class="nf">exit</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span></code></pre></figure>

<p>Notice that methods (dot notation) are used to utilize the built in functions of sys.</p>

<h2 id="file-operations">File operations</h2>

<p><strong>open()</strong> - returns a file object.
open() takes 2 parameters, filename and mode.
there are 4 modes;</p>

<p><strong>“r”</strong> - read - returns error if file does not exist</p>

<p><strong>“a”</strong> - append - creates file if it does not exist</p>

<p><strong>“w”</strong> - write - creates file if it does not exist</p>

<p><strong>“x”</strong> - create - returns error if the file exists</p>

<p>files can be read as binary “b” or text “t”.</p>

<p>default value for mode is “rt” (read, text), you do not need to specify this.</p>

<figure class="highlight"><pre><code class="language-python" data-lang="python"><span class="nb">file</span> <span class="o">=</span> <span class="nf">open</span><span class="p">(</span><span class="sh">"</span><span class="s">accesslog.txt</span><span class="sh">"</span><span class="p">,</span>  <span class="sh">"</span><span class="s">r</span><span class="sh">"</span><span class="p">)</span></code></pre></figure>

<p>If the file is located in a different location than the python program, you will have to specify the full pathname.</p>

<p><strong>.read()</strong> - returns the file content</p>

<p><strong>.write()</strong> - writes the specified string to the file</p>

<p><strong>.close()</strong> - closes the file when you are finished with it, this is best practice when you are done with the file.</p>

<p>Another way to handle the opening and closing of a file is to encase it inside a with condition;</p>

<figure class="highlight"><pre><code class="language-python" data-lang="python"><span class="k">with</span> <span class="nf">open</span><span class="p">(</span><span class="sh">'</span><span class="s">access_log.txt</span><span class="sh">'</span><span class="p">)</span> <span class="k">as</span> <span class="n">logs</span><span class="p">:</span>
	<span class="k">if</span> <span class="n">banned_user</span> <span class="ow">in</span> <span class="n">logs</span><span class="p">:</span>
		<span class="c1"># further processing goes here</span></code></pre></figure>

<p>The with statement handles closing of the file once it leaves the with block, even if there is an error.
This allows for cleaner code and makes handling of unexpected errors easier.</p>
<h2 id="regular-expressions">Regular expressions</h2>

<p>Regular expressions (RegEx for short) are a means to ensure that user-provided data fits a specific format.
Python has a build in library called re which can be used to work with regular expressions.</p>

<p><strong>import re</strong> - Uses expression symbols to find patterns in strings.</p>

<p><strong>re.findall()</strong> - returns a list containing all matches</p>

<p><strong>re.fullmatch</strong>(pattern, string, flags) - returns object only if the whole string matches the pattern, else returns none.</p>

<p><strong>re.compile()</strong> - compiles a pattern into a regex object; useful for effeciency when pattern matching more than once.</p>

<p><strong>Metacharacters, special sequences and sets</strong> - A special sequence is a \ followed by a character, a set is a set of characters inside a pair of brackets []. Special sequences, Metacharacters and sets all have a special meaning.</p>

<h3 id="case-study-valid-email">Case study: Valid email</h3>
<p>When taking an input from a user we may want to validate an email address for a variety of reasons; this could be done simply with;</p>

<p>(username)@(domain name).(at least 2 letters - top level domain name)</p>

<p>The above can be represented as a regex in Python with the below;</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
</code></pre></div></div>
<p>This is very cryptic, some syntax is explained below;</p>

<p><strong>r</strong> - used to prefix a regex string where you want to ignore \ (backslash) normally used in python; this is to prevent you having to write \\\\ (four backlashes) to match a single backslash since the regex version is \\ but each backslash must be escaped with another backslash per Python’s usage of the escape character.</p>

<p><strong>^</strong> - starts with</p>

<p><strong>[A-Z]</strong> - returns a match for any upper-case character alphabetically</p>

<p><strong>[a-z0-3]</strong> - returns a match for any lower-case character alphabetically and numbers 0-3</p>

<p><strong>.</strong> - is a wildcard for any character except newline</p>

<p><strong>+</strong> - returns one or more occurrences</p>

<p><strong>{}</strong> - returns the exact specified number of occurrences</p>

<p><strong>$</strong> - ends with</p>

<p><em>Most use-cases for regexes have already been solved by those before you, search engines and AI are your friends here.</em></p>

<p>Let’s use the above and create a simple function to check if a email is valid or not;</p>

<figure class="highlight"><pre><code class="language-python" data-lang="python"><span class="kn">import</span> <span class="n">re</span>
<span class="n">regex</span> <span class="o">=</span> <span class="n">re</span><span class="p">.</span><span class="nf">compile</span><span class="p">(</span><span class="sa">r</span><span class="sh">'</span><span class="s">^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$</span><span class="sh">'</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">checkemail</span><span class="p">(</span><span class="n">email</span><span class="p">):</span>
    <span class="k">if</span> <span class="n">re</span><span class="p">.</span><span class="nf">fullmatch</span><span class="p">(</span><span class="n">regex</span><span class="p">,</span> <span class="n">email</span><span class="p">):</span>
      <span class="nf">print</span><span class="p">(</span><span class="sh">"</span><span class="s">Valid email</span><span class="sh">"</span><span class="p">)</span>
    <span class="k">else</span><span class="p">:</span>
      <span class="nf">print</span><span class="p">(</span><span class="sh">"</span><span class="s">Invalid email</span><span class="sh">"</span><span class="p">)</span></code></pre></figure>

<p>The proposed so far while cryptic is in fact very simple, to mitigate security risks and handle a wider range of valid email addresses it is best to adhere to RFC 5322</p>

<p><strong>RFC5322</strong> - the document that specifies the internet message format (IMF), a syntax for text messages that are sent via E-mail.</p>

<p>This document contains the definition of what an email should look like; when conforming to this definition you will have a regex like below;</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(?:[a-z0-9!#$%&amp;'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&amp;'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9]))\.){3}(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])
</code></pre></div></div>
<p>This RFC5322 compliant regex expression is more clearly readable as a diagram</p>

<p><img src="https://emailregex.com/wp-content/uploads/sites/2/2014/06/General-Email-Regex-Railroad-Diagram-emailregex.com_.png" alt="RFC5322-compliant-regex" /></p>
<h6 id="taken-from-httpsemailregexcomwp-contentuploadssites2201406general-email-regex-railroad-diagram-emailregexcom_png">Taken from <a href="https://emailregex.com/wp-content/uploads/sites/2/2014/06/General-Email-Regex-Railroad-Diagram-emailregex.com_.png">https://emailregex.com/wp-content/uploads/sites/2/2014/06/General-Email-Regex-Railroad-Diagram-emailregex.com_.png</a>.</h6>

<p>While an improvement, this is not foolproof. Email addresses can be complex and subject to various rules and standards, best practice is to consider additional factors such as MX record checks, server-side validation and DNS validation to ensure accuracy and security.</p>

<p>Regex has many more use-cases, consider passwords - you can create rules such as minimum length, mix of uppercase and lowercase letters.</p>

<p>This is far more efficient than creating a series of if-else statements or custom functions.
regex functions such as search() and split() can help determine what specific improvements a user needs to make, such as “Password not long enough”.</p>

<p>Always remember to think of the end-user, avoid overly restrictive rules that impede their experience.</p>
<h2 id="further-reading">Further reading</h2>
<p>More information and discussion about <a href="https://emailregex.com">Email regex</a>.</p>

<p>Python has lots to offer, far more than can be covered here, consider free resources such as;</p>

<ul>
  <li><em>Harvard University’s introduction to programming - <a href="https://cs50.harvard.edu/x/">https://cs50.harvard.edu/x/</a></em></li>
  <li><em>W3 schools -<a href="www.w3schools.com/python">www.w3schools.com/python</a></em></li>
  <li><em>Python documentation - <a href="https://docs.python.org">https://docs.python.org</a></em></li>
</ul>

<p>Need some direction? try learning about the below as a next step;</p>

<ul>
  <li><em>Classes</em></li>
  <li><em>Lambda functions</em></li>
  <li><em>Decorators</em></li>
  <li><em>String methods</em></li>
  <li><em>List, set, tuple and dict methods.</em></li>
</ul>]]></content><author><name></name></author><summary type="html"><![CDATA[What is Python? Python is a simple, widely-used programming language that doesn’t require compilation. It’s executed directly by an interpreter, making it easy to learn and use. Python has extensive documentation and a large community for support.]]></summary></entry><entry><title type="html">Introduction to SQL</title><link href="https://blog.frend.pro/Intro-SQL/" rel="alternate" type="text/html" title="Introduction to SQL" /><published>2024-10-13T06:00:00+00:00</published><updated>2024-10-13T06:00:00+00:00</updated><id>https://blog.frend.pro/Intro-SQL</id><content type="html" xml:base="https://blog.frend.pro/Intro-SQL/"><![CDATA[<h3 id="flat-file-databases">Flat File Databases</h3>
<p>You may be familiar with a flat-file database; it is usually represented by patterns of columns and rows.
A spreadsheet such as those created in <em>Microsoft excel</em> or <em>Google sheets</em> can be considered a flat-file database.</p>

<h3 id="relational-databases">Relational Databases</h3>

<p>Big companies such as Google, Meta, Amazon all use relational databases to store their information at scale.
Relational databases store data in columns and rows in structures called tables.</p>

<p>Relational databases reference each other through the use of primary keys and foreign keys.</p>

<p>A primary key is always a unique value; such as a unique ID for each person, using a primary key ensures no two people have the same ID.</p>

<p>A foreign key is a reference to another table; if you have a table of user_logins and users, the user_id in the user_logins table would be a foreign key, referencing the primary key (unique ID) in the users table.
This connects the login attempts to the specific user who attempted it.</p>

<p>Primary keys are most commonly stored as an integer, this is for performance, numeric comparisons are faster than string comparisons, faster to index, smaller in size and easy to auto-increment, all of this becomes especially important when working with data at scale.</p>

<p><strong>Structured query language (SQL)</strong> is a standard language for accessing and manipulating databases, this can be done with 4 types of operations;</p>
<ul>
  <li>Create</li>
  <li>Read</li>
  <li>Update</li>
  <li>Delete</li>
</ul>

<p>(CRUD)</p>

<p>For the rest of this post, I will be demonstrating commands via sqlite3, a lightweight version of SQL that can be run from the command line.</p>

<h2 id="creating-your-database">Creating your database</h2>

<p><strong>Filename.db (Creating a database)</strong> - creates a .db database file on the filesystem.</p>

<figure class="highlight"><pre><code class="language-sql" data-lang="sql"><span class="k">database</span><span class="p">.</span><span class="n">db</span></code></pre></figure>

<p>After confirming with the user, will create a database named database.db.</p>

<p><strong>.mode</strong> - changes the output mode for the command line, also determines how data being imported by .import is interpreted.</p>

<figure class="highlight"><pre><code class="language-sql" data-lang="sql"><span class="p">.</span><span class="k">mode</span> <span class="n">csv</span></code></pre></figure>

<p>Changes the output of sqlite3 to match that of a .csv file
If using .import, sqlite3 will expect imported data to be CSV format and will parse accordingly.</p>

<figure class="highlight"><pre><code class="language-sql" data-lang="sql"><span class="p">.</span><span class="k">mode</span> <span class="o">?</span></code></pre></figure>

<p>Displays the current output mode.</p>

<p><strong>.import</strong> - imports a file or database.</p>

<figure class="highlight"><pre><code class="language-sql" data-lang="sql"><span class="p">.</span><span class="n">import</span> <span class="n">file</span><span class="p">.</span><span class="n">csv</span></code></pre></figure>

<p>While set to .mode csv, will correctly import a csv file into the database.db.
If .mode is set to sqlite3, sqlite3 shell compatible files are expected, complex operations such as importing entire databases can be accomplished.</p>

<p><strong>.schema</strong> - Displays the structure of the database.</p>

<figure class="highlight"><pre><code class="language-sql" data-lang="sql"><span class="p">.</span><span class="k">schema</span></code></pre></figure>

<p>Along with SELECT * FROM column; can be used to gain a high level overview of the data contained within the database to quickly understand what is contained therein.</p>

<h2 id="accessing-data">Accessing Data</h2>

<p><strong>SELECT FROM</strong> - Used to retrieve information from a database, FROM indicates which table to query and is required to perform this action.</p>

<figure class="highlight"><pre><code class="language-sql" data-lang="sql"><span class="k">SELECT</span> <span class="n">id_number</span> 
<span class="k">FROM</span> <span class="n">employees</span></code></pre></figure>

<p>displays the id_number column from the employees table.</p>

<p><em>sqlite3 commands themselves are not case sensitive; but it is convention and strongly recommended to capitalize these commands for readability (in other words, mandatory).</em></p>

<p><strong>WHERE</strong> - Filters rows based on a specific condition</p>

<figure class="highlight"><pre><code class="language-sql" data-lang="sql"><span class="k">SELECT</span> <span class="o">*</span> 
<span class="k">FROM</span> <span class="n">login_attempts</span>
<span class="k">WHERE</span> <span class="n">country</span> <span class="o">!=</span> <span class="n">USA</span></code></pre></figure>

<p>Displays all login attempts originating from outside the USA.</p>

<p><strong>Wildcards</strong> - *, % and _. Used to match 1 or many number of characters.</p>

<figure class="highlight"><pre><code class="language-sql" data-lang="sql"><span class="k">SELECT</span> <span class="o">*</span> 
<span class="k">FROM</span> <span class="n">employees</span></code></pre></figure>

<p>* (wildcard) matches any number of characters, causing sqlite to display ALL rows from the employees table.
% (percentage) is similar to * and will also replace 1 or more characters. 
__ (underscore) will only substitute 1 character.</p>

<p>Different SQL languages use different wildcards, check the documentation!</p>

<figure class="highlight"><pre><code class="language-sql" data-lang="sql"><span class="k">SELECT</span> <span class="o">*</span>
<span class="k">FROM</span> <span class="n">users</span>
<span class="k">WHERE</span> <span class="n">name</span> <span class="o">=</span> <span class="s1">'Cale F%'</span><span class="p">;</span></code></pre></figure>

<p>Select any user where their first name is Cale and Surname starts with F</p>

<p><strong>AND</strong> - Allows filtering of more rows</p>

<figure class="highlight"><pre><code class="language-sql" data-lang="sql"><span class="k">SELECT</span> <span class="o">*</span>
<span class="k">FROM</span> <span class="n">employees</span>
<span class="k">WHERE</span> <span class="n">office</span> <span class="o">=</span> <span class="s1">'East-Office'</span>
<span class="k">AND</span> <span class="n">department</span> <span class="o">=</span> <span class="s1">'finance'</span><span class="p">;</span></code></pre></figure>

<p>Filters employees to return only those from the finance department working at the East Office.
You can string together as many AND statements as you like.</p>

<p><strong>OR</strong> - retrieve data that matches either filter.</p>

<figure class="highlight"><pre><code class="language-sql" data-lang="sql"><span class="k">SELECT</span> <span class="o">*</span>
<span class="k">FROM</span> <span class="n">employees</span>
<span class="k">WHERE</span> <span class="n">office</span> <span class="o">=</span> <span class="s1">'East-Office'</span>
<span class="k">AND</span> <span class="n">department</span> <span class="o">=</span> <span class="s1">'finance'</span>
<span class="k">OR</span> <span class="n">department</span> <span class="o">=</span> <span class="s1">'sales'</span><span class="p">;</span></code></pre></figure>

<p>Selects employees from both the finance and sales departments working at the East Office.</p>

<p><strong>NOT</strong> - excludes data, the logical != can be used also.</p>

<figure class="highlight"><pre><code class="language-sql" data-lang="sql"><span class="k">SELECT</span> <span class="o">*</span>
<span class="k">FROM</span> <span class="n">employees</span>
<span class="k">WHERE</span> <span class="n">department</span> <span class="o">!=</span> <span class="s1">'human resources'</span>
<span class="c1">--WHERE NOT department = 'human resources'</span></code></pre></figure>

<p>Returns all employees not belonging to human resources; both WHERE statements are equivalent, either can be used.</p>
<h2 id="filtering-data">Filtering Data</h2>

<p><strong>AVG</strong> - Calculates the average value of a numeric column.</p>

<figure class="highlight"><pre><code class="language-sql" data-lang="sql"><span class="k">SELECT</span> <span class="k">AVG</span><span class="p">(</span><span class="n">age</span><span class="p">)</span>
<span class="k">FROM</span> <span class="n">employees</span></code></pre></figure>

<p>Calculates the average age of employees.</p>

<p><strong>COUNT</strong> - Counts the number of rows or values in a column.</p>

<figure class="highlight"><pre><code class="language-sql" data-lang="sql"><span class="k">SELECT</span> <span class="k">COUNT</span><span class="p">(</span><span class="o">*</span><span class="p">)</span>
<span class="k">FROM</span> <span class="n">login_attempts</span><span class="p">;</span></code></pre></figure>

<p>Displays the total number of login attempts.</p>

<p><strong>DISTINCT</strong> - returns unique values from a column</p>

<figure class="highlight"><pre><code class="language-sql" data-lang="sql"><span class="k">SELECT</span> <span class="k">DISTINCT</span> <span class="n">country</span>
<span class="k">FROM</span> <span class="n">customers</span><span class="p">;</span></code></pre></figure>

<p>lists unique countries of customers</p>

<p><strong>MAX</strong> - Returns the maximum (highest) value of a column</p>

<figure class="highlight"><pre><code class="language-sql" data-lang="sql"><span class="k">SELECT</span> <span class="k">MAX</span><span class="p">(</span><span class="n">price</span><span class="p">)</span>
<span class="k">FROM</span> <span class="n">products</span><span class="p">;</span></code></pre></figure>

<p>returns the highest product price</p>

<p><strong>MIN</strong> - Returns the minimum (lowest) value of a column</p>

<figure class="highlight"><pre><code class="language-sql" data-lang="sql"><span class="k">SELECT</span> <span class="k">MIN</span><span class="p">(</span><span class="n">price</span><span class="p">)</span>
<span class="k">FROM</span> <span class="n">products</span><span class="p">;</span></code></pre></figure>

<p>returns the lowest product price</p>

<p><strong>LIKE</strong> - used to match patterns in a string</p>

<figure class="highlight"><pre><code class="language-sql" data-lang="sql"><span class="k">SELECT</span> <span class="o">*</span>
<span class="k">FROM</span> <span class="n">employees</span>
<span class="k">WHERE</span> <span class="n">full_name</span> <span class="k">LIKE</span> <span class="s1">'John%'</span><span class="p">;</span></code></pre></figure>

<p>Returns all employee full names starting with John.</p>

<p><strong>ORDER BY</strong> - Sorts the result set by one or more columns</p>

<figure class="highlight"><pre><code class="language-sql" data-lang="sql"><span class="k">SELECT</span> <span class="o">*</span>
<span class="k">FROM</span> <span class="n">users</span>
<span class="k">ORDER</span> <span class="k">BY</span> <span class="n">last_login</span></code></pre></figure>

<p>sorts users by most recent login.</p>

<p><strong>LIMIT</strong> - Limits the number of rows returned</p>

<figure class="highlight"><pre><code class="language-sql" data-lang="sql"><span class="k">SELECT</span> <span class="o">*</span>
<span class="k">FROM</span> <span class="n">employees</span>
<span class="k">LIMIT</span> <span class="mi">10</span><span class="p">;</span></code></pre></figure>

<p>selects the first 10 employees.</p>

<p><strong>GROUP BY</strong> - Groups rows based on one or more columns</p>

<figure class="highlight"><pre><code class="language-sql" data-lang="sql"><span class="k">SELECT</span> <span class="n">country</span><span class="p">,</span> <span class="k">COUNT</span><span class="p">(</span><span class="o">*</span><span class="p">)</span>
<span class="k">FROM</span> <span class="n">employees</span>
<span class="k">GROUP</span> <span class="k">BY</span> <span class="n">country</span><span class="p">;</span></code></pre></figure>

<p>counts employees by country.</p>

<p><strong>–comment</strong> - Adds a comment to the code.</p>

<figure class="highlight"><pre><code class="language-sql" data-lang="sql"><span class="k">SELECT</span> <span class="o">*</span>
<span class="c1">-- this query selects all</span>
<span class="k">FROM</span> <span class="n">employees</span>
<span class="c1">-- the above determines which table is being queried</span></code></pre></figure>

<h2 id="nested-queries">Nested queries</h2>

<p>One query is placed inside another, the inner query runs first producing a result set, this result set is then used by the outer query.
This allows for complex filtering, structuring and aggregation of your data and is an essential skill in performing sophisticated data analysis.</p>

<figure class="highlight"><pre><code class="language-sql" data-lang="sql"><span class="k">SELECT</span> <span class="n">user_name</span> 
<span class="k">FROM</span> <span class="n">users</span> 
<span class="k">WHERE</span> <span class="n">user_id</span> <span class="k">IN</span> <span class="p">(</span> 
	<span class="k">SELECT</span> <span class="n">user_id</span> 
	<span class="k">FROM</span> <span class="n">login_logs</span> 
	<span class="k">GROUP</span> <span class="k">BY</span> <span class="n">user_id</span> 
	<span class="k">HAVING</span> <span class="k">COUNT</span><span class="p">(</span><span class="o">*</span><span class="p">)</span> <span class="o">&gt;</span> <span class="mi">500</span> 
<span class="p">);</span></code></pre></figure>

<p>Inner query identifies user IDs with more than 500 login attempts.
Outer query selects the names of those users.</p>

<h2 id="joining-tables">Joining tables</h2>

<p><strong>JOIN</strong> - Combines tables temporarily (tables with a many to many relationship.)</p>

<figure class="highlight"><pre><code class="language-sql" data-lang="sql"><span class="k">SELECT</span> <span class="n">column1</span><span class="p">,</span> <span class="n">column2</span><span class="p">,</span> <span class="p">...</span>
<span class="c1">--Specifies the columns you want to retrieve from the joined tables.</span>
<span class="k">FROM</span> <span class="n">table1</span>
<span class="c1">--Specifies the first table to join</span>
<span class="k">JOIN</span> <span class="n">table2</span> <span class="k">ON</span> <span class="n">table1</span><span class="p">.</span><span class="k">column</span> <span class="o">=</span> <span class="n">table2</span><span class="p">.</span><span class="k">column</span>
<span class="c1">--Specifies the second table to join and the condition for joining. </span>
<span class="c1">--ON  defines the relationship between the two tables based on a common column.</span>
<span class="k">WHERE</span> <span class="n">condition</span>
<span class="c1">--optionally filters the results</span></code></pre></figure>

<figure class="highlight"><pre><code class="language-sql" data-lang="sql"><span class="k">SELECT</span> <span class="n">user_name</span><span class="p">,</span> <span class="n">login_time</span>
<span class="k">FROM</span> <span class="n">users</span>
<span class="k">JOIN</span> <span class="n">login_attempts</span> <span class="k">ON</span> <span class="n">users</span><span class="p">.</span><span class="n">user_id</span> <span class="o">=</span> <span class="n">login_attempts</span><span class="p">.</span><span class="n">user_id</span>
<span class="k">WHERE</span> <span class="n">login_successful</span> <span class="o">=</span> <span class="k">TRUE</span>
<span class="k">ORDER</span> <span class="k">BY</span> <span class="n">login_time</span> <span class="k">DESC</span>
<span class="k">LIMIT</span> <span class="mi">5</span><span class="p">;</span></code></pre></figure>

<p>This example joins users and login_attempts tables based on their user_id.</p>

<p>The results are filtered to only show successful logins, order results by latest login time and limit to the 5 most recent successful login attempts.</p>

<p>This will provide a snapshot of the last few successful logins for the user.</p>

<p><strong>There are different types of JOIN.</strong></p>

<p><strong>INNER JOIN</strong> - returns only rows that have matching values in both tables.</p>

<p><strong>LEFT JOIN</strong> - returns all rows from the left table as well as matched rows from the right table.</p>

<p><strong>RIGHT JOIN</strong> - returns all rows from the right table, and matched rows from the left table.</p>

<p><strong>FULL OUTER JOIN</strong> - returns all rows when there is a match in either the left or right tables.</p>

<p><strong>SELF JOIN</strong> - Joins a table to itself, allowing you to compare rows within the same table.</p>

<h2 id="nested-join-query">Nested JOIN query</h2>

<p>Using the 2 techniques described above, we can find top 3 customers with the highest order value</p>

<figure class="highlight"><pre><code class="language-sql" data-lang="sql"><span class="k">SELECT</span> <span class="n">customer_name</span><span class="p">,</span> <span class="n">total_spent</span>
<span class="k">FROM</span> <span class="p">(</span>
  <span class="k">SELECT</span> <span class="n">customer_name</span><span class="p">,</span> <span class="k">SUM</span><span class="p">(</span><span class="n">order_total</span><span class="p">)</span> <span class="k">AS</span> <span class="n">total_spent</span>
  <span class="k">FROM</span> <span class="n">customers</span>
  <span class="k">JOIN</span> <span class="n">orders</span> <span class="k">ON</span> <span class="n">customers</span><span class="p">.</span><span class="n">customer_id</span> <span class="o">=</span> <span class="n">orders</span><span class="p">.</span><span class="n">customer_id</span>
  <span class="k">GROUP</span> <span class="k">BY</span> <span class="n">customer_name</span>
<span class="p">)</span> <span class="k">AS</span> <span class="n">customer_totals</span>
<span class="k">ORDER</span> <span class="k">BY</span> <span class="n">total_spent</span> <span class="k">DESC</span>
<span class="k">LIMIT</span> <span class="mi">3</span><span class="p">;</span></code></pre></figure>

<p>Inner query calculates the total spent by each customer
Outer query ranks customers based on their total spending and displays the top 3.</p>
<h2 id="data-types">Data types</h2>
<p>When creating a table, using the right data type ensures data integrity by enforcing a specific format. 
Using the correct type also ensures storage efficiency and enables accurate analysis.</p>

<p><strong>BLOB</strong> - Binary data, such as images or documents</p>

<figure class="highlight"><pre><code class="language-sql" data-lang="sql"><span class="k">CREATE</span> <span class="k">TABLE</span> <span class="n">images</span> <span class="p">(</span>
<span class="n">id</span> <span class="nb">INT</span><span class="p">,</span> 
<span class="n">image</span> <span class="nb">BLOB</span>
<span class="p">);</span></code></pre></figure>

<p>stores images in the image column</p>

<p><strong>INTEGER</strong> - integer number</p>

<figure class="highlight"><pre><code class="language-sql" data-lang="sql"><span class="k">CREATE</span> <span class="k">TABLE</span> <span class="n">products</span> <span class="p">(</span>
<span class="n">id</span> <span class="nb">INTEGER</span><span class="p">,</span>
<span class="n">price</span> <span class="nb">INTEGER</span>
<span class="p">);</span></code></pre></figure>

<p>Stores product IDs and prices as integers</p>

<p><strong>NUMERIC(precision, scale)</strong> – Best used for precise representation of numeric values, such as for currency or measurements.
<em>Precision specifies the total number of digits stored, both before and after the decimal point.</em>
<em>Scale indicates the number of digits that can be stored after the decimal point.</em></p>

<figure class="highlight"><pre><code class="language-sql" data-lang="sql"><span class="k">CREATE</span> <span class="k">TABLE</span> <span class="n">orders</span> <span class="p">(</span>
<span class="n">id</span> <span class="nb">INTEGER</span><span class="p">,</span> 
<span class="n">total_price</span> <span class="nb">NUMERIC</span><span class="p">(</span><span class="mi">10</span><span class="p">,</span><span class="mi">2</span><span class="p">)</span>
<span class="p">);</span></code></pre></figure>

<p>Stores order totals with 2 decimal places</p>

<p><strong>REAL</strong> - floating point number</p>

<figure class="highlight"><pre><code class="language-sql" data-lang="sql"><span class="k">CREATE</span> <span class="k">TABLE</span> <span class="n">products</span> <span class="p">(</span>
<span class="n">id</span> <span class="nb">INTEGER</span><span class="p">,</span>
<span class="n">weight</span> <span class="nb">REAL</span>
<span class="p">);</span></code></pre></figure>

<p><strong>TEXT</strong> - character strings</p>

<figure class="highlight"><pre><code class="language-sql" data-lang="sql"><span class="k">CREATE</span> <span class="k">TABLE</span> <span class="n">users</span> <span class="p">(</span>
<span class="n">id</span> <span class="nb">INTEGER</span><span class="p">,</span> 
<span class="n">name</span> <span class="nb">TEXT</span>
<span class="p">);</span></code></pre></figure>

<p>stores user names as text strings.</p>

<h3 id="special-constraints-for-columns">Special constraints for columns</h3>

<p><strong>NOT NUL</strong>L - Ensures a columns cannot contain null values</p>

<figure class="highlight"><pre><code class="language-sql" data-lang="sql"><span class="k">CREATE</span> <span class="k">TABLE</span> <span class="n">users</span> <span class="p">(</span>
<span class="n">id</span> <span class="nb">INTEGER</span> <span class="k">NOT</span> <span class="k">NULL</span><span class="p">,</span> 
<span class="n">email</span> <span class="nb">TEXT</span> <span class="k">NOT</span> <span class="k">NULL</span>
<span class="p">);</span></code></pre></figure>

<p>Ensures the id and email fields cannot be empty</p>

<p><strong>UNIQUE</strong> - ensures that all values in the column are unique</p>

<figure class="highlight"><pre><code class="language-sql" data-lang="sql"><span class="k">CREATE</span> <span class="k">TABLE</span> <span class="n">products</span> <span class="p">(</span>
<span class="n">sku</span> <span class="nb">INTEGER</span> <span class="k">PRIMARY</span> <span class="k">KEY</span><span class="p">,</span>
<span class="n">name</span> <span class="nb">TEXT</span> <span class="k">UNIQUE</span>
<span class="p">);</span></code></pre></figure>

<p>Ensures product names are unique.</p>

<p><strong>Some useful resources to help learn SQL:</strong></p>

<p><a href="https://selectstarsql.com/">Select star SQL</a></p>

<p>An interactive book, practice queries against real data, only takes a few hours and is completely free.
<em>This resource explores data relating to executions in Texas from 1976 and it is very interesting to analyze in its own right.</em></p>

<p><a href="https://cs50.harvard.edu/x/2024/weeks/7/">Harvard’s CS50 lecture on SQL (week 7, 2024)</a></p>

<p>A lecture on SQL that is part of Harvard’s introduction to computer programming. 
<em>A great course to take if you want to gain a bottom-up understanding of programming transferable to any language.</em></p>]]></content><author><name></name></author><summary type="html"><![CDATA[Flat File Databases You may be familiar with a flat-file database; it is usually represented by patterns of columns and rows. A spreadsheet such as those created in Microsoft excel or Google sheets can be considered a flat-file database.]]></summary></entry><entry><title type="html">Murder in SQL city</title><link href="https://blog.frend.pro/Murder-in-SQL-city/" rel="alternate" type="text/html" title="Murder in SQL city" /><published>2024-10-13T06:00:00+00:00</published><updated>2024-10-13T06:00:00+00:00</updated><id>https://blog.frend.pro/Murder-in-SQL-city</id><content type="html" xml:base="https://blog.frend.pro/Murder-in-SQL-city/"><![CDATA[<h3 id="a-way-to-practice-sql">A way to practice SQL</h3>
<p>Knight lab from the Northwestern University in the USA has a great web app that can be used to practice your SQL skills in a fun and engaging manner.</p>

<p>What follows is a walkthrough and explanation of solving the murder mystery of SQL city; this activity can be found at <a href="https://mystery.knightlab.com">https://mystery.knightlab.com/</a></p>

<p><strong>Some useful resources to help learn SQL:</strong></p>

<p><a href="https://selectstarsql.com/">Select star SQL</a></p>

<p>An interactive book, practice queries against real data, only takes a few hours and is completely free.
<em>This resource explores data relating to executions in Texas from 1976 and it very interesting to analyze in its own right.</em></p>

<p><a href="https://cs50.harvard.edu/x/2024/weeks/7/">Harvard’s CS50 lecture on SQL (week 7, 2024)</a></p>

<p>A lecture on SQL that is part of Harvard’s introduction to computer programming. 
<em>A great course to take if you want to gain a bottom-up understanding of programming transferable to any language.</em></p>
<h3 id="introduction">Introduction</h3>

<p>A crime has taken place and the detective needs your help. The detective gave you the crime scene report, but you somehow lost it. You vaguely remember that the crime was a <strong>​murder​</strong> that occurred sometime on ​<strong>Jan.15, 2018​</strong> and that it took place in ​<strong>SQL City​</strong>.</p>
<h3 id="solving-the-mystery">Solving the mystery</h3>

<p>Before moving to solve the crime we first need to gain an understanding of the data structure itself.
This website uses SQlite, to view the schema we can use the below command to query the sqlite_master, a table which contains all the metadata about all objects in the database.
We will restrict this query to showing just the tables to gain a high level overview of the dataset.</p>

<figure class="highlight"><pre><code class="language-sql" data-lang="sql"><span class="k">SELECT</span> <span class="n">name</span> 
<span class="k">FROM</span> <span class="n">sqlite_master</span>
<span class="k">where</span> <span class="k">type</span> <span class="o">=</span> <span class="s1">'table'</span></code></pre></figure>

<p><em>There are many different versions of SQL and each will have their own way of viewing the schema, be sure to check the documentation on how to do this.</em></p>

<p><img src="/images/Pasted image 20241013203031.png" alt="Select-name" /></p>

<p>We can also query how each table was made by querying</p>

<figure class="highlight"><pre><code class="language-sql" data-lang="sql"><span class="k">SELECT</span> <span class="k">sql</span>
<span class="k">FROM</span> <span class="n">sqlite_master</span></code></pre></figure>

<p>This identifies how each table was made and what types of values populate each column.</p>

<p><img src="/images/Pasted image 20241020122155.png" alt="Select-name" /></p>

<p>Next we will query the specific table we are currently interested in.
We start by using the * (wildcard) to see all data and use the LIMIT keyword to only display the first 3 entries, this allows us to gain an understanding of the syntax used for the data.</p>

<figure class="highlight"><pre><code class="language-sql" data-lang="sql"><span class="k">SELECT</span> <span class="o">*</span> 
<span class="k">FROM</span> <span class="n">crime_scene_report</span>
<span class="k">LIMIT</span> <span class="mi">3</span><span class="p">;</span></code></pre></figure>

<p><img src="/images/Pasted image 20241020121638.png" alt="Select-name" /></p>

<p>We now know what we are working with, time to start by retrieving the corresponding crime scene report from the police department’s database.</p>

<figure class="highlight"><pre><code class="language-sql" data-lang="sql"><span class="k">SELECT</span> <span class="o">*</span>
<span class="k">FROM</span> <span class="n">crime_scene_report</span>
<span class="k">WHERE</span> <span class="nb">date</span> <span class="o">=</span> <span class="s1">'20180115'</span><span class="p">;</span></code></pre></figure>

<p><img src="/images/Pasted image 20241013202800.png" alt="Select-name" /></p>

<p>This report gives us 2 clues about potential witnesses, we will need their person_id to query the witness table for their transcripts.</p>

<p>To get the last house on Northwestern Drive from the persons table we will apply filters to order by address number in descending order.</p>

<figure class="highlight"><pre><code class="language-sql" data-lang="sql"><span class="k">SELECT</span> <span class="o">*</span> 
<span class="k">FROM</span> <span class="n">person</span> 
<span class="k">WHERE</span> <span class="n">address_street_name</span> <span class="o">=</span> <span class="s1">'Northwestern Dr'</span>
<span class="k">ORDER</span> <span class="k">BY</span> <span class="n">address_number</span> <span class="k">DESC</span><span class="p">;</span></code></pre></figure>

<p><img src="/images/Pasted image 20241014192051.png" alt="Select-name" /></p>

<p>Next we will apply filters to search for anyone named Annabel who also lives on Franklin Avenue.</p>

<figure class="highlight"><pre><code class="language-sql" data-lang="sql"><span class="k">SELECT</span> <span class="o">*</span> 
<span class="k">FROM</span> <span class="n">person</span> 
<span class="k">WHERE</span> <span class="n">address_street_name</span> <span class="o">=</span> <span class="s1">'Franklin Ave'</span> 
<span class="k">AND</span> <span class="n">name</span> <span class="k">LIKE</span> <span class="s1">'Annabel%'</span><span class="p">;</span></code></pre></figure>

<p><img src="/images/Pasted image 20241013203750.png" alt="Select-name" /></p>

<p>We now have the id from 2 witnesses, We can now search the witness table using the person_id.</p>

<figure class="highlight"><pre><code class="language-sql" data-lang="sql"><span class="k">SELECT</span> <span class="o">*</span> 
<span class="k">FROM</span> <span class="n">interview</span>
<span class="k">WHERE</span> <span class="n">person_id</span> <span class="o">=</span> <span class="s1">'14887'</span>
<span class="k">OR</span> <span class="n">person_id</span> <span class="o">=</span> <span class="s1">'16371'</span></code></pre></figure>

<p><img src="/images/Pasted image 20241014192139.png" alt="Select-name" /></p>

<p>These transcripts give information relating to 3 different tables; we will have to use all the provided information to try and match the data with 1 search using a nested JOIN query, we will try and return a name from the person table bringing the tables queried to 4.</p>

<figure class="highlight"><pre><code class="language-sql" data-lang="sql"><span class="k">SELECT</span> <span class="n">person</span><span class="p">.</span><span class="n">name</span> 
<span class="k">FROM</span> <span class="n">person</span>
<span class="k">INNER</span> <span class="k">JOIN</span> <span class="n">get_fit_now_member</span> 
<span class="k">ON</span> <span class="n">get_fit_now_member</span><span class="p">.</span><span class="n">person_id</span> <span class="o">=</span> <span class="n">person</span><span class="p">.</span><span class="n">id</span> 
<span class="k">INNER</span> <span class="k">JOIN</span> <span class="n">get_fit_now_check_in</span> 
<span class="k">ON</span> <span class="n">get_fit_now_check_in</span><span class="p">.</span><span class="n">membership_id</span> <span class="o">=</span> <span class="n">get_fit_now_member</span><span class="p">.</span><span class="n">id</span>
<span class="k">INNER</span> <span class="k">JOIN</span> <span class="n">drivers_license</span>
<span class="k">ON</span> <span class="n">drivers_license</span><span class="p">.</span><span class="n">id</span> <span class="o">=</span> <span class="n">person</span><span class="p">.</span><span class="n">license_id</span>
<span class="k">WHERE</span> <span class="n">get_fit_now_member</span><span class="p">.</span><span class="n">id</span> <span class="k">LIKE</span> <span class="s1">'48Z%'</span> 
<span class="k">AND</span> <span class="n">get_fit_now_member</span><span class="p">.</span><span class="n">membership_status</span> <span class="o">=</span> <span class="s1">'gold'</span> 
<span class="k">AND</span> <span class="n">get_fit_now_check_in</span><span class="p">.</span><span class="n">check_in_date</span> <span class="o">=</span> <span class="s1">'20180109'</span>
<span class="k">AND</span> <span class="n">drivers_license</span><span class="p">.</span><span class="n">plate_number</span> <span class="k">LIKE</span> <span class="s1">'%H42W%'</span><span class="p">;</span></code></pre></figure>

<p>This will return Jeremy Bowers as the murderer, but that is not the end of this challenge.</p>

<p><img src="/images/Pasted image 20241015194547.png" alt="Select-name" /></p>

<p>We query the interview table using the killers name.</p>

<figure class="highlight"><pre><code class="language-sql" data-lang="sql"><span class="k">SELECT</span> <span class="n">transcript</span> <span class="k">FROM</span> <span class="n">interview</span>
<span class="k">INNER</span> <span class="k">JOIN</span> <span class="n">person</span>
<span class="k">ON</span> <span class="n">interview</span><span class="p">.</span><span class="n">person_id</span> <span class="o">=</span> <span class="n">person</span><span class="p">.</span><span class="n">id</span>
<span class="k">WHERE</span> <span class="n">person</span><span class="p">.</span><span class="n">name</span> <span class="o">=</span> <span class="s1">'Jeremy Bowers'</span><span class="p">;</span></code></pre></figure>

<p><img src="/images/Pasted image 20241015194803.png" alt="Select-name" /></p>

<p>This transcript provides alot of detail; by referring to the sqlite_master table we can see that we will have to query facebook_event_chein as well as drivers_license.
The difficulty lies in displaying results which appear 3 times within a certain date range; this can be done using the HAVING keyword.</p>

<figure class="highlight"><pre><code class="language-sql" data-lang="sql"><span class="k">SELECT</span> <span class="o">*</span>
<span class="k">FROM</span> <span class="n">person</span>
<span class="k">JOIN</span> <span class="n">facebook_event_checkin</span>
<span class="k">ON</span> <span class="n">person</span><span class="p">.</span><span class="n">id</span> <span class="o">=</span> <span class="n">facebook_event_checkin</span><span class="p">.</span><span class="n">person_id</span>
<span class="k">JOIN</span> <span class="n">drivers_license</span>
<span class="k">ON</span> <span class="n">drivers_license</span><span class="p">.</span><span class="n">id</span> <span class="o">=</span> <span class="n">person</span><span class="p">.</span><span class="n">license_id</span>
<span class="k">WHERE</span> <span class="n">facebook_event_checkin</span><span class="p">.</span><span class="n">event_name</span> <span class="o">=</span> <span class="s1">'SQL Symphony Concert'</span>
<span class="k">AND</span>  <span class="n">facebook_event_checkin</span><span class="p">.</span><span class="nb">date</span> <span class="k">LIKE</span> <span class="s1">'201712%'</span>
<span class="k">AND</span> <span class="n">drivers_license</span><span class="p">.</span><span class="n">hair_color</span> <span class="o">=</span> <span class="s1">'red'</span>
<span class="k">AND</span> <span class="n">drivers_license</span><span class="p">.</span><span class="n">car_make</span> <span class="o">=</span> <span class="s1">'Tesla'</span>
<span class="k">AND</span> <span class="n">drivers_license</span><span class="p">.</span><span class="n">car_model</span> <span class="o">=</span> <span class="s1">'Model S'</span>
<span class="k">AND</span> <span class="n">drivers_license</span><span class="p">.</span><span class="n">height</span> <span class="o">&gt;</span> <span class="mi">65</span>
<span class="k">GROUP</span> <span class="k">BY</span> <span class="n">person</span><span class="p">.</span><span class="n">id</span>
<span class="k">HAVING</span> <span class="k">COUNT</span><span class="p">(</span><span class="o">*</span><span class="p">)</span> <span class="o">&gt;=</span> <span class="mi">3</span><span class="p">;</span></code></pre></figure>

<p><strong>Key takeaways:</strong></p>

<p>Data is not always clean, remember to use wildcards (* or _) rule out grammatical errors and issues.</p>

<p>Learn how to query the Schema for the SQL language that you are using, and recall that SELECT * FROM table LIMIT 3; is a great way to gain a quick overview of the data you are analyzing.</p>

<p><img src="/images/Pasted image 20241020113542.png" alt="Select-name" /></p>]]></content><author><name></name></author><summary type="html"><![CDATA[A way to practice SQL Knight lab from the Northwestern University in the USA has a great web app that can be used to practice your SQL skills in a fun and engaging manner.]]></summary></entry><entry><title type="html">Managing Users in Linux</title><link href="https://blog.frend.pro/Managining-users-Linux/" rel="alternate" type="text/html" title="Managing Users in Linux" /><published>2024-10-07T06:30:00+00:00</published><updated>2024-10-07T06:30:00+00:00</updated><id>https://blog.frend.pro/Managining-users-Linux</id><content type="html" xml:base="https://blog.frend.pro/Managining-users-Linux/"><![CDATA[<h3 id="managing-users-in-linux-and-their-permissions">Managing users in Linux and their permissions</h3>
<p>The following will be useful for administrating users via a Linux system; this assumes familiarity with ls -la.</p>

<h3 id="permissions-and-ownership">Permissions and ownership</h3>

<p>Recall that</p>
<figure class="highlight"><pre><code class="language-shell" data-lang="shell"><span class="nb">ls</span> <span class="nt">-la</span></code></pre></figure>
<p>returns a list of files and directories and their permissions</p>

<p><img src="/images/ls-la.png" alt="ls-la-return" /></p>

<p>Permissions in Linux are printed as a 10 character string, drwxrwxrwx.
The first character represents whether permissions are associated with a directory (d)
or a file (-).</p>

<p>The next 9 characters represent permissions in groups of 3 characters for the three groups; User, Group and then other (everyone else).
R = read, W = write, x=execute, - (hyphen) = null.</p>

<p><strong>chmod - change permissions on files and directories</strong></p>

<figure class="highlight"><pre><code class="language-shell" data-lang="shell"><span class="nb">chmod </span>u+rwx, g+rwx, o+rwx login_sessions.txt</code></pre></figure>

<p>Changes user (u), group (g), and other (o) permissions to add (+) read (r), write (w), and execute (x) permissions for the login_sessions.txt file</p>

<figure class="highlight"><pre><code class="language-shell" data-lang="shell"><span class="nb">chmod </span>u-wx, u+r, g-wx, g+r, o-rwx projects/.project_x.txt</code></pre></figure>

<p>Hidden files start with a . (period)
Changes privilege’s so that only the user and the group can read the file.</p>

<figure class="highlight"><pre><code class="language-shell" data-lang="shell"><span class="nb">chmod </span>g-rwx, o-rwx drafts</code></pre></figure>

<p>changes the directory permissions of the drafts folder so that only the user can interact with the directory.</p>

<p><strong>chown - change ownership of a file or directory, used with sudo (more on sudo below)</strong></p>

<figure class="highlight"><pre><code class="language-shell" data-lang="shell"><span class="nb">sudo chown </span>cale access.txt</code></pre></figure>

<p>Changes the user owner of access.txt file to cale.</p>

<figure class="highlight"><pre><code class="language-shell" data-lang="shell"><span class="nb">sudo chown</span> :security access.txt</code></pre></figure>

<p>changes the group owner of access.txt to security, a colon (:) must be entered before the group name.</p>

<p><strong>groupdel - deletes a group from the system, used with sudo</strong></p>

<figure class="highlight"><pre><code class="language-shell" data-lang="shell"><span class="nb">sudo </span>groupdel accounting</code></pre></figure>

<p>deletes accounting as a group</p>

<p><strong>sudo - super user do</strong>
Temporarily grants elevated permissions to specific users, users must be in a sudoers file to have access to sudo.</p>

<figure class="highlight"><pre><code class="language-shell" data-lang="shell"><span class="nb">sudo </span>useradd cale</code></pre></figure>

<p>Grants elevated permissions to the user running this command so that this user can use the useradd command to add cale as a new user to the system.</p>

<p><strong>useradd - adds a new user, used with sudo</strong></p>

<figure class="highlight"><pre><code class="language-shell" data-lang="shell"><span class="nb">sudo </span>useradd <span class="nt">-g</span> security cale</code></pre></figure>

<p>adds cale as a new user and uses the -g option to set their primary group as security.</p>

<figure class="highlight"><pre><code class="language-shell" data-lang="shell"><span class="nb">sudo </span>useradd <span class="nt">-G</span> finance,admin cale</code></pre></figure>

<p>adds cale as a new user and uses the -G option to add them to the supplemental groups of finance and admin.</p>

<p><strong>userdel - deletes a user from the system, used with sudo</strong></p>

<figure class="highlight"><pre><code class="language-shell" data-lang="shell"><span class="nb">sudo </span>userdel cale</code></pre></figure>

<p>deletes cale as a user.</p>

<figure class="highlight"><pre><code class="language-shell" data-lang="shell"><span class="nb">sudo </span>userdel <span class="nt">-r</span> cale</code></pre></figure>

<p>deletes cale as a user and removes all file in their home directory.</p>

<p><strong>usermod - modify an existing user, use with sudo</strong></p>

<figure class="highlight"><pre><code class="language-shell" data-lang="shell"><span class="nb">sudo </span>usermod <span class="nt">-g</span> finance cale</code></pre></figure>

<p>uses the -g option to change the existing cale user’s primary group to be the finance group.</p>

<figure class="highlight"><pre><code class="language-shell" data-lang="shell"><span class="nb">sudo </span>usermod <span class="nt">-G</span> accounting cale</code></pre></figure>

<p>uses the -G option to replace any supplemental groups that the existing cale user is in with the supplemental accounting group.
Removes all other groups cale is in.</p>

<figure class="highlight"><pre><code class="language-shell" data-lang="shell"><span class="nb">sudo </span>usermod <span class="nt">-a</span> <span class="nt">-G</span> finance cale</code></pre></figure>

<p>uses the -a -G options to append the finance group to the user cale, this will not remove existing user groups from the user.</p>

<figure class="highlight"><pre><code class="language-shell" data-lang="shell"><span class="nb">sudo </span>usermod <span class="nt">-d</span> /home/cale_b</code></pre></figure>

<p>uses the -d option to change the existing cale user’s home directory to /home/cale_b.</p>

<figure class="highlight"><pre><code class="language-shell" data-lang="shell"><span class="nb">sudo </span>usermod <span class="nt">-L</span> cale</code></pre></figure>

<p>uses the -L option to lock the existing cale user’s account so that they cannot log in.</p>

<figure class="highlight"><pre><code class="language-shell" data-lang="shell"><span class="nb">sudo </span>usermod <span class="nt">-l</span> caleb cale</code></pre></figure>

<p>uses the -l option to change the existing cale user’s login name to caleb.</p>]]></content><author><name></name></author><summary type="html"><![CDATA[Managing users in Linux and their permissions The following will be useful for administrating users via a Linux system; this assumes familiarity with ls -la.]]></summary></entry><entry><title type="html">Navigating the Linux Command Line Interface (CLI)</title><link href="https://blog.frend.pro/Navigating-the-linux-CLI/" rel="alternate" type="text/html" title="Navigating the Linux Command Line Interface (CLI)" /><published>2024-10-06T09:00:00+00:00</published><updated>2024-10-06T09:00:00+00:00</updated><id>https://blog.frend.pro/Navigating-the-linux-CLI</id><content type="html" xml:base="https://blog.frend.pro/Navigating-the-linux-CLI/"><![CDATA[<h3 id="a-quick-crash-course-to-using-the-linux-command-line-interface-cli">A quick crash course to using the Linux command line interface (CLI)</h3>
<p>I will show you how to do the following:</p>
<ul>
  <li>Navigate the file system</li>
  <li>Read files</li>
  <li>Manage the file system</li>
  <li>Filter content</li>
  <li>Get help in Linux</li>
</ul>

<h3 id="navigating-the-file-system">Navigating the file system</h3>

<p>The following commands are used to navigate the Linux file system;</p>

<p><strong>cd - change directory</strong></p>

<figure class="highlight"><pre><code class="language-shell" data-lang="shell"><span class="nb">cd </span>reports</code></pre></figure>

<p>navigates from the current working directory to its subdirectory reports</p>

<figure class="highlight"><pre><code class="language-shell" data-lang="shell"><span class="nb">cd</span> <span class="se">\h</span>ome<span class="se">\c</span>ale<span class="se">\r</span>eports</code></pre></figure>

<p>navigates to the reports directory; the full pathname is required when reports is not a subfirectory of the current working directory</p>

<figure class="highlight"><pre><code class="language-shell" data-lang="shell"><span class="nb">cd</span> ..</code></pre></figure>

<p>Navigates to the directory that is one level above the current working directory</p>

<p><strong>ls - displays the names of files and directories</strong></p>

<figure class="highlight"><pre><code class="language-shell" data-lang="shell"><span class="nb">ls</span> <span class="se">\h</span>ome<span class="se">\c</span>ale<span class="se">\r</span>eports</code></pre></figure>

<p>Displays the names of the files and directories in the reports directory; providing an argument that specifies the path to a directory is necessary to display the contents of a directory other than the user’s current working directory.</p>

<figure class="highlight"><pre><code class="language-shell" data-lang="shell"><span class="nb">ls</span> <span class="nt">-a</span></code></pre></figure>

<p>Displays hidden files when displaying the names of files and directories inside the current working directory.</p>

<figure class="highlight"><pre><code class="language-shell" data-lang="shell"><span class="nb">ls</span> <span class="nt">-l</span></code></pre></figure>

<p>Displays permissions to files and directories in the current working directory; also displays other additional information such as owner name, group, file size and the time of last modification.</p>

<figure class="highlight"><pre><code class="language-shell" data-lang="shell"><span class="nb">ls</span> <span class="nt">-la</span></code></pre></figure>

<p>displays permissions to files and directories in the current working directoy; including hidden files. Also displays other additional information. This argument is a combination of both -a and -l and combines the output of both.</p>

<p><strong>pwd - prints the working directory to the screen</strong></p>

<figure class="highlight"><pre><code class="language-shell" data-lang="shell"><span class="nb">pwd</span></code></pre></figure>

<p>Prints the current working directory to screen, such as \home\cale</p>

<p><strong>whoami - returns the username of the current user</strong></p>

<figure class="highlight"><pre><code class="language-shell" data-lang="shell"><span class="nb">whoami</span></code></pre></figure>

<p>returns the current username, such as cale or admin.</p>

<h3 id="reading-files">Reading files</h3>
<p>The following details commands that are helpful when reading files</p>

<p><strong>cat - displays the contents of a file</strong></p>

<figure class="highlight"><pre><code class="language-shell" data-lang="shell"><span class="nb">cat </span>updates.txt</code></pre></figure>

<p>displays the content of the updates.txt file</p>

<p><strong>head - displays the first 10 lines of a file</strong></p>

<figure class="highlight"><pre><code class="language-shell" data-lang="shell"><span class="nb">head </span>updates.txt</code></pre></figure>

<p>displays the first 10 lines of the updates.txt file</p>

<figure class="highlight"><pre><code class="language-shell" data-lang="shell"><span class="nb">head</span> <span class="nt">-n</span> 5 updates.txt</code></pre></figure>

<p>displays only the first 5 lines of the file.
the -n option allows the user to specify the <em>number</em> of lines to return.</p>

<p><strong>less - returns the content of a file one page at a time</strong></p>

<figure class="highlight"><pre><code class="language-shell" data-lang="shell">less updates.txt</code></pre></figure>

<p>returns the content of updates one page at a time; the less command changes the terminal window to a display which allows users to easily move forward and backward through content.</p>

<p><strong>tail - displays the last 10 lines of a file</strong></p>

<figure class="highlight"><pre><code class="language-shell" data-lang="shell"><span class="nb">tail </span>updates.txt</code></pre></figure>

<p>displays the last 10 lines of the updates.txt file</p>

<figure class="highlight"><pre><code class="language-shell" data-lang="shell"><span class="nb">tail</span> <span class="nt">-n</span> 5 updates.txt</code></pre></figure>

<p>returns the last 5 lines of updates.txt. The -n option allows the user to specify the number of lines to return.</p>

<h3 id="manage-the-file-system">Manage the file system</h3>
<p>The following are useful when managing the file system.</p>

<p><strong>cp - copies a file or directory into a new location; the file will not be removed from the previous location</strong></p>

<figure class="highlight"><pre><code class="language-shell" data-lang="shell"><span class="nb">cp </span>permissions.txt /home/cale/logs</code></pre></figure>

<p>copies the permissions.txt from the users current working directory to the logs directory.</p>

<p><strong>mkdir - make directory</strong></p>

<figure class="highlight"><pre><code class="language-shell" data-lang="shell"><span class="nb">mkdir </span>network</code></pre></figure>

<p>creates a new directory named network in the users current working directory.</p>

<figure class="highlight"><pre><code class="language-shell" data-lang="shell"><span class="nb">mkdir</span> /home/analyst/logs/network</code></pre></figure>

<p>creates a new directory named network in the logs directory.
The full path is required when the target directory is not a subdirectory of the current directory.</p>

<p><strong>mv - moves a file or directory to a new location; the file is also removed from the previous location.</strong></p>

<figure class="highlight"><pre><code class="language-shell" data-lang="shell"><span class="nb">mv </span>permissions.txt /home/cale/logs</code></pre></figure>

<p>moves the permissions.txt file from the users current working directory to the logs directory.</p>

<figure class="highlight"><pre><code class="language-shell" data-lang="shell"><span class="nb">mv </span>permissions.txt perm.txt</code></pre></figure>

<p>moves the permissions.txt file from the users current working directory to the new file name perm.txt in the users current working directory; this results in renaming the permissions.txt file as perm.txt.</p>

<p><strong>nano - opens or creates a file in the nano CLI file editor.</strong></p>

<figure class="highlight"><pre><code class="language-shell" data-lang="shell">nano permissions.txt</code></pre></figure>

<p>Opens an existing permissions.txt file in the nano file editor, or creates permissions.txt in the nano file editor if it doesn’t already exist in the current working directory.</p>

<p><strong>rm - remove a file</strong></p>

<figure class="highlight"><pre><code class="language-shell" data-lang="shell"><span class="nb">rm </span>permissions.txt</code></pre></figure>

<p>removes the permissions.txt file from the users current working directory</p>

<figure class="highlight"><pre><code class="language-shell" data-lang="shell"><span class="nb">rm </span>home/cale/reports/permissions.txt</code></pre></figure>

<p>removes the permissions.txt file from the reports directory; the fill path is required is the users current working directory is not reports.</p>

<p><strong>rmdir - remove a directory</strong></p>

<figure class="highlight"><pre><code class="language-shell" data-lang="shell"><span class="nb">rmdir </span>network</code></pre></figure>

<p>removes the empty network subdirectory of the users current working directory from the file system.</p>

<figure class="highlight"><pre><code class="language-shell" data-lang="shell"><span class="nb">rm</span> /home/cale/logs/network</code></pre></figure>

<p>removes the empty network directory from the file system; the full path is required when network is not a subdirectory of the current directory.</p>

<p><strong>touch - creates a new file</strong></p>

<figure class="highlight"><pre><code class="language-shell" data-lang="shell"><span class="nb">touch </span>permissions.txt</code></pre></figure>

<p>creates a new file named permissions.txt in the users current working directory</p>

<figure class="highlight"><pre><code class="language-shell" data-lang="shell"><span class="nb">touch</span> /home/cale/reports/permissions.txt</code></pre></figure>

<p>creates a new file named permissions in the reports directory; the full path is required if the user wants to create permissions.txt in any directory other than the current working directory.</p>
<h3 id="filter-content">Filter content</h3>
<p>These commands are useful for filtering content.</p>

<p><strong>find - searches for directories and files that meet the specified criteria</strong></p>

<figure class="highlight"><pre><code class="language-shell" data-lang="shell">find <span class="se">\h</span>ome<span class="se">\c</span>ale<span class="se">\p</span>rojects</code></pre></figure>

<p>searches for all files starting at the projects directory</p>

<figure class="highlight"><pre><code class="language-shell" data-lang="shell">find <span class="se">\h</span>ome<span class="se">\c</span>ale<span class="se">\p</span>rojects <span class="nt">-iname</span> <span class="s2">"*log*"</span></code></pre></figure>

<p>searches for all files in the projects directory that contain the work log in the filename.
-iname searches for a specified string and is not case-sensitive; * is a wildcard and can represent zero or more unknown characters.</p>

<figure class="highlight"><pre><code class="language-shell" data-lang="shell">find <span class="se">\h</span>ome<span class="se">\c</span>ale<span class="se">\p</span>rojects <span class="nt">-mtime</span> <span class="nt">-3</span></code></pre></figure>

<p>Searches for all files in the projects directory that have been modified within the past 3 days.
-mtime bases its search for files or directories that were modifed within the specified number of days.</p>

<figure class="highlight"><pre><code class="language-shell" data-lang="shell">find <span class="se">\h</span>ome<span class="se">\c</span>ale<span class="se">\p</span>rojects <span class="nt">-nmin</span> <span class="nt">-15</span></code></pre></figure>

<p>Searches for all files in the projects directory that have been modified within the past 15 minutes.
-nmin bases its search for files or directories that were modified within the specified number of minutes.</p>

<p><strong>grep - searches within a specified file and returns all lines containing a specified string.</strong></p>

<figure class="highlight"><pre><code class="language-shell" data-lang="shell"><span class="nb">grep </span>OS updates.txt</code></pre></figure>

<p>searches the updates.txt file and returns all lines containing the string OS</p>

<p><strong>| (piping) - sends the output of one command as the input of another command for further processing.</strong></p>

<figure class="highlight"><pre><code class="language-shell" data-lang="shell"><span class="nb">ls</span> <span class="se">\h</span>ome<span class="se">\a</span>nalyst<span class="se">\r</span>eports | <span class="nb">grep users</span></code></pre></figure>

<p>redirects the standard output of ls \home\cale\reports to be standard input for the grep users command, meaning the grep users identifies files and subdirectories in the \home\cale\reports directory that contain the string users within their filename.</p>

<p><strong>There is a lot that you can do with piping, It is crucial to understand the basic concept as we will be using this later.</strong></p>

<h3 id="get-help-in-linux">Get help in Linux</h3>
<p>The following commands are useful when getting help in Linux.</p>

<p><strong>apropos - searches the manual page descriptions for a specified string</strong></p>

<figure class="highlight"><pre><code class="language-shell" data-lang="shell">apropos password</code></pre></figure>

<p>returns the manual pages of commands that contain the keyword password</p>

<figure class="highlight"><pre><code class="language-shell" data-lang="shell">apropos <span class="nt">-a</span> graph editor</code></pre></figure>

<p>returns the manual pages of commands that contain both keywords graph and editor.
-a species to return commands that only contain all specified strings.</p>

<p><strong>man - displays a manual page for the specified command</strong></p>

<figure class="highlight"><pre><code class="language-shell" data-lang="shell">man <span class="nb">chown</span></code></pre></figure>

<p>displays detailed information about chown and how it works.</p>

<p><strong>whatis - displays a description of a command on a single line</strong></p>

<figure class="highlight"><pre><code class="language-shell" data-lang="shell">whatis nano</code></pre></figure>

<p>Displays a description of nano on a single line.</p>]]></content><author><name></name></author><summary type="html"><![CDATA[A quick crash course to using the Linux command line interface (CLI) I will show you how to do the following: Navigate the file system Read files Manage the file system Filter content Get help in Linux]]></summary></entry><entry><title type="html">Hello world, I’m Cale</title><link href="https://blog.frend.pro/Hello-World/" rel="alternate" type="text/html" title="Hello world, I’m Cale" /><published>2024-10-06T06:00:00+00:00</published><updated>2024-10-06T06:00:00+00:00</updated><id>https://blog.frend.pro/Hello-World</id><content type="html" xml:base="https://blog.frend.pro/Hello-World/"><![CDATA[<p>I’m teaching myself IT; follow my journey through this blog.</p>]]></content><author><name></name></author><summary type="html"><![CDATA[I’m teaching myself IT; follow my journey through this blog.]]></summary></entry></feed>