<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Kitibwa Rich</title>
    <description>The latest articles on DEV Community by Kitibwa Rich (@richkitibwa).</description>
    <link>https://dev.to/richkitibwa</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F673054%2Fa2ebb31e-6a6c-4f5b-a007-22e5db717297.jpeg</url>
      <title>DEV Community: Kitibwa Rich</title>
      <link>https://dev.to/richkitibwa</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/richkitibwa"/>
    <language>en</language>
    <item>
      <title>Building a Webapp with User Authentification using Flask</title>
      <dc:creator>Kitibwa Rich</dc:creator>
      <pubDate>Fri, 27 Aug 2021 21:51:04 +0000</pubDate>
      <link>https://dev.to/richkitibwa/building-a-webapp-with-user-authentification-using-flask-443h</link>
      <guid>https://dev.to/richkitibwa/building-a-webapp-with-user-authentification-using-flask-443h</guid>
      <description>&lt;p&gt;In this article, I will be showing you how to build a simple web app with &lt;strong&gt;user authentification&lt;/strong&gt; or &lt;strong&gt;login&lt;/strong&gt; using flask.&lt;/p&gt;

&lt;h3&gt;
  
  
  This app will have the following features:
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;Users will be able to sign up using their email addresses and also create a password.&lt;/li&gt;
&lt;li&gt;Once a user is signed in, they are registered in the database.&lt;/li&gt;
&lt;li&gt;If any user tries to sign in with credentials that already exist in the database, an error message will be returned notifying them.&lt;/li&gt;
&lt;li&gt;The app will have a remember me function to remember users so they don't always have to enter their passwords to login to the app.&lt;/li&gt;
&lt;li&gt;When logged in, a user will be able to see other routes of the app like profile and sign out.&lt;/li&gt;
&lt;li&gt;When signed out, the user can only see the home, Login and signup routes.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Alright lets get coding.
&lt;/h2&gt;

&lt;p&gt;The first step is to fire up the IDE of choice. &lt;br&gt;
Then create a project folder and then set up a virtual environment in which we will add the different dependencies for the app.&lt;/p&gt;

&lt;p&gt;Install the necessary packages such as &lt;strong&gt;flask&lt;/strong&gt;, &lt;strong&gt;flask-login&lt;/strong&gt;(which is used for the user login and authentication), &lt;strong&gt;flask-sqlalchemy&lt;/strong&gt; which is used to create a database to store the data.&lt;/p&gt;

&lt;p&gt;Once all that is set up, create a new python file and call it &lt;code&gt;init.py&lt;/code&gt;. This will initialise the app.&lt;/p&gt;

&lt;p&gt;Open the &lt;code&gt;init.py&lt;/code&gt; file and import the following packages;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Flask&lt;/strong&gt; provides a lightweight framework for building our web app.&lt;br&gt;
&lt;strong&gt;SQLAlchemy&lt;/strong&gt; is used to create the database to store user data such as emails and passwords.&lt;br&gt;
Checkout the official documentation &lt;a href="https://flask-sqlalchemy.palletsprojects.com/en/2.x/"&gt;here&lt;/a&gt; to know about flask-SQLAlchemy.&lt;br&gt;
&lt;strong&gt;flask-login&lt;/strong&gt; provides user session management for flask. It handles common tasks such as logging in, logging out and remembering users' sessions . Be sure to check out the official flask-login documentation &lt;a href="https://flask-login.readthedocs.io/en/latest/"&gt;here&lt;/a&gt; for more information about it.&lt;/p&gt;

&lt;p&gt;Next, we will create a function to initialize the database using SQLAlchmemy as shown in the code snippet below.&lt;/p&gt;

&lt;p&gt;Initialise SQLAlchemy so we can use it later.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;db = SQLAlchemy()&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Create a function called &lt;code&gt;create_app&lt;/code&gt; and create the flask instance and also add other configurations for the database.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def create_app():
    app = Flask(__name__)
    app.secret_key = b'_5#y2L"F4Qz\k\xec]/'
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.db'
    db.init_app(app)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;create a variable called &lt;code&gt;login_manager&lt;/code&gt; to create a Login Manager instance to manage user login.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;login_manager = LoginManager()
login_manager.login_view = 'auth.login'
login_manager.init_app(app) 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then create another python file called &lt;code&gt;models.py&lt;/code&gt; to store information about the users.&lt;/p&gt;

&lt;p&gt;The model created is constituted of class which is translated into tables in our database. Each of the attributes are transformed into columns for the table.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(100), unique=True)
    password = db.Column(db.String(100))
    name = db.Column(db.String(1000)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Open the &lt;strong&gt;init.py&lt;/strong&gt; file again and import class &lt;strong&gt;User&lt;/strong&gt; from &lt;strong&gt;models.py&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Open a new python file called auth.py. This file will contain all the logic for our &lt;strong&gt;auth routes&lt;/strong&gt; for example login and signup.&lt;/p&gt;

&lt;p&gt;Import the neccesary packages first.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from flask import Blueprint, render_template, redirect, url_for, request, flash
from werkzeug.security import generate_password_hash, check_password_hash
from models import User
from flask_login import login_user, logout_user, login_required
from init import db
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Flash&lt;/strong&gt; is used to show messages to the user for example error messages.&lt;br&gt;
&lt;strong&gt;Blueprint&lt;/strong&gt; is a python package that can help structure a flask  application by grouping its functionality into reusable components. Read more about Blueprint package &lt;a href="https://realpython.com/flask-blueprint/"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;In this file we will put all the auth routes with logic to add new users to the database ,remember the user and logout the user.&lt;/p&gt;

&lt;p&gt;Here is the full file below &lt;/p&gt;

&lt;p&gt;&lt;code&gt;auth.py&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from flask import Blueprint, render_template, redirect, url_for, request, flash
from werkzeug.security import generate_password_hash, check_password_hash
from models import User
from flask_login import login_user, logout_user, login_required
from init import db

auth = Blueprint('auth', __name__)


@auth.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        return render_template('login.html')
    else:
        email = request.form.get('email')
        password = request.form.get('password')
        remember = True if request.form.get('remember') else False
        user = User.query.filter_by(email=email).first()

        if not user:
            flash('Please sign up first!')
            return redirect(url_for('auth.signup'))
        elif not check_password_hash(user.password, password):
            flash('Please check your login details and try again.')
            return redirect(url_for('auth.login'))
        login_user(user, remember=remember)
        return redirect(url_for('main.profile'))


@auth.route('/signup', methods=['GET', 'POST'])
def signup():
    if request.method == 'GET':
        return render_template('signup.html')
    else:
        email = request.form.get('email')
        name = request.form.get('name')
        password = request.form.get('password')
        user = User.query.filter_by(email=email).first()

        if user:
            flash('Email already exists')
            return redirect(url_for('auth.signup'))
        new_user = User(email=email, name=name, password=generate_password_hash(password, method='SHA256'))

        db.session.add(new_user)
        db.session.commit()
        return redirect(url_for('auth.login'))


@auth.route('/logout')
@login_required
def logout():
    logout_user()
    return redirect(url_for('main.index'))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is the full &lt;strong&gt;init.py&lt;/strong&gt; file.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager

db = SQLAlchemy()


def create_app():
    app = Flask(__name__)
    app.secret_key = b'_5#y2L"F4Qz\k\xec]/'
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.db'
    db.init_app(app)
    login_manager = LoginManager()
    login_manager.login_view = 'auth.login'
    login_manager.init_app(app)

    from models import User

    @login_manager.user_loader
    def load_user(user_id):
        return User.query.get(int(user_id))

    # blueprint for auth routes in the app
    from auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint)

    # blueprint for non auth routes in the app
    from main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    return app
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;main.py&lt;/code&gt; file&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from flask import Blueprint, render_template
from flask_login import login_required, current_user
from init import create_app, db

main = Blueprint('main', __name__)


@main.route('/')
def index():
    return render_template('index.html')


@main.route('/profile')
@login_required
def profile():
    return render_template('profile.html', name=current_user.name)


app = create_app()

if __name__ == '__main__':
    db.create_all(app=create_app())
    app.run(debug=True)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is the main entry point of the app.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;models.py&lt;/code&gt; file&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from flask_login import UserMixin
from init import db


class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(100), unique=True)
    password = db.Column(db.String(100))
    name = db.Column(db.String(1000))

    def __repr__(self):
        return'&amp;lt;User %r&amp;gt;' % self.id

    def __init__(self, email, password, name):
        db.create_all()
        self.email = email
        self.password = password
        self.name = name
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After creating the logic for the app, we now create the templates of the different pages.&lt;/p&gt;

&lt;p&gt;Create a templates folder in the main project folder and create a new html file called &lt;code&gt;base.html&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;This is the main html file from which all the other  html file will inherit. We use &lt;strong&gt;jinja templates&lt;/strong&gt; to extend the base.html to the other templates.&lt;/p&gt;

&lt;p&gt;Here is the full &lt;code&gt;base.html&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html lang="en"&amp;gt;
&amp;lt;head&amp;gt;
    &amp;lt;meta charset="UTF-8"&amp;gt;
    &amp;lt;title&amp;gt;Flask Login&amp;lt;/title&amp;gt;
    &amp;lt;link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.2/css/bulma.min.css" /&amp;gt;
    &amp;lt;link rel="stylesheet" href="{{ url_for('static', filename='css/main.css') }}"&amp;gt;

&amp;lt;/head&amp;gt;
&amp;lt;body&amp;gt;
&amp;lt;section class="hero is-fullheight" style="background-image:#C4FCEF;"&amp;gt;

    &amp;lt;div class="hero-head"&amp;gt;
        &amp;lt;nav class="navbar"&amp;gt;
            &amp;lt;div class="container"&amp;gt;
                &amp;lt;div class="navbar-brand"&amp;gt;
                    &amp;lt;a href="{{ url_for('main.index') }}" class="navbar-item" style="color:white"&amp;gt;
                        CampNight
                    &amp;lt;/a&amp;gt;
                &amp;lt;/div&amp;gt;

                &amp;lt;div id="navbarMenuHeroA" class="navbar-menu"&amp;gt;
                    &amp;lt;div class="navbar-end"&amp;gt;
                        &amp;lt;a href="{{ url_for('main.index') }}" class="navbar-item"&amp;gt;
                            Home
                        &amp;lt;/a&amp;gt;
                        {% if current_user.is_authenticated %}
                        &amp;lt;a href="{{ url_for('main.profile') }}" class="navbar-item"&amp;gt;
                            Profile
                        &amp;lt;/a&amp;gt;
                        {% endif %}

                        {% if not current_user.is_authenticated %}
                        &amp;lt;a href="{{ url_for('auth.login') }}" class="navbar-item"&amp;gt;
                            Login
                        &amp;lt;/a&amp;gt;
                        &amp;lt;a href="{{ url_for('auth.signup') }}" class="navbar-item"&amp;gt;
                            Sign Up
                        &amp;lt;/a&amp;gt;
                        {% endif %}

                        {% if current_user.is_authenticated %}
                        &amp;lt;a href="{{ url_for('auth.logout') }}" class="navbar-item"&amp;gt;
                            Logout
                        &amp;lt;/a&amp;gt;
                        {% endif %}
                    &amp;lt;/div&amp;gt;
                &amp;lt;/div&amp;gt;
            &amp;lt;/div&amp;gt;
        &amp;lt;/nav&amp;gt;
    &amp;lt;/div&amp;gt;

    &amp;lt;div class="hero-body"&amp;gt;
        &amp;lt;div class="container has-text-centered"&amp;gt;
            {% block content %}{% endblock %}
        &amp;lt;/div&amp;gt;
    &amp;lt;/div&amp;gt;
&amp;lt;/section&amp;gt;
&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Notice that for the style we use &lt;strong&gt;Bulma css&lt;/strong&gt; which is a nice framework. Read more about it &lt;a href="https://bulma.io/"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;We then create an &lt;code&gt;index.html&lt;/code&gt; which is the homepage. &lt;/p&gt;

&lt;p&gt;&lt;code&gt;index.html&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{% extends "base.html" %}

{%block content%}
&amp;lt;h1 class ="title"&amp;gt;Welcome to CampNight &amp;lt;/h1&amp;gt;
&amp;lt;h2 class="subtitle"&amp;gt;Are you ready for an adventure?&amp;lt;/h2&amp;gt;
{%endblock%}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Check out the jinja templates used here in curly brackets. You can read more about jinja templates &lt;a href="https://jinja.palletsprojects.com/en/3.0.x/"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;We then create the &lt;code&gt;login.html&lt;/code&gt; template&lt;/p&gt;

&lt;p&gt;&lt;code&gt;login.html&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{% extends "base.html" %}

{%block content%}
&amp;lt;div class="column is-4 is-offset-4"&amp;gt;
    &amp;lt;h3 class="title"&amp;gt;Login&amp;lt;/h3&amp;gt;
    &amp;lt;div class="box"&amp;gt;
        {% with messages = get_flashed_messages() %}
            {% if messages %}
                &amp;lt;div class="notification is-danger"&amp;gt;
                     {{ messages[0] }}
                 &amp;lt;/div&amp;gt;
            {% endif %}
        {% endwith %}
        &amp;lt;form method="POST" action="/login"&amp;gt;
            &amp;lt;div class="field"&amp;gt;
                &amp;lt;div class="control"&amp;gt;
                    &amp;lt;input class="input is-large" type="email" name="email" placeholder="Your Email" autofocus=""&amp;gt;
                &amp;lt;/div&amp;gt;
            &amp;lt;/div&amp;gt;
            &amp;lt;div class="field"&amp;gt;
                &amp;lt;div class="control"&amp;gt;
                    &amp;lt;input class="input is-large" type="password" name="password" placeholder="Your Password"&amp;gt;
                &amp;lt;/div&amp;gt;
            &amp;lt;/div&amp;gt;
            &amp;lt;div class="field"&amp;gt;
                &amp;lt;label class="checkbox"&amp;gt;
                    &amp;lt;input type="checkbox"&amp;gt;
                    Remember me
                &amp;lt;/label&amp;gt;
            &amp;lt;/div&amp;gt;
            &amp;lt;button class="button is-block is-info is-large is-fullwidth"&amp;gt;Login&amp;lt;/button&amp;gt;
        &amp;lt;/form&amp;gt;
    &amp;lt;/div&amp;gt;
&amp;lt;/div&amp;gt;
{%endblock%}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then the &lt;code&gt;profile.html&lt;/code&gt; to display the name of the particular user once they login.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{% extends 'base.html' %}

{% block content %}
&amp;lt;h1 class="title"&amp;gt;
    Welcome, {{ name }}!
&amp;lt;/h1&amp;gt;
{% endblock %}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We  then add the &lt;code&gt;signup.html&lt;/code&gt;  for users to sign up.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{% extends "base.html" %}

{% block content %}
&amp;lt;div class="column is-4 is-offset-4"&amp;gt;
    &amp;lt;h3 class="title"&amp;gt;Sign Up&amp;lt;/h3&amp;gt;
    &amp;lt;div class="box"&amp;gt;
        {% with messages = get_flashed_messages() %}
            {% if messages %}
                &amp;lt;div class="notification is-danger"&amp;gt;
                    {{ messages[0] }}&amp;lt;br&amp;gt; Go to &amp;lt;a href="{{ url_for('auth.login') }}"&amp;gt;login page&amp;lt;/a&amp;gt;
                &amp;lt;/div&amp;gt;
            {% endif %}
        {% endwith %}
        &amp;lt;form method="POST" action="/signup"&amp;gt;
            &amp;lt;div class="field"&amp;gt;
                &amp;lt;div class="control"&amp;gt;
                    &amp;lt;input class="input is-large" type="email" name="email" placeholder="Email" autofocus=""&amp;gt;
                &amp;lt;/div&amp;gt;
            &amp;lt;/div&amp;gt;
            &amp;lt;div class="field"&amp;gt;
                &amp;lt;div class="control"&amp;gt;
                    &amp;lt;input class="input is-large" type="text" name="name" placeholder="Name" autofocus=""&amp;gt;
                &amp;lt;/div&amp;gt;
            &amp;lt;/div&amp;gt;
            &amp;lt;div class="field"&amp;gt;
                &amp;lt;div class="control"&amp;gt;
                    &amp;lt;input class="input is-large" type="password" name="password" placeholder="Password"&amp;gt;
                &amp;lt;/div&amp;gt;
            &amp;lt;/div&amp;gt;
            &amp;lt;button class="button is-block is-info is-large is-fullwidth"&amp;gt;Sign Up&amp;lt;/button&amp;gt;
        &amp;lt;/form&amp;gt;
    &amp;lt;/div&amp;gt;
&amp;lt;/div&amp;gt;
{% endblock %}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Add another folder in the project folder and name it &lt;strong&gt;static&lt;/strong&gt;.&lt;br&gt;
This folder contains resources for the app such as customised css sheets and images added to the app.&lt;/p&gt;

&lt;p&gt;The app is now finally ready and you can run it by running &lt;code&gt;python main.py&lt;/code&gt; in the terminal. &lt;/p&gt;

&lt;p&gt;Run the app on local host 5000 and it will displayed in the browser.&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--REtzFn8---/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/udpn4kxrzhbj6trskz0s.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--REtzFn8---/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/udpn4kxrzhbj6trskz0s.png" alt="Sample webapp"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Feel free to run the app hosted on &lt;a href="https://campnight1.herokuapp.com/"&gt;here&lt;/a&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  Resources
&lt;/h4&gt;

&lt;p&gt;Be sure to check out &lt;a href="https://medium.com/analytics-vidhya/creating-login-page-on-flask-9d20738d9f42"&gt;this&lt;/a&gt; amazing medium article for more on how to implement user authentification in your web app using flask.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>A gentle introduction to Flask </title>
      <dc:creator>Kitibwa Rich</dc:creator>
      <pubDate>Wed, 11 Aug 2021 20:54:43 +0000</pubDate>
      <link>https://dev.to/richkitibwa/a-gentle-introduction-to-flask-2d95</link>
      <guid>https://dev.to/richkitibwa/a-gentle-introduction-to-flask-2d95</guid>
      <description>&lt;h2&gt;
  
  
  What is Flask?
&lt;/h2&gt;

&lt;p&gt;According to &lt;a href="https://en.wikipedia.org/wiki/Flask_(web_framework)"&gt;wikipedia&lt;/a&gt; &lt;strong&gt;Flask&lt;/strong&gt; is micro web framework written in Python. It is classified as a microframework because it does not require particular tools or libraries. Flask makes it possible to easily build web applications.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why use flask?
&lt;/h2&gt;

&lt;p&gt;There are other options you could consider to build your web application, so you may be wondering why choose flask? &lt;br&gt;
Well, Flask  is much easier to learn and doesn't need a large code base to implement a simple web application as we will see later on.&lt;/p&gt;
&lt;h2&gt;
  
  
  Getting started
&lt;/h2&gt;

&lt;p&gt;In this article I will be showing you how to build a very simple hello world web application using flask. We will be using python 3.&lt;/p&gt;
&lt;h1&gt;
  
  
  Using a virtual environment.
&lt;/h1&gt;

&lt;p&gt;When developing in python, its always important to write your code in a &lt;strong&gt;virtual environment&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;A virtual environment is an isolated environment where dependencies for a particular python project can be downloaded. Each python project should have it's own virtual environment where the specific dependencies are downloaded separate from the main global installation on your system.&lt;br&gt;
With a virtual environment, everyone on the team can be able to run the python project with the same dependencies so this helps solve errors which could arise due to version changes in some dependencies.&lt;/p&gt;
&lt;h3&gt;
  
  
  Setting up the virtual environment.
&lt;/h3&gt;

&lt;p&gt;A virtual environment can be easily set up as shown below: &lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;First, fire up your favorite IDE and create a project folder.&lt;/li&gt;
&lt;li&gt;In the terminal, type &lt;code&gt;pip3 install virtualenv&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Type &lt;code&gt;virtualenv env&lt;/code&gt; to create your virtual environment. Note that the &lt;code&gt;env&lt;/code&gt; after &lt;code&gt;virtualenv&lt;/code&gt; can be any name you choose to call your virtual environment. So it could be &lt;code&gt;virtualenv myapp&lt;/code&gt;, or any name that you feel is appropriate. &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;After successful creation of the virtual environment, you should be able to see a folder added to your project folder with the name of the virtual environment you just created. &lt;/p&gt;

&lt;p&gt;Now to activate your virtual environment, you just need to run the command &lt;code&gt;your_virtual_env_name\Scripts\activate.bat&lt;/code&gt; on windows and for mac, &lt;br&gt;
run &lt;code&gt;source your_virtual_env_name/bin/activate&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Your virtual environment should now be active. The name will be displayed in brackets just before the path in the terminal.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--LkSroQGd--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y2yr2lp4gtpnn0g8yfkr.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--LkSroQGd--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y2yr2lp4gtpnn0g8yfkr.jpg" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now that we have a virtual environment up and running we can start building our flask app.&lt;/p&gt;
&lt;h3&gt;
  
  
  Setting up the flask app.
&lt;/h3&gt;

&lt;p&gt;Within the activated virtual environment, install flask using the terminal  by typing &lt;code&gt;pip3 install Flask&lt;/code&gt;.&lt;br&gt;
Create a new python file in the project folder, you can name it &lt;strong&gt;main.py&lt;/strong&gt; or &lt;strong&gt;app.py&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Open up the newly created python file and import flask.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;from flask import Flask&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Then make an instance of the Flask class and call it app. Calling it app is just by convention.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;app = Flask(__name__)&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;The first first argument &lt;code&gt;__name__&lt;/code&gt; is the name of the application module. This is  needed so that Flask knows where to look for resources such as &lt;strong&gt;templates&lt;/strong&gt; and &lt;strong&gt;static files&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Then we use the &lt;code&gt;route()&lt;/code&gt; decorator to tell Flask what URL should trigger our function. &lt;/p&gt;

&lt;p&gt;&lt;code&gt;@app.route('/')&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;We then add a function to return what we want to display in the browser.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def Hello():
    return "Hello World!"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Finally the app is started by running,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if __name__ == "__main__":
    app.run(debug=True)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can use &lt;code&gt;app.run()&lt;/code&gt; without the arguments and the app will still run, but usually its good to include the &lt;code&gt;debug=True&lt;/code&gt;argument in order to be able to see any error logs in case there are any errors.&lt;/p&gt;

&lt;p&gt;That's if for our set up of the basic app.&lt;/p&gt;

&lt;p&gt;This is the full code for our app.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from flask import Flask

app = Flask(__name__)

@app.route("/")
def hello_world():
    return "&amp;lt;p&amp;gt;Hello, World!&amp;lt;/p&amp;gt;"

if __name__ == "__main__":
    app.run(debug=True)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now the next step is to run the app in the browser.&lt;/p&gt;

&lt;p&gt;To do this, go back to the terminal, ensure that you are still in the virtual environment and run &lt;code&gt;python main.py&lt;/code&gt;. &lt;strong&gt;main.py&lt;/strong&gt; is the name of the python file that is the entry point for your app. So you could give it any name that makes sense to your project.&lt;/p&gt;

&lt;p&gt;On running the command &lt;code&gt;python main.py&lt;/code&gt; a URL will show up in the terminal and you can open it up in the browser to see the web application.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--Qui13XyE--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vp07ey4cbaox39valda7.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Qui13XyE--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vp07ey4cbaox39valda7.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--NE0U7aNK--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vzu1t1l37u0m33t5cspf.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--NE0U7aNK--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vzu1t1l37u0m33t5cspf.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Viola, that's how simple it is to get started with flask.&lt;/p&gt;

&lt;p&gt;This is a very basic introduction just to whet your appetite for flask . Be sure to check out more resources on how you can use flask for a variety of cool stuff.&lt;/p&gt;

&lt;p&gt;The official flask documentation &lt;a href="https://flask.palletsprojects.com/en/2.0.x/quickstart/"&gt;here&lt;/a&gt; is a good start to understand flask.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Introduction to Python Functions</title>
      <dc:creator>Kitibwa Rich</dc:creator>
      <pubDate>Tue, 03 Aug 2021 06:28:16 +0000</pubDate>
      <link>https://dev.to/richkitibwa/introduction-to-python-functions-79d</link>
      <guid>https://dev.to/richkitibwa/introduction-to-python-functions-79d</guid>
      <description>&lt;h1&gt;
  
  
  What is a function?
&lt;/h1&gt;

&lt;p&gt;A function is a set of instructions/ block of code that is put together to achieve a specific outcome or perform specific tasks.&lt;br&gt;
Functions enable us avoid having repetitive blocks of code in our program making it easy to read and maintain.&lt;/p&gt;

&lt;p&gt;Functions in python are either &lt;strong&gt;built-in&lt;/strong&gt; or &lt;strong&gt;user defined&lt;/strong&gt;.&lt;/p&gt;
&lt;h2&gt;
  
  
  Built-in functions.
&lt;/h2&gt;

&lt;p&gt;These are functions that come with python installation. For example the &lt;code&gt;print()&lt;/code&gt; function that is used to print to the console.&lt;br&gt;
Other types of built-in functions include &lt;code&gt;float()&lt;/code&gt; which returns a floating type number, &lt;code&gt;input()&lt;/code&gt; which allows user input, &lt;code&gt;int()&lt;/code&gt; which returns an integer, etc.&lt;/p&gt;
&lt;h2&gt;
  
  
  User defined functions.
&lt;/h2&gt;

&lt;p&gt;These are functions that a developer creates in order to perform a given task.&lt;/p&gt;

&lt;p&gt;Functions are defined using the &lt;code&gt;def&lt;/code&gt; keyword followed by the function name and parenthesis then a full colon.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def my_function(parameters):
    """Docstring"""
    statement
    return
my_function()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The function body consists of an optional &lt;strong&gt;docstring&lt;/strong&gt; that is written inside triple quotation marks. It's optional but advisable as good practice to include a docstring at the start of your function as way to describe what the function is supposed to do.&lt;/p&gt;

&lt;p&gt;The statement refers to the code in  the function. It could be an if statement, a for loop, a print statement or any other code that maybe added to the function. This must be indented.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;return&lt;/code&gt; statement is a keyword that exits a function optionally passing back an expression to the caller.&lt;br&gt;
The return statement can be written without any arguments and in that case its the same as return None so it will just exit the function.&lt;/p&gt;

&lt;p&gt;However, there can be arguments added after the return statement. The return statement can consist of a variable, or expression which is returned at the end of the function execution.&lt;/p&gt;

&lt;p&gt;Finally the function call which is done by writing the name of the function followed by parenthesis. The parenthesis is filled with arguments that are passed when calling the function. Sometimes they can be left empty. The function call is &lt;strong&gt;de-indented&lt;/strong&gt; and at the same margin with the def keyword.&lt;/p&gt;

&lt;p&gt;The parenthesis in the function definition can either be left empty or filled with parameters.&lt;/p&gt;
&lt;h2&gt;
  
  
  Function arguments.
&lt;/h2&gt;

&lt;p&gt;An argument is a value that is sent to the function when it is called. It's important to note that by default a function should be called with the correct number of arguments, meaning that if your function expects two arguments, it must called with two arguments not more not less lest it throws an error.&lt;/p&gt;

&lt;p&gt;There are different types of arguments in python functions.&lt;/p&gt;
&lt;h3&gt;
  
  
  Default arguments.
&lt;/h3&gt;

&lt;p&gt;This is an argument  that assumes a default value if a value is not passed in the function call for that argument.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def car_brand(brand="Toyota"):
    print("I drive a " + brand)

car_brand("Benz")
car_brand("Jeep")
car_brand("Volvo")
car_brand()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The above code will produce the following when run.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;I drive a Benz
I drive a Jeep
I drive a Volvo
I drive a Toyota
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The last function call was provided no argument so when it was called, the default argument that was supplied in the function definition was passed.&lt;/p&gt;

&lt;h3&gt;
  
  
  Keyword arguments.
&lt;/h3&gt;

&lt;p&gt;When using keyword arguments, you provide names to the parameters as you pass them through the function definition so during the function call, the caller identifies the arguments by the parameter names.&lt;br&gt;
This allows you to place arguments out of order since the python interpreter is able to use the keywords provided to match the values with the parameters.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def my_friends(friend1, friend2, friend3):
    print("My best friend is " + friend1)

my_friends(friend3 = "Mark", friend1 = "James", friend2 = "Sophie")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This function will return:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;My best friend is James
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The order in which you call the arguments doesn't matter.&lt;/p&gt;

&lt;h3&gt;
  
  
  Arbitrary keyword arguments
&lt;/h3&gt;

&lt;p&gt;If you don't know how many keyword arguments will be provided into your function, add two asterisks &lt;code&gt;**&lt;/code&gt; before the parameter name in the function definition. &lt;br&gt;
Usually the keyword &lt;code&gt;**kwargs&lt;/code&gt; is used to represent keyword arguments.&lt;br&gt;
The double asterisks allow us to pass any number of keyword arguments.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def favorite_place(**kwargs):
    print("My favorite city is " + kwargs["city"])


favorite_place(country="England", city="London")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This code will produce the output below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;My favorite city is London
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Arbitrary arguments (*args)
&lt;/h3&gt;

&lt;p&gt;If you don't know the number of arguments that will be passed into you function, add an asterisk (*) before the parameter name in the function definition. The function will receive a tuple of arguments and access them accordingly.&lt;/p&gt;

&lt;p&gt;Using the *, the variable that we associate with the * becomes an iterable meaning you can do things like iterate over it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def friends(*args):
    for friend in args:
        print(friend)

friends("Marcus", "James", "John", "Oliver")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The code above iterates through the args and prints out each friend passed in the friends function. You can pass as many arguments in friends as you want and they will all be printed out.&lt;/p&gt;

&lt;h3&gt;
  
  
  Anonymous functions.
&lt;/h3&gt;

&lt;p&gt;Anonymous functions aren't declared using the def key word. Instead, the key word &lt;strong&gt;Lambda&lt;/strong&gt; is used.&lt;/p&gt;

&lt;p&gt;A Lambda function can take any number of arguments but return just one value in form of an expression. They are restricted to a single expression.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;lambda arguments: expression&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;lambda x,y: x+y&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Here x,y are the arguments and x+y is the expression.&lt;/p&gt;

&lt;p&gt;An advantage of using Lambda functions is that you can write a function in one line of code making it concise.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;add = lambda x, y: x + y
print(add(5 , 6))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The above lambda function adds two numbers together.&lt;/p&gt;

&lt;p&gt;When the same function is written with a function definition, It is longer&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def add(x, y):
    return x + y

print(add(5, 6))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;yet both these functions return the same result.&lt;/p&gt;

&lt;p&gt;I hope this brief introduction makes functions in python a bit easier for you to understand. Cheers.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Python Basics, Python 101!</title>
      <dc:creator>Kitibwa Rich</dc:creator>
      <pubDate>Sat, 24 Jul 2021 12:53:05 +0000</pubDate>
      <link>https://dev.to/richkitibwa/python-basics-python-101-4m98</link>
      <guid>https://dev.to/richkitibwa/python-basics-python-101-4m98</guid>
      <description>&lt;h2&gt;
  
  
  What is python?
&lt;/h2&gt;

&lt;p&gt;Python is an interpreted, object oriented ,dynamically typed, high level programming language. This means that instead of executing all of the source code at once, python executes it line by line. Its high level built-in data structures combined with dynamic typing make it suitable for rapid application development.&lt;/p&gt;

&lt;p&gt;Python has applications in a wide range of areas including:&lt;br&gt;
  Artificial intelligence and machine learning.&lt;br&gt;
  Web development &lt;br&gt;
  Game development&lt;br&gt;
  Digital signal processing&lt;/p&gt;
&lt;h2&gt;
  
  
  Python Datatypes
&lt;/h2&gt;

&lt;p&gt;A datatype is an attribute of data which tells the &lt;a href="https://en.wikipedia.org/wiki/Compiler"&gt;compiler&lt;/a&gt; or &lt;a href="https://en.wikipedia.org/wiki/Interpreter_(computing)"&gt;interpreter&lt;/a&gt; how the programmer intends to use the data.&lt;/p&gt;

&lt;p&gt;In python there are a variety of data types including &lt;strong&gt;strings&lt;/strong&gt;, &lt;strong&gt;float&lt;/strong&gt;, &lt;strong&gt;int&lt;/strong&gt;, &lt;strong&gt;boolean&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;A string is a collection of characters enclosed in quotation marks .It could be double ("")or single ('')quotation marks but one must ensure that they don't mix them up.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;x = "hello world"&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;A float is a decimal number&lt;/p&gt;

&lt;p&gt;&lt;code&gt;num_float = 0.42&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;An int is a number without any decimals&lt;/p&gt;

&lt;p&gt;&lt;code&gt;num_integer = 25&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Boolean has two types; true or false.&lt;/p&gt;

&lt;p&gt;You can easily get the data type of a variable in python using the &lt;code&gt;type()&lt;/code&gt; function &lt;/p&gt;

&lt;p&gt;type(x) will return str data type.&lt;/p&gt;
&lt;h2&gt;
  
  
  Data structures
&lt;/h2&gt;

&lt;p&gt;Python is made up of a variety of data structures some inbuilt and some can be user defined.&lt;br&gt;
Data structures are code structures that define how data is stored and organized. &lt;br&gt;
Python has four built-in data structures i.e.  &lt;strong&gt;lists&lt;/strong&gt;, &lt;strong&gt;dictionaries&lt;/strong&gt; ,&lt;strong&gt;tuples&lt;/strong&gt; and &lt;strong&gt;sets&lt;/strong&gt;.&lt;/p&gt;
&lt;h3&gt;
  
  
  Lists
&lt;/h3&gt;

&lt;p&gt;A List is an array-like data structure that  contains an &lt;strong&gt;ordered&lt;/strong&gt; collection of items. &lt;br&gt;
ordered means that every item in a list has a position.&lt;br&gt;
Lists are &lt;strong&gt;mutable&lt;/strong&gt; (can be changed).&lt;/p&gt;

&lt;p&gt;A list is created by defining a list name and the items are put in square brackets.&lt;br&gt;
For example&lt;br&gt;
&lt;code&gt;my_list = []&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;The items are separated by comas.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;my_list = [a,b,c,d]&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;If you want to get an element from a list you use zero based indexing, meaning that the first element is at position 0&lt;/p&gt;

&lt;p&gt;&lt;code&gt;get_first_item = my_list[0]&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;This will return the first item in the list which is a.&lt;/p&gt;

&lt;p&gt;Lists have many methods which can be used to perform operations on them. &lt;br&gt;
For example&lt;br&gt;
&lt;code&gt;append()&lt;/code&gt; which is used to add an element at the end of the list&lt;br&gt;
&lt;code&gt;insert()&lt;/code&gt; which is used to add an element at a specified position.&lt;br&gt;
&lt;code&gt;copy()&lt;/code&gt; which is used to return a copy of the entire list.&lt;/p&gt;
&lt;h3&gt;
  
  
  Tuples
&lt;/h3&gt;

&lt;p&gt;A tuple is like a list but it is &lt;strong&gt;immutable&lt;/strong&gt; meaning it cannot be changed once it's declared. Tuples are also ordered meaning that they have a defined order and it will not be changed. A tuple is declared using parenthesis ().&lt;/p&gt;

&lt;p&gt;&lt;code&gt;my_tuple = (oranges,mangoes,apples)&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;It's also possible to declare a tuple with one element. To do this, ensure that you add a coma after the  element in parenthesis so that python can know that it's a tuple.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;one_tuple = (banana,)&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;If you never want to change your elements they should be declared in a tuple since it's immutable.&lt;/p&gt;
&lt;h3&gt;
  
  
  Set
&lt;/h3&gt;

&lt;p&gt;Sets are &lt;strong&gt;unordered&lt;/strong&gt; collections meaning that the elements follow no specific order (are unindexed). They are declared with curly brackets {}.&lt;br&gt;
Sets are &lt;strong&gt;mutable&lt;/strong&gt;, they can be changed, items can be removed, added or replaced.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;my_set = {1,2,3,4,5}&lt;/code&gt;&lt;br&gt;
Sets are used when we need to confirm the presence or absence of an item in a set. In other words, they are used for membership tests.&lt;/p&gt;
&lt;h3&gt;
  
  
  Dictionary (Dict)
&lt;/h3&gt;

&lt;p&gt;A dictionary is a collection of &lt;strong&gt;key/value pairs&lt;/strong&gt;. A dictionary is initialized using curly brackets {} and filled with colon : separated keys and values (key : value). Dictionaries are ordered and changeable .&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;my_dict = {
 "Name": "James",
 "age":25,
 "Nationality": "Ugandan"
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note that the keys in dictionaries can not be duplicated.&lt;/p&gt;

&lt;h2&gt;
  
  
  Functions in python
&lt;/h2&gt;

&lt;p&gt;A function is a set of instructions that you want to use repeatedly in a program. Instead of writing these instructions every time you need them, they can easily be written in a function once and for all. The function just needs to be called in case you need to use the instructions.&lt;/p&gt;

&lt;p&gt;A function is created using the def key word.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def my_function():
    print("Hello")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The function can be called by using its name followed by parenthesis&lt;/p&gt;

&lt;p&gt;&lt;code&gt;my_function()&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Parameters&lt;/strong&gt; are specified in the function definition by putting them in the parenthesis. If you have more than one parameter, they can be separated using comas&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def my_add_function(a,b):
    return(a+b)
my_add_function(1,2)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here a and b are parameters&lt;/p&gt;

&lt;p&gt;An &lt;strong&gt;argument&lt;/strong&gt; is what is passed through when calling the function.&lt;/p&gt;

&lt;p&gt;1 and 2 are arguments.&lt;/p&gt;

&lt;h2&gt;
  
  
  Control flow
&lt;/h2&gt;

&lt;p&gt;Control flow is the order in which a program executes its instructions.&lt;br&gt;
Control flow in python is regulated by control statements and loops.&lt;/p&gt;
&lt;h3&gt;
  
  
  Python conditions and if statements
&lt;/h3&gt;

&lt;p&gt;Python has a variety of logical operators used to perform logic in control flow.&lt;/p&gt;

&lt;p&gt;These include:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Equals: a == b
Not Equals: a != b
Less than: a &amp;lt; b
Less than or equal to: a &amp;lt;= b
Greater than: a &amp;gt; b
Greater than or equal to: a &amp;gt;= b
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  If statement
&lt;/h3&gt;

&lt;p&gt;Often, you need to execute some statements only if some condition holds, or choose statements to execute depending on several mutually exclusive conditions. The Python compound statement if, which uses &lt;strong&gt;if&lt;/strong&gt;, &lt;strong&gt;elif&lt;/strong&gt;, and &lt;strong&gt;else&lt;/strong&gt; clauses, lets you conditionally execute blocks of statements.&lt;/p&gt;

&lt;p&gt;Usually if statements are used with logical operators as shown in the example below&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;a = 12
b = 5
if b &amp;gt; a:
  print("b is greater than a")
elif a == b:
  print("a and b are equal")
else:
  print("a is greater than b")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the first condition b is less than a so it will print false.&lt;br&gt;
In the second a is not equal to b so it will print false&lt;br&gt;
then in the third it will print 'a is greater than b' since its true.&lt;/p&gt;

&lt;p&gt;Remember that in python &lt;strong&gt;indentation&lt;/strong&gt; is very important.&lt;/p&gt;
&lt;h3&gt;
  
  
  Loops.
&lt;/h3&gt;

&lt;p&gt;Loops are used to iterate over a sequence.&lt;/p&gt;
&lt;h4&gt;
  
  
  For loop
&lt;/h4&gt;

&lt;p&gt;The key word &lt;strong&gt;for&lt;/strong&gt; is used.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;countries = ["Uganda", "Kenya", "Tanzania"]
for x in country:
  print(x) 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will print each country.&lt;/p&gt;

&lt;h4&gt;
  
  
  While loop
&lt;/h4&gt;

&lt;p&gt;While loop executes a set of statements as long as a condition is true.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;i = 1
while i &amp;lt; 4:
  print(i)
  i += 1
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can add a &lt;strong&gt;break&lt;/strong&gt; statement to stop the loop even if the while condition is true.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;i = 1
while i &amp;lt; 4:
  print(i)
  if i == 3:
    break
  i += 1
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Using the &lt;strong&gt;continue&lt;/strong&gt; statement, we can stop the current iteration, and continue with the next.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;i = 0
while i &amp;lt; 4:
  i += 1
  if i == 3:
    continue
  print(i)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I hope this brief introduction was helpful and insightful.&lt;/p&gt;

</description>
    </item>
  </channel>
</rss>
