<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>App Development Archives - Be on the Right Side of Change</title>
	<atom:link href="https://blog.finxter.com/category/app-development/feed/" rel="self" type="application/rss+xml" />
	<link>https://blog.finxter.com/category/app-development/</link>
	<description></description>
	<lastBuildDate>Sun, 28 Apr 2024 14:15:30 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>

<image>
	<url>https://blog.finxter.com/wp-content/uploads/2020/08/cropped-cropped-finxter_nobackground-32x32.png</url>
	<title>App Development Archives - Be on the Right Side of Change</title>
	<link>https://blog.finxter.com/category/app-development/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Creating a Live Bitcoin Price Chart Using Binance API (No API Key!)</title>
		<link>https://blog.finxter.com/creating-a-live-bitcoin-price-chart-using-binance-api-no-api-key/</link>
		
		<dc:creator><![CDATA[Jean Rousseau]]></dc:creator>
		<pubDate>Sun, 28 Apr 2024 14:14:46 +0000</pubDate>
				<category><![CDATA[App Development]]></category>
		<category><![CDATA[Bitcoin]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Web Development]]></category>
		<category><![CDATA[Web Scraping]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1670164</guid>

					<description><![CDATA[<p>In this tutorial, we&#8217;ll learn how to create a simple live-updating Bitcoin price chart using the Binance API. This straightforward guide will cover all the necessary HTML, JavaScript, and CSS code required to get started with real-time cryptocurrency price tracking. You don&#8217;t need much for this tutorial: ✅ We&#8217;ll create a single HTML document that ... <a title="Creating a Live Bitcoin Price Chart Using Binance API (No API Key!)" class="read-more" href="https://blog.finxter.com/creating-a-live-bitcoin-price-chart-using-binance-api-no-api-key/" aria-label="Read more about Creating a Live Bitcoin Price Chart Using Binance API (No API Key!)">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/creating-a-live-bitcoin-price-chart-using-binance-api-no-api-key/">Creating a Live Bitcoin Price Chart Using Binance API (No API Key!)</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>In this tutorial, we&#8217;ll learn how to create a simple live-updating Bitcoin price chart using the Binance API. This straightforward guide will cover all the necessary HTML, JavaScript, and CSS code required to get started with real-time cryptocurrency price tracking.</p>



<p>You don&#8217;t need much for this tutorial: <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /> </p>



<ol class="wp-block-list">
<li>Basic understanding of HTML, CSS, and JavaScript.</li>



<li>A modern web browser.</li>
</ol>



<p>We&#8217;ll create a single HTML document that includes inline JavaScript and CSS. This approach ensures that you can easily copy, paste, and run the example without managing multiple files.</p>



<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4c8.png" alt="📈" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Execution</strong>: To run the Bitcoin price checker, copy the entire HTML code into a file with a <code>.html</code> extension. Open this file in any modern web browser to see the live Bitcoin price updating every few seconds.</p>



<p>You can see it live right here:</p>



<!DOCTYPE html>
<html lang="en">
<head>
    
    
    <title>Live Bitcoin Price Chart</title>
    <style>
        body {
            font-family: Arial, sans-serif;
        }
        #chartContainer {
            height: 300px;
            width: 100%;
            margin: 20px auto;
            border: 1px solid #ccc;
        }
    </style>
</head>
<body>
    <div id="chartContainer"></div>
    <script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
    <script>
        let priceDataPoints = [];

        function updateChartData() {
            fetch('https://api.binance.com/api/v3/ticker/price?symbol=BTCUSDT')
                .then(response => response.json())
                .then(data => {
                    const btcPrice = parseFloat(data.price);
                    const currentTime = new Date();
                    priceDataPoints.push({ x: currentTime, y: btcPrice });
                    if (priceDataPoints.length > 20) {
                        priceDataPoints.shift();
                    }
                    updateChart();
                }).catch(error => console.error("Error fetching BTC price:", error));
        }

        function updateChart() {
            let chart = new CanvasJS.Chart("chartContainer", {
                title: {
                    text: "Live Bitcoin Price"
                },
                axisX: {
                    title: "Time",
                    valueFormatString: "HH:mm:ss",
                    labelAngle: -30
                },
                axisY: {
                    title: "Price (USD)",
                    includeZero: false,
                    prefix: "$"
                },
                data: [{
                    type: "line",
                    xValueType: "dateTime",
                    dataPoints: priceDataPoints
                }]
            });
            chart.render();
        }

        updateChartData(); // Initial call to populate the chart
        setInterval(updateChartData, 5000); // Update chart every 5 seconds
    </script>
</body>
</html>



<p>Here&#8217;s the full HTML document with embedded CSS and JavaScript:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">&lt;!DOCTYPE html>
&lt;html lang="en">
&lt;head>
    &lt;meta charset="UTF-8">
    &lt;meta name="viewport" content="width=device-width, initial-scale=1.0">
    &lt;title>Live Bitcoin Price Chart&lt;/title>
    &lt;style>
        body {
            font-family: Arial, sans-serif;
        }
        #chartContainer {
            height: 300px;
            width: 100%;
            margin: 20px auto;
            border: 1px solid #ccc;
        }
    &lt;/style>
&lt;/head>
&lt;body>
    &lt;div id="chartContainer">&lt;/div>
    &lt;script src="https://canvasjs.com/assets/script/canvasjs.min.js">&lt;/script>
    &lt;script>
        let priceDataPoints = [];

        function updateChartData() {
            fetch('https://api.binance.com/api/v3/ticker/price?symbol=BTCUSDT')
                .then(response => response.json())
                .then(data => {
                    const btcPrice = parseFloat(data.price);
                    const currentTime = new Date();
                    priceDataPoints.push({ x: currentTime, y: btcPrice });
                    if (priceDataPoints.length > 20) {
                        priceDataPoints.shift();
                    }
                    updateChart();
                }).catch(error => console.error("Error fetching BTC price:", error));
        }

        function updateChart() {
            let chart = new CanvasJS.Chart("chartContainer", {
                title: {
                    text: "Live Bitcoin Price"
                },
                axisX: {
                    title: "Time",
                    valueFormatString: "HH:mm:ss",
                    labelAngle: -30
                },
                axisY: {
                    title: "Price (USD)",
                    includeZero: false,
                    prefix: "$"
                },
                data: [{
                    type: "line",
                    xValueType: "dateTime",
                    dataPoints: priceDataPoints
                }]
            });
            chart.render();
        }

        updateChartData(); // Initial call to populate the chart
        setInterval(updateChartData, 5000); // Update chart every 5 seconds
    &lt;/script>
&lt;/body>
&lt;/html></pre>



<p>The code works as follows:</p>



<p><strong>HTML Structure</strong>: We have a <code>div</code> element where the chart will be displayed.</p>



<p><strong>CSS Styling</strong>: Simple styles are applied to ensure the chart container is visually defined.</p>



<p><strong>JavaScript for Live Data</strong>:</p>



<ul class="wp-block-list">
<li><strong>Fetching Data</strong>: The JavaScript uses the <code>fetch</code> API to pull live Bitcoin prices from Binance&#8217;s public API endpoint.</li>



<li><strong>Updating the Chart</strong>: We use CanvasJS (a third-party library) to render the price chart. New data points are added every 5 seconds, and the oldest data points are removed to keep the chart clean and readable.</li>



<li><strong>CanvasJS Library</strong>: This is a powerful and easy-to-use chart library, which we include from a CDN. It simplifies drawing the live chart.</li>
</ul>
<p>The post <a href="https://blog.finxter.com/creating-a-live-bitcoin-price-chart-using-binance-api-no-api-key/">Creating a Live Bitcoin Price Chart Using Binance API (No API Key!)</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How I Created a Calculator App Using Django – Part 3</title>
		<link>https://blog.finxter.com/how-i-created-a-calculator-app-using-django-part-3/</link>
		
		<dc:creator><![CDATA[Jonathan Okah]]></dc:creator>
		<pubDate>Thu, 22 Jun 2023 09:27:19 +0000</pubDate>
				<category><![CDATA[App Development]]></category>
		<category><![CDATA[Django]]></category>
		<category><![CDATA[Projects]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Web Development]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1455197</guid>

					<description><![CDATA[<p>We have finished designing the calculator app. Using a hypertext markup language (HTML), we set the structure of the calculator. The Cascading Style Sheet (CSS) was used to beautify the calculator and to design the layout. Finally, we used JavaScript to make the app interact with other buttons and perform basic calculations. Our task is ... <a title="How I Created a Calculator App Using Django – Part 3" class="read-more" href="https://blog.finxter.com/how-i-created-a-calculator-app-using-django-part-3/" aria-label="Read more about How I Created a Calculator App Using Django – Part 3">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/how-i-created-a-calculator-app-using-django-part-3/">How I Created a Calculator App Using Django – Part 3</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>We have finished designing the calculator app. Using a hypertext markup language (HTML), <a rel="noreferrer noopener" href="https://blog.finxter.com/how-i-created-a-calculator-app-using-django/" data-type="post" data-id="1377998" target="_blank">we set the structure of the calculator</a>. The Cascading Style Sheet (CSS) was used to beautify the calculator and to design the layout. Finally, we used <a href="https://blog.finxter.com/how-i-created-a-calculator-app-using-django-part-2/" data-type="post" data-id="1448231" target="_blank" rel="noreferrer noopener">JavaScript to make the app interact</a> with other buttons and perform basic calculations.</p>



<ul class="wp-block-list">
<li><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f9ee.png" alt="🧮" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Part 1: </strong><a href="https://blog.finxter.com/how-i-created-a-calculator-app-using-django/" data-type="URL" data-id="https://blog.finxter.com/how-i-created-a-calculator-app-using-django/" target="_blank" rel="noreferrer noopener">How I Created a Calculator App Using Django</a></li>



<li><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f9ee.png" alt="🧮" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Part 2: </strong><a href="https://blog.finxter.com/how-i-created-a-calculator-app-using-django-part-2/" data-type="URL" data-id="https://blog.finxter.com/how-i-created-a-calculator-app-using-django-part-2/" target="_blank" rel="noreferrer noopener">How I Created a Calculator App Using Django</a></li>



<li><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f9ee.png" alt="🧮" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Part 3: </strong><a href="https://blog.finxter.com/how-i-created-a-calculator-app-using-django-part-3/" data-type="URL" data-id="https://blog.finxter.com/how-i-created-a-calculator-app-using-django-part-3/" target="_blank" rel="noreferrer noopener">How I Created a Calculator App Using Django</a></li>
</ul>



<p>Our task is done but there is a problem. Throughout the development stage, we used a text editor to write our code and to observe what we were doing on a browser, we copied the path to the file and pasted it to the address bar. </p>



<p>Without doing this, we cannot see the calculator app.</p>



<p>Furthermore, if we were to call it a day, how then will we include Python language as part of learning Python through building projects? Just as we mentioned in the first part of this project tutorial, we will use Django, a Python framework, to host this app.</p>



<h2 class="wp-block-heading">Django Setup</h2>



<p>We have a lot to do on the terminal to set up Django. We start by creating a separate folder for this project, activating a virtual environment and installing Django.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">mkdir project &amp;&amp; cd project
python3 -m venv .venv
source .venv/bin/activate
pip install django tzdata
</pre>



<p>Next, we start Django project and Django app.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">django-admin startproject operation .
python3 manage.py startapp calculator
</pre>



<p>At this stage, you are expected to have these files in your folder:</p>



<pre class="wp-block-preformatted"><code>README.md  calculator  index.html  manage.py  operation  script.js  styles.css</code></pre>



<p>Next, we create templates and static folders. Inside the static folder, we create two additional folders for JavaScript and CSS.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">mkdir -p templates static/js static/css</pre>



<h2 class="wp-block-heading">Making changes in the settings file</h2>



<p>We now head over to the <code>settings.py</code> file to inform Django of what we have done. Inside the file, start by adding the newly created app in the <code>INSTALLED_APPS</code> section.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">INSTALLED_APPS = [
    …
    # custom app
    'calculator',
]
</pre>



<p>Next, import the <a href="https://blog.finxter.com/exploring-pythons-os-module/" data-type="post" data-id="19050" target="_blank" rel="noreferrer noopener"><code>os</code> module</a> and go to the TEMPLATES section to make this one-line change.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">TEMPLATES = [
…
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
…
]
</pre>



<p>We have static files. To tell Django where to look for these static files, go to the bottom of the file just below the <code>STATIC_URL</code>, and also make this one-line change.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]</pre>



<p>Next, in your project-level URL, make this change:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('calculator.urls')),
]
</pre>



<p>On the terminal, rename the CSS file and move the template and static files to their rightful place.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">mv styles.css base.css
mv index.html templates

mv base.css static/css/

mv script.js static/js/
</pre>



<p>This is how your project folder is expected to be:</p>



<pre class="wp-block-preformatted"><code>README.md  calculator  manage.py  operation  static  templates</code></pre>



<h2 class="wp-block-heading">Making changes to the Markup file</h2>



<p>Next, open your <code>index.html</code>. Load the static files at the top like this:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">{% load static %}</pre>



<p>Adjust the link that points to the CSS file to be like this:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">    &lt;link rel="stylesheet" href="{% static 'css/base.css' %}"></pre>



<p>The script tag for the JavaScript will also be like this:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">&lt;script src="{% static 'js/script.js' %}”>&lt;/script></pre>



<h2 class="wp-block-heading">The view function and the app-level URL</h2>



<p>To view the calculator app on the local server, we have to create a view function and render it.</p>



<p>The view function is quite simple:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from django.shortcuts import render

def index(request):
    return render(request, 'index.html')
</pre>



<p>For the app-level URL, create a <code>urls.py</code> file inside the app folder.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from django.urls import path
from .views import index


urlpatterns = [
    path('', index, name='home'),
]
</pre>



<p>That’s all. We can now start the local server.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">python3 manage.py migrate
python3 manage.py runserver
</pre>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img fetchpriority="high" decoding="async" width="720" height="405" src="https://blog.finxter.com/wp-content/uploads/2023/06/image-218.png" alt="" class="wp-image-1455207" srcset="https://blog.finxter.com/wp-content/uploads/2023/06/image-218.png 720w, https://blog.finxter.com/wp-content/uploads/2023/06/image-218-300x169.png 300w" sizes="(max-width: 720px) 100vw, 720px" /></figure>
</div>


<h2 class="wp-block-heading">A little addition</h2>



<p>Let’s extend this calculator app to include a digital clock so that as we are performing calculations, we can be observing the time as well. Add this to the <code>index.html</code> file just after the <code>&lt;body></code> tag:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">{% block top %} {% include 'clock.html' %} {% endblock top %}</pre>



<p>I want to adhere to the principle of separation of concern. Hence, we will create a separate file for the clock and include it in the <code>index.html</code> file. Note the <code>block</code> keyword: <code>top</code>. It can be any word of your choice. I use it to indicate that I want the clock to appear at the top of the calculator.</p>



<p>Everything is going to be on a separate file. So, since we are still in the <code>index.html</code> file, include the link to the CSS and JavaScript files.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">&lt;link rel="stylesheet" href="{% static 'css/clock.css' %}">
&lt;script src="{% static 'js/clock.js' %}">&lt;/script>
</pre>



<p>Now, create a <code>clock.html</code> file inside the templates folder.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">{% block top %}

&lt;div id="MyClockDisplay" class="clock">&lt;/div>

{% endblock top %}
</pre>



<p>That’s all the markup we need. The rest will be done with JavaScript. Notice how we make sure this markup appears in the <code>index.html</code> file by wrapping the code inside the block statements.</p>



<p>Next is the CSS file. It will go inside the css folder.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">.clock {
  position: absolute;
  top: 10%;
  left: 45%;
  transform: translateX(-50%) translateY(-50%);
  color: #17d4fe;
  font-size: 60px;
  font-family: Times New Roman;
  letter-spacing: 7px;
}
</pre>



<p>We have explained some of these in the <a href="https://blog.finxter.com/how-i-created-a-calculator-app-using-django/" data-type="post" data-id="1377998" target="_blank" rel="noreferrer noopener">first part series</a> of this project article. We use the class <em>clock</em> to style the HTML element. The absolute position positions the element to its nearest ancestor. Otherwise, it positions the element to its initial block.</p>



<p>I use the top and left properties (10% away from the top edge and 45% away from the left edge) to make sure the digital clock rest on top of the calculator. The transform property also makes sure the element is centered horizontally and vertically.</p>



<p>Next is JavaScript. This will display the clock and make it tick.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">window.onload = function showTime(){
  let date = new Date(),
      h = date.getHours(),
      m = date.getMinutes(),
      s = date.getSeconds(),
      session = 'AM';

  if (h == 0){
    h = 12;
  }

  if (h > 12){
    h -=  12;
    session = 'PM';
  }

  h = (h &lt; 10) ? '0' + h : h;
  m = (m &lt; 10) ? '0' + m : m;
  s = (s &lt; 10) ? '0' + s : s;

  let time = h + ':' + m + ':' + s + ' ' + session;

  document.getElementById('MyClockDisplay').innerHTML = time;

  setTimeout(showTime, 1000);
}

showTime();
</pre>



<p>The <code>window.onload</code> makes sure that the page is loaded before any JavaScript code is run. Inside the <code>showTime()</code> function, we create a date object and using its get methods assign the seconds, minutes and hours in local time to a variable.</p>



<p>If the hour is equal to 0 (i.e., midnight), it is set to 12 to avoid the use of 24-hour time. If the hour is greater than 12 (i.e., in the afternoon), 12 is subtracted from it and the value of&nbsp;session initially set to ‘AM’&nbsp;is set to&nbsp;&#8216;PM&#8217;.</p>



<p>The function then checks if the hours, minutes, and seconds are less than 10. If they are, a&nbsp;&#8216;0&#8217;&nbsp;is added before them to ensure that they always have two digits. It then formats the time and stores it in a variable, time.</p>



<p>Using the <code>.innerHTML</code> of the element, we display the current time on the page. Finally, the function calls itself every 1 second to update the time.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img decoding="async" width="720" height="405" src="https://blog.finxter.com/wp-content/uploads/2023/06/image-219.png" alt="" class="wp-image-1455208" srcset="https://blog.finxter.com/wp-content/uploads/2023/06/image-219.png 720w, https://blog.finxter.com/wp-content/uploads/2023/06/image-219-300x169.png 300w" sizes="(max-width: 720px) 100vw, 720px" /></figure>
</div>


<h2 class="wp-block-heading">Conclusion</h2>



<p>This is the end of this project tutorial on creating a calculator app. The project focuses on how to use JavaScript to interact with the DOM. As an extension, we demonstrated how to add a digital clock to be displayed on the calculator app.</p>



<p>No doubt, you have learned a lot from this project tutorial. Use this knowledge to create your project using the Django framework. Be sure to check the source code on <a href="https://github.com/Jonaben1/django_calculator_app" data-type="URL" data-id="https://github.com/Jonaben1/django_calculator_app" target="_blank" rel="noreferrer noopener">my GitHub page</a>. You are welcome!</p>
<p>The post <a href="https://blog.finxter.com/how-i-created-a-calculator-app-using-django-part-3/">How I Created a Calculator App Using Django – Part 3</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How I Built a Virtual Assistant like Siri using ChatGPT Prompting (No Code!)</title>
		<link>https://blog.finxter.com/how-i-built-a-virtual-assistant-like-siri-using-chatgpt-prompting-no-code/</link>
		
		<dc:creator><![CDATA[Nikhilesh Talreja]]></dc:creator>
		<pubDate>Thu, 02 Mar 2023 18:48:03 +0000</pubDate>
				<category><![CDATA[App Development]]></category>
		<category><![CDATA[ChatGPT]]></category>
		<category><![CDATA[macOS]]></category>
		<category><![CDATA[OpenAI]]></category>
		<category><![CDATA[Prompt Engineering]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1177543</guid>

					<description><![CDATA[<p>Siri sucks. 😞 I am a Siri user, and Siri fails me more than it performs for me. It doesn&#8217;t understand the chain of commands. Project Idea: Recreate Siri Using ChatGPT This got me thinking, &#8220;What if I can repurpose ChatGPT to work like Siri?&#8221;. So before I tell you how the prompt looks like ... <a title="How I Built a Virtual Assistant like Siri using ChatGPT Prompting (No Code!)" class="read-more" href="https://blog.finxter.com/how-i-built-a-virtual-assistant-like-siri-using-chatgpt-prompting-no-code/" aria-label="Read more about How I Built a Virtual Assistant like Siri using ChatGPT Prompting (No Code!)">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/how-i-built-a-virtual-assistant-like-siri-using-chatgpt-prompting-no-code/">How I Built a Virtual Assistant like Siri using ChatGPT Prompting (No Code!)</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Siri sucks. <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f61e.png" alt="😞" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<p>I am a Siri user, and Siri fails me more than it performs for me. It doesn&#8217;t understand the chain of commands. </p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-4-3 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="How I Built a Virtual Assistant like Siri using ChatGPT Prompting (No Code!)" width="937" height="703" src="https://www.youtube.com/embed/o74q2Fa1IPs?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<h2 class="wp-block-heading">Project Idea: Recreate Siri Using ChatGPT</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="577" height="564" src="https://blog.finxter.com/wp-content/uploads/2023/03/image-10.png" alt="" class="wp-image-1177554" srcset="https://blog.finxter.com/wp-content/uploads/2023/03/image-10.png 577w, https://blog.finxter.com/wp-content/uploads/2023/03/image-10-300x293.png 300w" sizes="auto, (max-width: 577px) 100vw, 577px" /></figure>
</div>


<p>This got me thinking, <em>&#8220;What if I can repurpose ChatGPT to work like Siri?&#8221;</em>. So before I tell you how the prompt looks like this is what the chatbot can recognise in the most natural form:</p>



<ul class="wp-block-list">
<li>Increase volume</li>



<li>Decrease volume</li>



<li>Play movie</li>



<li>Pause or stop the movie</li>



<li>Open an app</li>



<li>Book a movie or movie ticket</li>



<li>Play song</li>



<li>Book a cab</li>



<li>Call someone</li>



<li>Set a reminder</li>



<li>Send a message</li>



<li>Set an alarm</li>



<li>Open a website</li>



<li>Get directions</li>



<li>Check the weather</li>
</ul>



<p>To trigger these commands, the user needed to begin the instruction with <strong><em><code>"Hey Nik"</code></em></strong>.</p>



<p>Let me begin by showing you the most complicated instruction it can handle</p>



<h2 class="wp-block-heading">Prompt First Trial &#8211; Not Perfect Yet</h2>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="756" src="https://blog.finxter.com/wp-content/uploads/2023/03/image-11-1024x756.png" alt="" class="wp-image-1177579" srcset="https://blog.finxter.com/wp-content/uploads/2023/03/image-11-1024x756.png 1024w, https://blog.finxter.com/wp-content/uploads/2023/03/image-11-300x222.png 300w, https://blog.finxter.com/wp-content/uploads/2023/03/image-11-768x567.png 768w, https://blog.finxter.com/wp-content/uploads/2023/03/image-11.png 1323w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<pre class="wp-block-preformatted"><code><strong>Nik</strong>: Assume it's sunny. Hey Nik check the weather for me and if it's sunny book a cab to go to the beach, play song california love by 2Pac

<strong>ChatGPT</strong>: Hey there! The weather today is sunny. Sure, I can check the weather for you and book a cab to the beach if it's sunny. Here are the commands:

[WEATHER] [OPENAPP UBER] [PLAYSONG CALIFORNIA LOVE BY 2PAC]</code></pre>



<p><strong>Nik</strong>: Assume it&#8217;s sunny. <em>Hey Nik check the weather for me and if it&#8217;s sunny book a cab to go to the beach, play song california love by 2Pac</em></p>



<p><strong>ChatGPT</strong>: Hey there! The weather today is sunny. Sure, I can check the weather for you and book a cab to the beach if it&#8217;s sunny. Here are the commands:</p>



<p>[WEATHER] [OPENAPP UBER] [PLAYSONG CALIFORNIA LOVE BY 2PAC]</p>



<p>Please note that the cab booking will not be completed as this is a simulated environment.</p>



<p>ChatGPT is not aware of my environment hence I had to tell them that it&#8217;s sunny. And then I start with <code>"Hey Nik..."</code><em>. </em>In contrast, Google &amp; Siri cannot handle this.</p>



<p>After a good deal of <a href="https://blog.finxter.com/i-created-a-chatgpt-powered-website-creator-with-chatgpt-heres-what-i-learned/" data-type="post" data-id="1158337" target="_blank" rel="noreferrer noopener">prompt engineering</a>, I came up with the following prompt that could be used by an app to not only detect user meaning but also respond accordingly &#8212; without needing to create a single line of code to accomplish this magic!</p>



<p>ChatGPT truly can be used as the <a href="https://blog.finxter.com/building-a-movie-recommendation-app-with-chatgpt/" data-type="post" data-id="1132950" target="_blank" rel="noreferrer noopener">heart</a> of many applications &#8212; not just to create them!</p>



<h2 class="wp-block-heading">Final Prompt</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="489" height="528" src="https://blog.finxter.com/wp-content/uploads/2023/03/image-12.png" alt="" class="wp-image-1177581" srcset="https://blog.finxter.com/wp-content/uploads/2023/03/image-12.png 489w, https://blog.finxter.com/wp-content/uploads/2023/03/image-12-278x300.png 278w" sizes="auto, (max-width: 489px) 100vw, 489px" /></figure>
</div>


<p>You can copy and paste this prompt in case you want to reuse it to build your own Siri replacement:</p>



<pre class="wp-block-preformatted"><code><strong>Nik</strong>: I want you to be an interactive chatbot that responds to predefined instructions. The instructions and their respective commands are:

Increase volume: [INCREASEVOLUME]

Decrease volume: [DECREASEVOLUME]

Play movie [MOVIE NAME]: [PLAYMOVIE [MOVIE NAME]]

Pause or stop the movie: [STOPMOVIE]

Open an app [APP NAME]: [OPENAPP [APP NAME]]

Book a movie or movie ticket: [OPENAPP BOOKMYSHOW]

Play song [song or artist name]: [PLAYSONG [song or artist name]]

Book a cab: [OPENAPP UBER]

Call someone [NAME]: [CALL [NAME]]

Set a reminder [TIME] [REMINDER]: [SETREMINDER [TIME] [REMINDER]]

Send a message [NAME] [MESSAGE]: [SENDMESSAGE [NAME] [MESSAGE]]

Set an alarm - [SETALARM [time]]

Open a website - [OPEN [website name]]

Get directions - [DIRECTIONTO [location]]

Check the weather - [WEATHER]

Here are some conditions to consider:

If the instruction includes a number or percentage when using INCREASEVOLUME or DECREASEVOLUME, append it to the command.

If the instruction includes the name of an app when using OPENAPP, append it to the command.

To trigger these commands, begin the instruction with "Hey Nik".

Please note that commands will be in square brackets, with spaces removed except for messages or names.

Your response should contain an acknowledgement in English and below it should be the sequence of commands.

After you display the commands do not print anything else.</code></pre>



<p>I came up with the following commands on the first attempt</p>



<ul class="wp-block-list">
<li>Increase volume: [INCREASE VOLUME]</li>



<li>Decrease volume: [DECREASEVOLUME]</li>



<li>Play movie [MOVIE NAME]: [PLAYMOVIE [MOVIE NAME]]</li>



<li>Pause or stop the movie: [STOPMOVIE]</li>



<li>Open an app [APP NAME]: [OPENAPP [APP NAME]]</li>



<li>Book a movie or movie ticket: [OPENAPP BOOKMYSHOW]</li>



<li>Play song [song or artist name]: [PLAYSONG [song or artist name]]</li>



<li>Book a cab: [OPENAPP UBER]</li>
</ul>



<p>After I perfected the results, I wanted to see if ChatGPT could add more commands, so I tried the following prompt</p>



<h2 class="wp-block-heading">Refinement Prompt</h2>



<pre class="wp-block-preformatted"><code><strong>Nik</strong>: Can you add more commands in the style given to the prompt. Take inspiration from "ok google" and "hey siri"

Please write in English language.

<strong>ChatGPT</strong>: Sure, I can add more commands in the style given to the prompt! Here are some additional commands you can use:

To set a reminder, say "Hey Nik, set a reminder for [time] to [task]". For example, "Hey Nik, set a reminder for 2pm to attend a meeting".

To check the weather, say "Hey Nik, what's the weather like today?".

To get directions, say "Hey Nik, how do I get to [location]?". For example, "Hey Nik, how do I get to Central Park?".

To set an alarm, say "Hey Nik, set an alarm for [time]". For example, "Hey Nik, set an alarm for 7am".

To send a message, say "Hey Nik, send a message to [contact name]". You will then be prompted to dictate the message and confirm before sending.

To open a website, say "Hey Nik, open [website name]". For example, "Hey Nik, open Google".

Remember to begin each command with "Hey Nik" for the chatbot to respond. I hope these additional commands are helpful!

<strong>Nik</strong>:Ok now generate the original prompt with the newly added commands

Please write in English language.</code></pre>



<h2 class="wp-block-heading">My Personal Considerations and Findings Using This Prompt</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="679" height="429" src="https://blog.finxter.com/wp-content/uploads/2023/03/image-13.png" alt="" class="wp-image-1177583" srcset="https://blog.finxter.com/wp-content/uploads/2023/03/image-13.png 679w, https://blog.finxter.com/wp-content/uploads/2023/03/image-13-300x190.png 300w" sizes="auto, (max-width: 679px) 100vw, 679px" /></figure>
</div>


<p>I am impressed with ChatGPT&#8217;s ability to generate a more user-friendly and straightforward set of commands. And it also kept modifying my original prompt to include these commands.&nbsp; </p>



<p>But, I realized that there were some conditions that I needed to consider, such as:</p>



<ul class="wp-block-list">
<li>If the instruction includes a number or percentage when using INCREASEVOLUME or DECREASEVOLUME, append it to the command.</li>



<li>If the instruction includes the name of an app when using OPENAPP, append it to the command.</li>
</ul>



<p>With these conditions in mind, I combined the original set of commands with the new commands generated by ChatGPT and added the necessary conditions to create a more comprehensive and user-friendly prompt.</p>



<p>As I developed the chatbot, I discovered that one of its most significant advantages over Siri was its ability to handle an unlimited set of inputs. Siri, on the other hand, works with one command at a time, which can be limiting for users who want to execute multiple tasks in one go.</p>



<p>Here are some examples of user inputs and their respective responses:</p>



<pre class="wp-block-preformatted"><code><strong>User Input</strong>: Hey Nik, play movie The Shawshank Redemption

<strong>Response</strong>: [PLAYMOVIE The Shawshank Redemption]

<strong>User Input</strong>: Hey Nik, increase volume by 50 percent

<strong>Response</strong>: [INCREASEVOLUME 50 percent]</code>
<code>
<strong>User Input</strong>: Hey Nik, send a message to John saying I will be there in 10 minutes </code>

<code><strong>Response</strong>: [SENDMESSAGE John I will be there in 10 minutes]

<strong>User Input</strong>: Hey Nik, what is the weather like in New York?

<strong>Response</strong>: [WEATHER New York]</code></pre>



<p>Here is an example of the user input and response for the &#8220;play song&#8221; command:</p>



<pre class="wp-block-preformatted"><code><strong>User input</strong>: Hey Nik, play song Shape of You by Ed Sheeran

<strong>Response</strong>: Playing Shape of You by Ed Sheeran

<strong>Command</strong>: [PLAYSONG Shape of You by Ed Sheeran]</code></pre>



<p>And here is an example of the user input and response for the <code>"open an app"</code> command:</p>



<pre class="wp-block-preformatted"><code><strong>User input</strong>: Hey Nik, open app Netflix

<strong>Response</strong>: Opening Netflix

<strong>Command</strong>: [OPEN APP NETFLIX]</code></pre>



<h2 class="wp-block-heading">How to Deploy This</h2>



<p>To deploy it as an app, you can use the ChatGPT API + Promptable + Any No Code App Builder, the app can be deployed on iPhone, but there are many permissions that need to be worked out. </p>



<p>A similar version of this may work on Android as it is more open.</p>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f449.png" alt="👉" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/building-a-movie-recommendation-app-with-chatgpt/" data-type="URL" data-id="https://blog.finxter.com/building-a-movie-recommendation-app-with-chatgpt/" target="_blank" rel="noreferrer noopener">ChatGPT at the Heart – Building a Movie Recommendation Python Web App</a></p>
<p>The post <a href="https://blog.finxter.com/how-i-built-a-virtual-assistant-like-siri-using-chatgpt-prompting-no-code/">How I Built a Virtual Assistant like Siri using ChatGPT Prompting (No Code!)</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How I Created a Short Quiz App with Kivy</title>
		<link>https://blog.finxter.com/how-i-created-a-short-quiz-app-with-kivy/</link>
		
		<dc:creator><![CDATA[Heshna Bhagawan]]></dc:creator>
		<pubDate>Tue, 28 Feb 2023 13:38:12 +0000</pubDate>
				<category><![CDATA[App Development]]></category>
		<category><![CDATA[GUI]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Web Development]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1170134</guid>

					<description><![CDATA[<p>Building a quiz app is simple with Kivy. 💡 Kivy is a free, open-source library that made the development of the quiz app simple. The Kivy methods save us a ton of coding time. In this article, I created a short quiz app that helps you decide what to eat to demonstrate how Kivy works. ... <a title="How I Created a Short Quiz App with Kivy" class="read-more" href="https://blog.finxter.com/how-i-created-a-short-quiz-app-with-kivy/" aria-label="Read more about How I Created a Short Quiz App with Kivy">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/how-i-created-a-short-quiz-app-with-kivy/">How I Created a Short Quiz App with Kivy</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Building a quiz app is simple with Kivy. </p>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Kivy</strong> is a free, open-source library that made the development of the quiz app simple. The Kivy methods save us a ton of coding time.</p>



<p>In this article, I created a short quiz app that helps you decide what to eat to demonstrate how Kivy works. In addition, the quiz app enhanced my coding skills with classes and functions, especially with repeating codes.</p>



<p>There are three layouts for the quiz app.</p>



<ol class="wp-block-list" type="1" start="1">
<li>Home Screen: </li>
</ol>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="240" height="206" src="https://blog.finxter.com/wp-content/uploads/2023/02/image-404.png" alt="" class="wp-image-1170136"/></figure>
</div>


<ol class="wp-block-list" type="1" start="2">
<li>Question: </li>
</ol>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="239" height="206" src="https://blog.finxter.com/wp-content/uploads/2023/02/image-405.png" alt="" class="wp-image-1170137"/></figure>
</div>


<ol class="wp-block-list" type="1" start="3">
<li>Answer (varies)<br></li>
</ol>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="240" height="206" src="https://blog.finxter.com/wp-content/uploads/2023/02/image-406.png" alt="" class="wp-image-1170138"/></figure>
</div>


<p>You can find an image <a href="https://www.pexels.com/" target="_blank" rel="noreferrer noopener">here</a> or download mine from my <a href="https://github.com/heshnaB/How-I-Created-a-Short-Quiz-App-with-KIVY">GitHub profile</a>. The only exterior file you need is an image, and make sure you save the image under the same file as your code. Download the <a href="https://github.com/heshnaB/How-I-Created-a-Short-Quiz-App-with-KIVY">completed code</a> to check your work.</p>



<p>Here we go!</p>



<h2 class="wp-block-heading">Step 1: Install the library </h2>



<p>Install the library by entering <code>pip install kivy</code><em> </em>in the command prompt.</p>



<h2 class="wp-block-heading">Step 2: Import the following libraries</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.image import Image
from kivy.uix.button import Button
from kivy.graphics import Color, Rectangle
from kivy.uix.floatlayout import FloatLayout
import random
</pre>



<h2 class="wp-block-heading">Step 3: Create a home screen for the app and initiate the class.</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">class Home(FloatLayout):
 
    def __init__(self, **kwargs):
        super(Home, self).__init__(**kwargs)
    	self.main_home()
</pre>



<p>Now we can create everything we need inside the Home() class.</p>



<h3 class="wp-block-heading">Create the logo() and add_label() functions</h3>



<p>We can use the kivy method below to add widgets, including images, labels, and buttons.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">self.add_widget()</pre>



<p>We can create the logo using the kivy method shown below. Then, insert it inside the <code>add_widget()</code> kivy method.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Image(source="image_name.type",
      size_hint = (0.3, 0.7), # Size of the image
      pos_hint={'center_x': 0.5, 'y': 0.355}) # position of the image</pre>



<p>For the label, we can use the kivy method below to add a label and insert it inside the <code>add_widget()</code> kivy method.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Label(text = string, # string is from parameter of function
      font_size = 45, # Size of text
      color = "#FFFFFF", # Color of text
      bold = True, # Makes the test bold
      pos_hint={'x': 0.000000001, 'center_y': 0.4}) # Position of label</pre>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>** Since one function creates every label in the app, it needs a string parameter so the user can change the text.**</strong></p>



<h3 class="wp-block-heading">Create the add_button() function</h3>



<p>We will use a different approach when adding the buttons to prevent repeating lines of code. To do that, we must <strong>create a new variable for every button</strong>, then <strong>return the variable</strong>. The kivy method for creating a button is:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">self.b = Button(text = string, # Text displayed on the button
            size_hint = size, # Size of the button
            bold = True, # Makes text bold
            font_size = 30, # font size
            pos_hint={'center_x': 0.5, 'y': y},) # position of the text
</pre>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Since we use one function to create all buttons, we can use parameters to change the variables. The function contains four parameters: <code>self</code>, <code>string</code>, <code>size</code>, and <code>y</code>. </strong></p>



<ul class="wp-block-list">
<li>The <code>string</code> represents the text on the button. </li>



<li>The <code>size</code> determines the size of the button. </li>



<li>Then, we have the <code>y</code> parameter, which describes the y position of the button.</li>
</ul>



<p>For example, if we include two buttons on the screen that are the same size, the buttons will overlap. So, we can either change the <code>y</code> or the <code>x</code> value. Thus when we change the <code>y</code> value, the buttons won&#8217;t overlap.</p>



<h3 class="wp-block-heading">Create the reset() function.</h3>



<p>The reset function only requires two lines of code.</p>



<p>The first line is for using the kivy method to erase all widgets from the app:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">self.clear_widgets()</pre>



<p>The second line calls the <code>logo()</code> to create and display it:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">self.logo() </pre>



<h3 class="wp-block-heading">Create the main_home() function</h3>



<p>The <code>main_home()</code> consists of calling functions and using kivy methods. We can start by using the kivy method to clear all widgets.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">self.clear_widgets()</pre>



<p>Call the <code>add_label()</code> function with the desired question in the parameter.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">self.add_label("Are you ready to decide what to eat?")</pre>



<p>To create the button on the home screen, we must call the <code>add_button()</code> function. Then use the kivy method to add the button to the app.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">self.button = self.add_button("Yes, I'm starving!", (0.9, 0.185), 0.1)
self.add_widget(self.button)</pre>



<p>Then, we call the logo function to display the logo.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">self.logo()</pre>



<h2 class="wp-block-heading">Step 4: Create the main quiz app and initiate the class.</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">class QuizApp(App):
   
    def build(self):
        self.root = root = Home()
  self.start(root)
</pre>



<p>Now we can create everything we need for the <code>QuizApp(App)</code> class.</p>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>** Every function (except for the <code>__init__</code> function) inside this class needs the root parameter. **</strong></p>



<p>For the class <code>QuizApp(App)</code>, “Quiz” is the title for the tab.</p>



<h3 class="wp-block-heading">Create the start() function.</h3>



<p>The <code>start()</code> function will bind the button on the home screen so that the user can begin the quiz when they press it.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def start(self, root):
self.root.button.bind(on_press= self.beginQ)
</pre>



<h3 class="wp-block-heading">Create the return_home() function</h3>



<p>This function should return to the home screen after the user presses the restart button.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">self.root.main_home()     
self.start(root)</pre>



<p>Since there are only two answers to the quiz, create a function for each answer.</p>



<p>Each function will return the random choice of the list of the chosen places.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">self.display_result(root, f"Get {random.choice(['KFC', 'Wendy', 'Popeyes'])}!")</pre>



<h3 class="wp-block-heading">Create a function to display the result called display_result(self, root, result)</h3>



<p>We can start by calling the <code>reset()</code> function from the <code>Home()</code> class.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">self.root.reset()</pre>



<p>Then call the <code>add_label(result)</code> to add the result to the app.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">self.root.add_label(result)</pre>



<p>The final step is to create and display a <code>Restart</code> button and bind the button to return to the home screen.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">self.restart_but = self.root.add_button("Restart", (0.9, 0.1), 0.18)
self.root.add_widget(self.restart_but)
self.restart_but.bind(on_press= self.return_home)
</pre>



<h3 class="wp-block-heading">Create the begin quiz function</h3>



<p>Call the <code>reset()</code> function from the <code>Home()</code> class.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">self.root.reset() </pre>



<p>Add the label for the questions and create the buttons for both answers.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">self.root.add_label("Do you feel like driving?")
self.yes = self.root.add_button("Sure", (0.9, 0.1), 0.21)
self.no = self.root.add_button("Absolutely not!", (0.9, 0.1), 0.1)
</pre>



<p>Display the buttons on the app.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">self.root.add_widget(self.yes)
self.root.add_widget(self.no)
</pre>



<p>Bind both answer buttons to call the two option functions you created earlier.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">self.yes.bind(on_press= self.option_y)
self.no.bind(on_press= self.option_n)
</pre>



<h2 class="wp-block-heading"><u>References</u></h2>



<p>Doc for Kivy:<a href="https://kivy.org/doc/stable/guide/widgets.html"> </a><a href="https://kivy.org/doc/stable/guide/widgets.html" target="_blank" rel="noreferrer noopener">https://kivy.org/doc/stable/guide/widgets.html</a></p>



<p>Another app example:<a href="https://www.section.io/engineering-education/kivy-python-first-app/"> </a><a href="https://www.section.io/engineering-education/kivy-python-first-app/" target="_blank" rel="noreferrer noopener">https://www.section.io/engineering-education/kivy-python-first-app/</a> &#8211; Import the datetime module for the code to work.</p>



<p><a href="https://www.simplikivyapp.com/" target="_blank" rel="noreferrer noopener">https://www.simplikivyapp.com/</a>  &#8211; Better for a quiz with more than one question.</p>
<p>The post <a href="https://blog.finxter.com/how-i-created-a-short-quiz-app-with-kivy/">How I Created a Short Quiz App with Kivy</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How I Created a Football Prediction App on Streamlit</title>
		<link>https://blog.finxter.com/how-i-created-a-football-prediction-app-on-streamlit/</link>
		
		<dc:creator><![CDATA[Jonathan Okah]]></dc:creator>
		<pubDate>Sun, 05 Feb 2023 16:34:02 +0000</pubDate>
				<category><![CDATA[App Development]]></category>
		<category><![CDATA[Data Science]]></category>
		<category><![CDATA[Math]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Statistics]]></category>
		<category><![CDATA[Streamlit]]></category>
		<category><![CDATA[Web Development]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1111357</guid>

					<description><![CDATA[<p>This tutorial shows you how I created a model to predict football results using Poisson distribution. You&#8217;ll learn how I designed an interactive dashboard on Streamlit where our users can select a team and get to know the odds of a home win, draw, or away win. Here&#8217;s a live demo of using the app ... <a title="How I Created a Football Prediction App on Streamlit" class="read-more" href="https://blog.finxter.com/how-i-created-a-football-prediction-app-on-streamlit/" aria-label="Read more about How I Created a Football Prediction App on Streamlit">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/how-i-created-a-football-prediction-app-on-streamlit/">How I Created a Football Prediction App on Streamlit</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>This tutorial shows you how I created a model to predict football results using Poisson distribution. You&#8217;ll learn how I designed an interactive dashboard on Streamlit where our users can select a team and get to know the odds of a home win, draw, or away win.</p>



<p>Here&#8217;s a live demo of using the app to predict different games, such as <strong>Arsenal vs. Southampton</strong>:</p>



<figure class="wp-block-video"><video autoplay controls src="https://blog.finxter.com/wp-content/uploads/2023/02/streamlit-app-2023-02-05-18-02-19.webm"></video></figure>



<div class="wp-block-buttons is-content-justification-center is-layout-flex wp-container-core-buttons-is-layout-16018d1d wp-block-buttons-is-layout-flex">
<div class="wp-block-button has-custom-width wp-block-button__width-75"><a class="wp-block-button__link wp-element-button" href="https://jonaben1-football-prediction-app-nlr1w7.streamlit.app/" target="_blank" rel="noreferrer noopener">Try The Live App</a></div>
</div>



<div style="height:100px" aria-hidden="true" class="wp-block-spacer"></div>



<p>The purpose of this tutorial is purely educational, to introduce you to some concepts in Python. Using this app other than what it is stated for, for example, to compare bookmakers’ odds, and place a stake, is entirely at your own risk.</p>



<p>We will be predicting the English Premier League as it’s the most-watched sport in the world.</p>



<h2 class="wp-block-heading">Poisson Distribution</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="582" height="869" src="https://blog.finxter.com/wp-content/uploads/2023/02/image-61.png" alt="" class="wp-image-1111471" srcset="https://blog.finxter.com/wp-content/uploads/2023/02/image-61.png 582w, https://blog.finxter.com/wp-content/uploads/2023/02/image-61-201x300.png 201w" sizes="auto, (max-width: 582px) 100vw, 582px" /></figure>
</div>


<p>Speaking in a football context, how likely will a match result in a win or draw within 90 minutes of gameplay? If it’s to result in a win, what are the chances of a team scoring 3 goals with a clean sheet? </p>



<p>That is exactly what a Poisson distribution tends to answer. </p>



<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2139.png" alt="ℹ" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Info</strong>: A Poisson distribution is a type of probability distribution that helps to calculate the chance of a certain number of events happening in a given space or time period. It considers the average rate of these events and assumes they are independent of each other.</p>



<p>So, here are our assumptions:</p>



<ol class="wp-block-list" type="1">
<li><strong>Two or more events occurring are independent of each other.</strong> This means that if Tottenham FC were to pack the box, it does not prevent Manchester City from scoring against them in a match.</li>



<li><strong>Two events cannot occur simultaneously at the same time.</strong> This means that if Chelsea were to score a goal, it would not result in an instant equalizer.</li>



<li><strong>The number of events occurring in a given time interval can be counted.</strong> This means we can precisely say that Liverpool will commit a painful mistake that will gift their rival the trophy.</li>
</ol>



<p>As we can see from the above examples, the assumptions are not always the case in real-life situations, thus rendering the Poisson distribution as pointless as it appears to offer anything useful. Despite the inherent limitations, we can still draw insight from this model to see if its features can form a basis for further research for any predictive football model.</p>



<p>Sparing you with the theories and mathematical formula, we get down to business to see how we can implement the Poisson distribution using Python.</p>



<h2 class="wp-block-heading">The Dataset</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="733" height="423" src="https://blog.finxter.com/wp-content/uploads/2023/02/image-62.png" alt="" class="wp-image-1111474" srcset="https://blog.finxter.com/wp-content/uploads/2023/02/image-62.png 733w, https://blog.finxter.com/wp-content/uploads/2023/02/image-62-300x173.png 300w" sizes="auto, (max-width: 733px) 100vw, 733px" /></figure>
</div>


<p>We will import match results from the English Premier League (EPL). There are various sources to get this data, Kaggle<sup>1</sup>, GitHub<sup>2</sup>, and football API<sup>3</sup>. But we will source our data from football-data.co.uk<sup>4</sup>.</p>



<p><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/26bd.png" alt="⚽" class="wp-smiley" style="height: 1em; max-height: 1em;" /> At the point of writing, the EPL has gone halfway. It is now becoming more interesting than when it commenced. Arsenal’s dramatic resurgence means they are seen by many as favorites to win the crown. Manchester City are relentlessly in hot pursuit, especially with the arrival of Erling Haaland. Newcastle have become a surprising contender for the title.</p>



<p>On the other hand, Chelsea is nowhere to be found in the Champions League places, and so is Liverpool. These indicate that football is unpredictable. Hence, using the past to predict the future may not yield the expected results.</p>



<p>Furthermore, some Premier League clubs have undergone dramatic changes. From the change of ownership to managerial change to the transfer of players in and out of the competition. All these have made football prediction a very difficult one.</p>



<p>For these and other reasons, I used only the data from the current season to train the model.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import pandas as pd
data = pd.read_csv('https://www.football-data.co.uk/mmz4281/2223/E0.csv')
print(data.shape)
# (199, 106)</pre>



<p>We will not save the data. It is going to be in such a way that we will be getting real-time updates to make the prediction. The data has 106 columns, but we are only interested in 4 columns. </p>



<p>Let’s select and rename them.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">epl = data[['HomeTeam', 'AwayTeam','FTHG', 'FTAG']]
epl = epl.rename(columns={'FTHG': 'HomeGoals', 'FTAG':'AwayGoals'})
print(epl.head())</pre>



<p>Output:</p>



<pre class="wp-block-preformatted has-medium-font-size"><code>         HomeTeam       AwayTeam    HomeGoals  AwayGoals
0     Crystal Palace        Arsenal               0            2
1          Fulham           Liverpool              2             2
2     Bournemouth    Aston Villa              2             0
3           Leeds                 Wolves              2            1
4       Newcastle        Nott'm Forest          2             0</code></pre>



<p>We want to compare our predictions with live results. So, we will reserve the last 20 rows representing two game weeks. Then we see if we can draw insights from the home and away goals.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">test = epl[-20:]
epl = epl[:-20]
print(epl[['HomeGoals', 'AwayGoals']].mean())</pre>



<p>Output:</p>



<pre class="wp-block-preformatted"><code>HomeGoals    1.631285
AwayGoals    1.217877
dtype: float64</code></pre>



<p>We now have 179 rows and 4 columns. You can see that, on average, the home team scores more goals than the away team but only by a small margin. </p>



<p>This information is vital. If an event follows a Poisson distribution, the mean also known as <em>lambda;</em> is the only thing we need to know to find the probability of that event occurring a certain number of times.</p>



<p>A <strong>skellam distribution</strong> is the difference between two means of a Poisson distribution (the mean of the home and away goals in our case). </p>



<p>We can then calculate the probability mass function (PMF) for a skellam distribution using the mean goals to determine the probability of a draw or a win between home and away teams.</p>



<p>from scipy.stats import skellam, poisson</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from scipy.stats import skellam, poisson

# probability of a draw
skellam.pmf(0.0, epl.HomeGoals.mean(), epl.AwayGoals.mean())
# Output: 0.24434197359198495

# probability of a win by one goal
skellam.pmf(1.0, epl.HomeGoals.mean(), epl.AwayGoals.mean())
# Output: 0.22500333061251618
</pre>



<p>The result shows that the probability of a draw in EPL is 24% while a win by one goal is 25%. Remember, this is a combination of all the matches. We will then follow this process to model specific matches.</p>



<h2 class="wp-block-heading">Data Preparation</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="582" height="870" src="https://blog.finxter.com/wp-content/uploads/2023/02/image-63.png" alt="" class="wp-image-1111475" srcset="https://blog.finxter.com/wp-content/uploads/2023/02/image-63.png 582w, https://blog.finxter.com/wp-content/uploads/2023/02/image-63-201x300.png 201w" sizes="auto, (max-width: 582px) 100vw, 582px" /></figure>
</div>


<p>Before we begin building the model, let’s first prepare our data, making it suitable for modeling.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">home = epl.iloc[:,0:3].assign(home=1).rename(columns={'HomeTeam':'team', 'AwayTeam':'opponent', 'HomeGoals':'goals'})
away = epl.iloc[:, [1, 0, 3]].assign(home=0).rename(columns={'AwayTeam': 'team', 'HomeTeam': 'opponent', 'AwayGoals': 'goals'})
df = pd.concat([home, away])
print(df)</pre>



<p>Output:</p>



<pre class="wp-block-preformatted"><code>               team          opponent        goals      home
0    Crystal Palace         Arsenal          0            1
1            Fulham       Liverpool           2            1
2       Bournemouth     Aston Villa      2            1
3             Leeds          Wolves              2            1
4         Newcastle   Nott'm Forest        2            1
..              ...             ...    ...   ...
174       Tottenham  Crystal Palace      4            0
175        Man City         Chelsea          1            0
176         Chelsea          Fulham          1            0
177           Leeds     Aston Villa            1           0
178        Man City      Man United       1            0

[358 rows x 4 columns]</code>
</pre>



<p>We wanted to merge everything that represents home and away into a single column. </p>



<p>So, what we did was to filter them out, gave them similar names, then, concatenate them. </p>



<p>To differentiate away goals from home goals, we created a column and assigned 1 to represent home goals and 0 for away goals. Our data is now suitable for modeling.</p>



<h2 class="wp-block-heading">The Generalized Linear Model</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="740" height="412" src="https://blog.finxter.com/wp-content/uploads/2023/02/image-64.png" alt="" class="wp-image-1111476" srcset="https://blog.finxter.com/wp-content/uploads/2023/02/image-64.png 740w, https://blog.finxter.com/wp-content/uploads/2023/02/image-64-300x167.png 300w" sizes="auto, (max-width: 740px) 100vw, 740px" /></figure>
</div>


<p>The generalized linear model is a family of models in which <a rel="noreferrer noopener" href="https://blog.finxter.com/logistic-regression-in-one-line-python/" data-type="post" data-id="2537" target="_blank">logistic regression</a> and <a rel="noreferrer noopener" href="https://blog.finxter.com/python-linear-regression-1-liner/" data-type="post" data-id="1920" target="_blank">linear regression</a> models we use in machine learning are included. It is used to model different types of data. Poisson regression as part of the generalized linear model is used to analyze count data. </p>



<p>Remember, we are dealing with count data. For example, the number of goals per match. Since count data follows a Poisson distribution, we will be using Poisson regression to build our model.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import statsmodels.api as sm
import statsmodels.formula.api as smf

formula = 'goals ~ team + opponent + home'
model = smf.glm(formula=formula, data=df, family=sm.families.Poisson()).fit()
print(model.summary())
</pre>



<p>We imported <code><a href="https://blog.finxter.com/logistic-regression-scikit-learn-vs-statsmodels/" data-type="post" data-id="22984" target="_blank" rel="noreferrer noopener">statsmodels</a></code> library to help us build the model.</p>



<p>The formula to predict the number of goals is defined as the combination of the team, opponent, and whether it is home or away goals. Take a look at the summary. The result of the <em>Generalized Linear Model</em> contains so much that we cannot explain all of them in this article. </p>



<p>But let’s focus on the <code>coef</code> column.</p>



<p>As you already know, the team side means a home match, and the opponent side means an away match. If the value is closer to 0, it indicates the possibility of a draw. If the value of the home side is positive, it means the team has a strong attacking ability. Teams with a negative value indicate that they have a not-so-strong attacking ability.</p>



<p>Having trained the model, we can now use it to make predictions. Let’s create a function to do so.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def predict_match(model, homeTeam, awayTeam, max_goals=10):
    home_goals = model.predict(pd.DataFrame(data={'team': homeTeam,
                                                  'opponent':awayTeam,
                                                  'home': 1},
                                            index=[1])).values[0]
    away_goals = model.predict(pd.DataFrame(data={'team': awayTeam,
                                                  'opponent': homeTeam,
                                                  'home':0},
                                            index=[1])).values[0]
    pred = [[poisson.pmf(i, team_avg) for i in range(0, max_goals+1)] for team_avg in [home_goals, away_goals]]
    return(np.outer(np.array(pred[0]), np.array(pred[1])))
</pre>



<p>The function has four parameters: </p>



<ul class="wp-block-list">
<li>the Poisson model to be used to make the predictions, </li>



<li>the home team, </li>



<li>the away team, and </li>



<li>the maximum number of goals. </li>
</ul>



<p>We set it to 10 as the highest a team can score within 90 minutes of gameplay. Remember, the formula combines all these to predict the number of goals.</p>



<p>We looped over the predicted number of home and away goals. We also looped over the maximum goals. </p>



<p>In each iteration, we calculate the probability mass function of the Poisson distribution. This tells us the probability of a team scoring several goals. Taking the outer product of the two sets of probabilities, the function created and returned a matrix.</p>



<p>Let me assume Arsenal and Manchester City are to face each other at Emirate Stadium and you want to make the prediction.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">print(model.predict(pd.DataFrame(data={'team': 'Arsenal', 'opponent': 'Man City', 'home':1}, index=[1])))</pre>



<p>Output:</p>



<pre class="wp-block-preformatted"><code>1.   2.026391
dtype: float64
</code></pre>



<p>The model is predicting Arsenal to score two goals…</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">print(model.predict(pd.DataFrame(data={'team': 'Man City', 'opponent': 'Arsenal', 'home':0}, index=[1])))</pre>



<p>Output:</p>



<pre class="wp-block-preformatted"><code>1    1.284658
dtype: float64</code></pre>



<p>… and Manchester City to score 1.23 goals, approximately 3 goals in the match.</p>



<p>The model roughly predicts a 2-1 home win for Arsenal. </p>



<p>Now that the three members of the formula are complete, we can feed it to the <code>predict_match()</code> function to get the odds of a home win, away win, and a draw.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">ars_man = predict_match(model, 'Arsenal', 'Man City', max_goals=3)</pre>



<p>Result:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">array([[0.03647786, 0.04686159, 0.03010057, 0.01288965],
       [0.07391843, 0.09495992, 0.06099553, 0.02611947],
       [0.07489383, 0.09621298, 0.06180041, 0.02646414],
       [0.05058807, 0.06498838, 0.04174394, 0.01787557]])
</pre>



<p>The rows and columns represent Arsenal and Manchester City’s chances of scoring a particular goal respectively. </p>



<p>The diagonal entries represent a draw since it is where both teams score the same number of goals. Below the line (the lower triangle of the array found using <code>numpy.tril</code>) is Arsenal’s victory, and above (the upper triangle of the array found using <code>numpy.triu</code>) is Man City’s.</p>



<p>Let’s automate this with Python.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import numpy as np

# victory for Arsenal
np.sum(np.tril(ars¬_man, -1)) * 100
# 40.23456259724963

# victory for Man City
np.sum(np.triu(ars_man, 1)) * 100
# 20.34309498981432

# a draw
np.sum(np.diag(ars_man)) * 100
# 21.111376045176485
</pre>



<p></p>



<p>Our model tells us that Arsenal has a 40% chance of winning which is much more than Man City’s odds at 21%. That makes the earlier prediction of 2-1 correspond accordingly.</p>



<p>Feel free to compare your prediction with the test data and see how far or close you are to predict live results. We can now proceed to create a football prediction app on Streamlit. </p>



<p><a href="https://github.com/finxter/Football_Prediction" data-type="URL" data-id="https://github.com/finxter/Football_Prediction" target="_blank" rel="noreferrer noopener">Check my GitHub page</a> to see the full script.</p>



<p><a href="https://jonaben1-football-prediction-app-nlr1w7.streamlit.app/" data-type="URL" data-id="https://jonaben1-football-prediction-app-nlr1w7.streamlit.app/" target="_blank" rel="noreferrer noopener">Check out the live demo app</a> to play with it!</p>



<h2 class="wp-block-heading">Streamlit Dashboard</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="733" height="541" src="https://blog.finxter.com/wp-content/uploads/2023/02/image-65.png" alt="" class="wp-image-1111479" srcset="https://blog.finxter.com/wp-content/uploads/2023/02/image-65.png 733w, https://blog.finxter.com/wp-content/uploads/2023/02/image-65-300x221.png 300w" sizes="auto, (max-width: 733px) 100vw, 733px" /></figure>
</div>


<p>In the file named <code>app.py</code>, you will see how I used <code>st.sidebar.selectbox</code> to display a list of all the clubs in the Premier League. This will appear on the left-hand side. Since the names of the club appeared twice, I made sure that only one was selected for prediction.</p>



<p>The rest of the code has been explained. If the button is pressed, the <code>get_scores()</code> function is executed and displays the prediction results.</p>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f449.png" alt="👉" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/learning-streamlits-buttons-features/" data-type="post" data-id="462652" target="_blank" rel="noreferrer noopener">Streamlit Button &#8212; Ultimate Guide with Video</a></p>



<p>Notice that I didn’t save the dataset. </p>



<p>Whenever the app is opened, it will get real-time updates that will help it train the model for the next prediction. Also, since every code is not wrapped in a function, the order is important. </p>



<p>That is why the <code>get_scores()</code> function was called last. Of course, there are many ways to write the code and get the same result.</p>



<h2 class="wp-block-heading">A Word of Caution</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="728" height="482" src="https://blog.finxter.com/wp-content/uploads/2023/02/image-66.png" alt="" class="wp-image-1111483" srcset="https://blog.finxter.com/wp-content/uploads/2023/02/image-66.png 728w, https://blog.finxter.com/wp-content/uploads/2023/02/image-66-300x199.png 300w" sizes="auto, (max-width: 728px) 100vw, 728px" /></figure>
</div>


<p>I clarified to you from the beginning that this article is for educational purposes only and should not be used for anything else. </p>



<p>Many things can impact the result of a match that the model didn’t put into consideration. Change of a manager, injury, refereeing decision, player fitness, team morale, weather condition, plus the limitations of Poisson distribution used to make these predictions. </p>



<p>Of course, no model is perfect. So, use responsibly.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://jonaben1-football-prediction-app-nlr1w7.streamlit.app/" target="_blank" rel="noreferrer noopener"><img loading="lazy" decoding="async" width="725" height="408" src="https://blog.finxter.com/wp-content/uploads/2023/02/image-58.png" alt="" class="wp-image-1111393" srcset="https://blog.finxter.com/wp-content/uploads/2023/02/image-58.png 725w, https://blog.finxter.com/wp-content/uploads/2023/02/image-58-300x169.png 300w" sizes="auto, (max-width: 725px) 100vw, 725px" /></a></figure>
</div>


<h2 class="wp-block-heading">Prediction Result</h2>



<p>I deployed the app on Streamlit Cloud and tried to predict upcoming matches in the English Premier League. </p>



<p>The results were amazing. You can give it a try. I don’t expect the Premier League clubs to get those scores. Predicted result is not always the same as actual result. But I will rate the performance of our model if some, if not all, the home wins, draws, or away wins were predicted correctly.</p>



<h2 class="wp-block-heading">Conclusion</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="721" height="880" src="https://blog.finxter.com/wp-content/uploads/2023/02/image-67.png" alt="" class="wp-image-1111484" srcset="https://blog.finxter.com/wp-content/uploads/2023/02/image-67.png 721w, https://blog.finxter.com/wp-content/uploads/2023/02/image-67-246x300.png 246w" sizes="auto, (max-width: 721px) 100vw, 721px" /></figure>
</div>


<p>We have learned a lot today, ranging from data manipulation to model building. </p>



<p>You learned how to make football predictions using Poisson distribution. I did my best to make the explanation simple by leaving the mathematical theories and calculations behind. If you want to know more, you have the internet at your disposal. Alright, have a nice day.</p>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f449.png" alt="👉" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/how-i-built-a-house-price-prediction-app-using-streamlit/" data-type="post" data-id="1104457" target="_blank" rel="noreferrer noopener">How I Built a House Price Prediction App Using Streamlit</a></p>



<h2 class="wp-block-heading">Resources</h2>



<ol class="wp-block-list" type="1">
<li><a href="https://www.kaggle.com/hugomathien/soccer" target="_blank" rel="noreferrer noopener"><sup>https://www.kaggle.com/hugomathien/soccer</sup></a></li>



<li><a href="https://github.com/jalapic/engsoccerdata" target="_blank" rel="noreferrer noopener"><sup>https://github.com/jalapic/engsoccerdata</sup></a></li>



<li><a href="http://api.football-data.org/index" target="_blank" rel="noreferrer noopener"><sup>http://api.football-data.org/index</sup></a></li>



<li><a href="http://www.football-data.co.uk/englandm.php" target="_blank" rel="noreferrer noopener"><sup>http://www.football-data.co.uk/englandm.php</sup></a></li>



<li><a href="https://jonaben1-football-prediction-app-nlr1w7.streamlit.app" target="_blank" rel="noreferrer noopener"><sup>https://jonaben1-football-prediction-app-nlr1w7.streamlit.app</sup></a></li>
</ol>
<p>The post <a href="https://blog.finxter.com/how-i-created-a-football-prediction-app-on-streamlit/">How I Created a Football Prediction App on Streamlit</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		<enclosure url="https://blog.finxter.com/wp-content/uploads/2023/02/streamlit-app-2023-02-05-18-02-19.webm" length="4794020" type="video/webm" />

			</item>
		<item>
		<title>20 Real-Life Skills You Need as a UI Developer in 2023</title>
		<link>https://blog.finxter.com/real-life-skills-you-need-as-a-ui-developer/</link>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Fri, 27 Jan 2023 18:17:46 +0000</pubDate>
				<category><![CDATA[App Development]]></category>
		<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[Productivity]]></category>
		<category><![CDATA[Projects]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1089517</guid>

					<description><![CDATA[<p>I have created many apps throughout my career. Some apps, such as the Finxter Python learning app, have reached millions of users over the years. While I&#8217;m not a professional web designer (by education), I was taught the hard way (by trial and error) that there are some crucial and timeless skills you need to ... <a title="20 Real-Life Skills You Need as a UI Developer in 2023" class="read-more" href="https://blog.finxter.com/real-life-skills-you-need-as-a-ui-developer/" aria-label="Read more about 20 Real-Life Skills You Need as a UI Developer in 2023">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/real-life-skills-you-need-as-a-ui-developer/">20 Real-Life Skills You Need as a UI Developer in 2023</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>I have created many apps throughout my career. Some apps, such as the <a href="https://app.finxter.com/learn/computer/science/" data-type="URL" data-id="https://app.finxter.com/learn/computer/science/" target="_blank" rel="noreferrer noopener">Finxter Python learning app</a>, have reached millions of users over the years.</p>



<p>While I&#8217;m not a professional web designer (by education), I was taught the hard way (by trial and error) that there are some crucial and timeless skills you need to master as a User Interface developer no matter what.</p>



<p>This list of 20 tips is my best-of compilation. So, without further ado, let&#8217;s dive right in! <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f447.png" alt="👇" class="wp-smiley" style="height: 1em; max-height: 1em;" /> </p>



<h2 class="wp-block-heading">Skill 1: HTML/CSS</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="554" height="367" src="https://blog.finxter.com/wp-content/uploads/2023/01/image-320.png" alt="" class="wp-image-1089537" srcset="https://blog.finxter.com/wp-content/uploads/2023/01/image-320.png 554w, https://blog.finxter.com/wp-content/uploads/2023/01/image-320-300x199.png 300w" sizes="auto, (max-width: 554px) 100vw, 554px" /></figure>
</div>


<p>HTML and CSS are the building blocks of any website, and a must-have for any UI developer. </p>



<p>HTML is the structural markup language used to create webpages, while CSS is the styling language used to make them look attractive.</p>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f30d.png" alt="🌍" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/full-stack-web-developer-income-and-opportunity/" data-type="post" data-id="326336" target="_blank" rel="noreferrer noopener">Full-Stack Web Developer &#8212; Income and Opportunity</a></p>



<h2 class="wp-block-heading">Skill 2: JavaScript</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="554" height="369" src="https://blog.finxter.com/wp-content/uploads/2023/01/image-321.png" alt="" class="wp-image-1089544" srcset="https://blog.finxter.com/wp-content/uploads/2023/01/image-321.png 554w, https://blog.finxter.com/wp-content/uploads/2023/01/image-321-300x200.png 300w" sizes="auto, (max-width: 554px) 100vw, 554px" /></figure>
</div>


<p><a rel="noreferrer noopener" href="https://blog.finxter.com/javascript-data-types/" data-type="post" data-id="222514" target="_blank">JavaScript</a> is a scripting language used to create dynamic and interactive webpages. UI developers need to be proficient in this language to develop modern websites and web applications.</p>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f30d.png" alt="🌍" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/javascript-developer-income-and-opportunity/" data-type="post" data-id="191233" target="_blank" rel="noreferrer noopener">JavaScript Developer &#8212; Income and Opportunity</a></p>



<h2 class="wp-block-heading">Skill 3: Responsive Design</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="554" height="407" src="https://blog.finxter.com/wp-content/uploads/2023/01/image-322.png" alt="" class="wp-image-1089546" srcset="https://blog.finxter.com/wp-content/uploads/2023/01/image-322.png 554w, https://blog.finxter.com/wp-content/uploads/2023/01/image-322-300x220.png 300w" sizes="auto, (max-width: 554px) 100vw, 554px" /></figure>
</div>


<p>Responsive design ensures that a website looks and functions great on any device (e.g., mobile devices). </p>



<p>UI developers must be able to create websites that look great on any screen size, from mobile phones to large desktop displays.</p>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f30d.png" alt="🌍" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/mobile-app-developer/" data-type="post" data-id="337807" target="_blank" rel="noreferrer noopener">Mobile App Developer &#8212; Income and Opportunity</a></p>



<h2 class="wp-block-heading">Skill 4: Wireframing</h2>



<p>Wireframing is the process of <strong>creating a blueprint</strong> of a website or web application. UI developers need to be able to create wireframes to plan out the structure and layout of a website.</p>



<p>This skill especially requires you to be able to communicate effectively with your clients and project owners.</p>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f30d.png" alt="🌍" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/get-more-clients-as-a-freelance-developer-with-this-one-simple-trick/" data-type="URL" data-id="https://blog.finxter.com/get-more-clients-as-a-freelance-developer-with-this-one-simple-trick/" target="_blank" rel="noreferrer noopener">Get More Clients as a Freelance Developer with This One Simple Trick</a></p>



<h2 class="wp-block-heading">Skill 5: User Interface Design</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="554" height="738" src="https://blog.finxter.com/wp-content/uploads/2023/01/image-323.png" alt="" class="wp-image-1089552" srcset="https://blog.finxter.com/wp-content/uploads/2023/01/image-323.png 554w, https://blog.finxter.com/wp-content/uploads/2023/01/image-323-225x300.png 225w" sizes="auto, (max-width: 554px) 100vw, 554px" /></figure>
</div>


<p>User interface design is the process of creating user-friendly and visually appealing interfaces for websites and web applications. </p>



<p>UI developers need to understand the <strong>principles of good design</strong> to be able to create interfaces that are both attractive and easy to use.</p>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f30d.png" alt="🌍" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/less-is-more-in-design/" data-type="post" data-id="24247" target="_blank" rel="noreferrer noopener">Less Is More in Design</a></p>



<h2 class="wp-block-heading">Skill 6: User Experience Design</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="554" height="369" src="https://blog.finxter.com/wp-content/uploads/2023/01/image-324.png" alt="" class="wp-image-1089553" srcset="https://blog.finxter.com/wp-content/uploads/2023/01/image-324.png 554w, https://blog.finxter.com/wp-content/uploads/2023/01/image-324-300x200.png 300w" sizes="auto, (max-width: 554px) 100vw, 554px" /></figure>
</div>


<p>User experience design is the process of creating engaging and meaningful experiences for users of websites and web applications. </p>



<p>UI developers need to understand the principles of user experience and dive deep into users&#8217; emotions so they can create enjoyable and fun experiences.</p>



<h2 class="wp-block-heading">Skill 7: Cross-Browser Compatibility</h2>



<p>Cross-browser compatibility is the ability of a website or web application to work properly across multiple types of web browsers. </p>



<p>UI developers need to ensure that their websites and applications look and function properly on all types of browsers.</p>



<h2 class="wp-block-heading">Skill 8: Version Control</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="554" height="369" src="https://blog.finxter.com/wp-content/uploads/2023/01/image-325.png" alt="" class="wp-image-1089554" srcset="https://blog.finxter.com/wp-content/uploads/2023/01/image-325.png 554w, https://blog.finxter.com/wp-content/uploads/2023/01/image-325-300x200.png 300w" sizes="auto, (max-width: 554px) 100vw, 554px" /></figure>
</div>


<p>Version control is a system used to track and manage changes to files and documents. UI developers need to be able to use version control to keep track of changes and ensure that their work is up to date.</p>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f30d.png" alt="🌍" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/top-cheat-sheets-for-git/" data-type="post" data-id="20843" target="_blank" rel="noreferrer noopener">Git Cheat Sheet [Ultimate Guide]</a></p>



<h2 class="wp-block-heading">Skill 9: Debugging</h2>



<p>Yes, we all know it and fear it: <strong>debugging</strong>. </p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="480" height="246" src="https://blog.finxter.com/wp-content/uploads/2023/01/DebuggingProgrammingGIF.gif" alt="" class="wp-image-1089555"/></figure>
</div>


<p></p>



<p>Debugging is the process of finding and fixing errors in a website or web application. UI developers need to be able to debug their code to ensure that their websites and applications are functioning correctly.</p>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f30d.png" alt="🌍" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/writing-running-debugging-and-testing-code-in-pycharm/" data-type="URL" data-id="https://blog.finxter.com/writing-running-debugging-and-testing-code-in-pycharm/" target="_blank" rel="noreferrer noopener">Debugging in PyCharm &#8212; The Right Way</a></p>



<h2 class="wp-block-heading">Skill 10: Testing/QA</h2>



<p><strong>Testing and Quality Assurance</strong> are processes used to ensure that a website or web application is functioning correctly before it is released. UI developers need to be able to test their work and ensure that it meets the specified requirements.</p>



<p>Testing is often not done correctly or follows too strict rules. In my world, when I create apps, I just play with them, pressing any button and inputting all kinds of stupid things to test my app. This has brought to light many more errors than standard unit tests.</p>



<h2 class="wp-block-heading">Skill 11: Building User Interfaces with Frameworks</h2>



<p>Frameworks are used to simplify the process of building user interfaces. UI developers need to be familiar with the most popular frameworks in order to create modern and efficient user interfaces.</p>



<p>Here&#8217;s a table I created to show the income distributions of different PHP frameworks:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="619" height="614" src="https://blog.finxter.com/wp-content/uploads/2023/01/image-326.png" alt="" class="wp-image-1089562" srcset="https://blog.finxter.com/wp-content/uploads/2023/01/image-326.png 619w, https://blog.finxter.com/wp-content/uploads/2023/01/image-326-300x298.png 300w, https://blog.finxter.com/wp-content/uploads/2023/01/image-326-150x150.png 150w" sizes="auto, (max-width: 619px) 100vw, 619px" /></figure>
</div>


<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f30d.png" alt="🌍" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/php-frameworks-that-make-you-money-as-a-web-developer-in-2023/" data-type="URL" data-id="https://blog.finxter.com/php-frameworks-that-make-you-money-as-a-web-developer-in-2023/" target="_blank" rel="noreferrer noopener">8 PHP Frameworks That Make You Money as a Web Developer in 2023</a></p>



<h2 class="wp-block-heading">Skill 12: Accessibility and Usability</h2>



<p>Accessibility and usability are two important aspects of user interface design. In fact, there&#8217;s a huge megatrend towards creating more accessible user interfaces &#8212; often, they are legally required!</p>



<p>It&#8217;s a big growth market &#8212; unbelievable, isn&#8217;t it? <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="553" src="https://blog.finxter.com/wp-content/uploads/2023/01/image-327-1024x553.png" alt="" class="wp-image-1089565" srcset="https://blog.finxter.com/wp-content/uploads/2023/01/image-327-1024x553.png 1024w, https://blog.finxter.com/wp-content/uploads/2023/01/image-327-300x162.png 300w, https://blog.finxter.com/wp-content/uploads/2023/01/image-327-768x414.png 768w, https://blog.finxter.com/wp-content/uploads/2023/01/image-327.png 1512w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p>UI developers need to be able to design interfaces that are both accessible and usable to provide the best user experience.</p>



<h2 class="wp-block-heading">Skill 13: Interaction Design</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="554" height="692" src="https://blog.finxter.com/wp-content/uploads/2023/01/image-328.png" alt="" class="wp-image-1089566" srcset="https://blog.finxter.com/wp-content/uploads/2023/01/image-328.png 554w, https://blog.finxter.com/wp-content/uploads/2023/01/image-328-240x300.png 240w" sizes="auto, (max-width: 554px) 100vw, 554px" /></figure>
</div>


<p>Interaction design is the process of creating user interactions that are both intuitive and efficient. UI developers need to be able to create interactions that are easy to use and don’t require a lot of effort from the user.</p>



<h2 class="wp-block-heading">Skill 14: Web Design Principles</h2>



<p>Web design principles are the fundamental rules that should be followed when designing websites and web applications. UI developers need to understand these principles to create attractive and effective interfaces.</p>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f30d.png" alt="🌍" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/tips-to-write-clean-code/" data-type="post" data-id="17059" target="_blank" rel="noreferrer noopener">7 Tips to Write Clean Code</a></p>



<hr class="wp-block-separator has-css-opacity"/>



<h2 class="wp-block-heading">The Art of Clean Code</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://www.amazon.com/Art-Clean-Code-Practices-Complexity/dp/1718502184" target="_blank" rel="noopener"><img loading="lazy" decoding="async" width="325" height="427" src="https://blog.finxter.com/wp-content/uploads/2022/05/image-269.png" alt="" class="wp-image-385474" srcset="https://blog.finxter.com/wp-content/uploads/2022/05/image-269.png 325w, https://blog.finxter.com/wp-content/uploads/2022/05/image-269-228x300.png 228w" sizes="auto, (max-width: 325px) 100vw, 325px" /></a></figure>
</div>


<p>Most software developers waste thousands of hours working with overly complex code. The eight core principles in The Art of Clean Coding will teach you how to write clear, maintainable code without compromising functionality. The book’s guiding principle is simplicity: reduce and simplify, then reinvest energy in the important parts to save you countless hours and ease the often onerous task of code maintenance.</p>



<ol class="wp-block-list">
<li>Concentrate on the important stuff with the <strong>80/20 principle</strong> &#8212; focus on the 20% of your code that matters most</li>



<li>Avoid coding in isolation: create a <strong>minimum viable product</strong> to get early feedback</li>



<li>Write code cleanly and simply to <strong>eliminate clutter</strong>&nbsp;</li>



<li><strong>Avoid premature optimization</strong> that risks over-complicating code&nbsp;</li>



<li>Balance your goals, capacity, and feedback to achieve the productive state of <strong>Flow</strong></li>



<li>Apply the <strong>Do One Thing Well</strong> philosophy to vastly improve functionality</li>



<li>Design efficient user interfaces with the <strong>Less is More</strong> principle</li>



<li>Tie your new skills together into one unifying principle: <strong>Focus</strong></li>
</ol>



<p>The Python-based <em><strong><a rel="noreferrer noopener" href="https://www.amazon.com/Art-Clean-Code-Practices-Complexity/dp/1718502184" data-type="URL" data-id="https://www.amazon.com/Art-Clean-Code-Practices-Complexity/dp/1718502184" target="_blank">The Art of Clean Coding</a></strong></em> is suitable for programmers at any level, with ideas presented in a language-agnostic manner.</p>



<div class="wp-block-buttons is-content-justification-center is-layout-flex wp-container-core-buttons-is-layout-16018d1d wp-block-buttons-is-layout-flex">
<div class="wp-block-button has-custom-width wp-block-button__width-50"><a class="wp-block-button__link wp-element-button" href="https://www.amazon.com/Art-Clean-Code-Practices-Complexity/dp/1718502184" target="_blank" rel="noreferrer noopener">Get on Amazon!</a></div>
</div>



<hr class="wp-block-separator has-css-opacity"/>



<h2 class="wp-block-heading">Skill 15: Graphic Design</h2>



<p>Graphic design is the process of creating visuals and graphics for websites and web applications. UI developers need to be able to create attractive visuals to make their websites look appealing.</p>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f30d.png" alt="🌍" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/front-end-web-developer-income-and-opportunity/" data-type="post" data-id="316587" target="_blank" rel="noreferrer noopener">Graphic Designer and Front-End Web Developer</a></p>



<h2 class="wp-block-heading">Skill 16: Object-Oriented Programming</h2>



<p>Object-oriented programming is a programming paradigm used to create complex websites and web applications. UI developers must understand this programming paradigm to create efficient and powerful web applications.</p>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f30d.png" alt="🌍" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/introduction-to-python-classes/" data-type="post" data-id="30596" target="_blank" rel="noreferrer noopener">Object-Oriented Programming in Python</a></p>



<h2 class="wp-block-heading">Skill 17: Animation and Effects</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="554" height="738" src="https://blog.finxter.com/wp-content/uploads/2023/01/image-329.png" alt="" class="wp-image-1089578" srcset="https://blog.finxter.com/wp-content/uploads/2023/01/image-329.png 554w, https://blog.finxter.com/wp-content/uploads/2023/01/image-329-225x300.png 225w" sizes="auto, (max-width: 554px) 100vw, 554px" /></figure>
</div>


<p>Animations and effects are used to create dynamic and engaging user interfaces. UI developers need to be able to create animations and effects to make their websites more attractive and engaging.</p>



<h2 class="wp-block-heading">Skill 18: Mobile App Design</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="554" height="415" src="https://blog.finxter.com/wp-content/uploads/2023/01/image-330.png" alt="" class="wp-image-1089579" srcset="https://blog.finxter.com/wp-content/uploads/2023/01/image-330.png 554w, https://blog.finxter.com/wp-content/uploads/2023/01/image-330-300x225.png 300w" sizes="auto, (max-width: 554px) 100vw, 554px" /></figure>
</div>


<p>Mobile app design is the process of designing user interfaces for mobile applications. UI developers need to understand the principles of mobile app design in order to create engaging and user-friendly apps.</p>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f30d.png" alt="🌍" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/top-6-mobile-app-development-career-paths-in-2023/" data-type="URL" data-id="https://blog.finxter.com/top-6-mobile-app-development-career-paths-in-2023/" target="_blank" rel="noreferrer noopener">Top 6 Mobile App Development Career Paths in 2023</a></p>



<h2 class="wp-block-heading">Skill 19: Front-End Performance Optimization</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="554" height="345" src="https://blog.finxter.com/wp-content/uploads/2023/01/image-331.png" alt="" class="wp-image-1089581" srcset="https://blog.finxter.com/wp-content/uploads/2023/01/image-331.png 554w, https://blog.finxter.com/wp-content/uploads/2023/01/image-331-300x187.png 300w" sizes="auto, (max-width: 554px) 100vw, 554px" /></figure>
</div>


<p>Front-end performance optimization is the process of optimizing a website or web application to make it faster and more efficient. UI developers must understand optimization principles to create fast and efficient websites and web applications.</p>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f30d.png" alt="🌍" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/premature-optimization/" data-type="post" data-id="17717" target="_blank" rel="noreferrer noopener">Premature Optimization is the Root of All Evil!</a></p>



<h2 class="wp-block-heading">Skill 20: Data Visualization</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="554" height="367" src="https://blog.finxter.com/wp-content/uploads/2023/01/image-332.png" alt="" class="wp-image-1089582" srcset="https://blog.finxter.com/wp-content/uploads/2023/01/image-332.png 554w, https://blog.finxter.com/wp-content/uploads/2023/01/image-332-300x199.png 300w" sizes="auto, (max-width: 554px) 100vw, 554px" /></figure>
</div>


<p>Data visualization is the process of creating visuals that represent data in an easy-to-understand way. UI developers need to be able to create effective data visualizations to make complex data easier to understand.</p>



<p>Personally, I&#8217;d recommend you check out Plotly Dash &#8212; a Python framework for easy development of dashboard apps:</p>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f30d.png" alt="🌍" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/your-first-dash-app-how-to-get-started-in-4-minutes-or-less/" data-type="post" data-id="27820" target="_blank" rel="noreferrer noopener">Create Your First App in Plotly Dash</a></p>



<h2 class="wp-block-heading">Learn More</h2>



<hr class="wp-block-separator has-css-opacity"/>



<p><em>If you&#8217;re interested in learning more about how to create beautiful dashboard applications in Python, check out our new book <a rel="noreferrer noopener" href="https://www.amazon.com/Python-Dash-Analysis-Visualization-Plotly-dp-1718502222/dp/1718502222/" data-type="URL" data-id="https://www.amazon.com/Python-Dash-Analysis-Visualization-Plotly-dp-1718502222/dp/1718502222/" target="_blank">Python Dash</a>. </em></p>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow">
<figure class="wp-block-image size-full is-resized"><a href="https://www.amazon.com/Python-Dash-Analysis-Visualization-Plotly-dp-1718502222/dp/1718502222/" target="_blank" rel="noopener"><img loading="lazy" decoding="async" src="https://blog.finxter.com/wp-content/uploads/2022/05/image-24.png" alt="" class="wp-image-336350" width="292" height="384" srcset="https://blog.finxter.com/wp-content/uploads/2022/05/image-24.png 325w, https://blog.finxter.com/wp-content/uploads/2022/05/image-24-228x300.png 228w" sizes="auto, (max-width: 292px) 100vw, 292px" /></a></figure>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow">
<p><em>You’ve seen dashboards before; think election result visualizations you can update in real-time, or population maps you can filter by demographic. </em></p>



<p><em>With the Python Dash library, you’ll create analytic dashboards that present data in effective, usable, elegant ways in just a few lines of code.</em></p>
</div>
</div>



<p><em>Get the book on <a rel="noreferrer noopener" href="https://nostarch.com/python-dash" data-type="URL" data-id="https://nostarch.com/python-dash" target="_blank">NoStarch</a> or <a rel="noreferrer noopener" href="https://www.amazon.com/Python-Dash-Analysis-Visualization-Plotly-dp-1718502222/dp/1718502222/" data-type="URL" data-id="https://www.amazon.com/Python-Dash-Analysis-Visualization-Plotly-dp-1718502222/dp/1718502222/" target="_blank">Amazon</a>! </em></p>



<hr class="wp-block-separator has-css-opacity"/>
<p>The post <a href="https://blog.finxter.com/real-life-skills-you-need-as-a-ui-developer/">20 Real-Life Skills You Need as a UI Developer in 2023</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>OpenAI API &#8211; or How I Made My Python Code Intelligent</title>
		<link>https://blog.finxter.com/openai-api-or-how-i-made-my-python-code-intelligent/</link>
		
		<dc:creator><![CDATA[Chris]]></dc:creator>
		<pubDate>Tue, 24 Jan 2023 17:02:53 +0000</pubDate>
				<category><![CDATA[App Development]]></category>
		<category><![CDATA[Artificial Intelligence]]></category>
		<category><![CDATA[Machine Learning]]></category>
		<category><![CDATA[Projects]]></category>
		<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1081478</guid>

					<description><![CDATA[<p>In this quick tutorial, I&#8217;ll show you how I integrated ChatGPT intelligence into an app I&#8217;m currently working on. It&#8217;s really simple, so let&#8217;s get started! Step 1: Create a Paid Account with OpenAI I&#8217;m not affiliated with OpenAI in any way. However, to use it, you need to create a (paid) account to create ... <a title="OpenAI API &#8211; or How I Made My Python Code Intelligent" class="read-more" href="https://blog.finxter.com/openai-api-or-how-i-made-my-python-code-intelligent/" aria-label="Read more about OpenAI API &#8211; or How I Made My Python Code Intelligent">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/openai-api-or-how-i-made-my-python-code-intelligent/">OpenAI API &#8211; or How I Made My Python Code Intelligent</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>In this quick tutorial, I&#8217;ll show you how I integrated ChatGPT intelligence into an app I&#8217;m currently working on. It&#8217;s really simple, so let&#8217;s get started!</p>



<h2 class="wp-block-heading">Step 1: Create a Paid Account with OpenAI</h2>



<p>I&#8217;m not affiliated with OpenAI in any way. However, to use it, you need to create a (paid) account to create an API key that you&#8217;ll need in order to connect ChatGPT with your code.</p>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f449.png" alt="👉" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <a href="https://beta.openai.com/playground" data-type="URL" data-id="https://beta.openai.com/playground" target="_blank" rel="noreferrer noopener">Click here to create an account</a> and connect it with your credit card</p>



<p>I use it a lot and pay only a couple of cents per day so it&#8217;s really inexpensive for now.</p>



<h2 class="wp-block-heading">Step 2: Get Your API Key</h2>



<p>Open the link <a href="https://beta.openai.com/playground" target="_blank" rel="noreferrer noopener">https://beta.openai.com/playground</a> and navigate to <code>Personal > View API keys</code>. </p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="721" src="https://blog.finxter.com/wp-content/uploads/2023/01/image-301-1024x721.png" alt="" class="wp-image-1081485" srcset="https://blog.finxter.com/wp-content/uploads/2023/01/image-301-1024x721.png 1024w, https://blog.finxter.com/wp-content/uploads/2023/01/image-301-300x211.png 300w, https://blog.finxter.com/wp-content/uploads/2023/01/image-301-768x541.png 768w, https://blog.finxter.com/wp-content/uploads/2023/01/image-301-1536x1082.png 1536w, https://blog.finxter.com/wp-content/uploads/2023/01/image-301.png 1651w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p>Now, click the <code>+ Create new secret key</code> button to create a new API key:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="569" src="https://blog.finxter.com/wp-content/uploads/2023/01/image-302-1024x569.png" alt="" class="wp-image-1081487" srcset="https://blog.finxter.com/wp-content/uploads/2023/01/image-302-1024x569.png 1024w, https://blog.finxter.com/wp-content/uploads/2023/01/image-302-300x167.png 300w, https://blog.finxter.com/wp-content/uploads/2023/01/image-302-768x427.png 768w, https://blog.finxter.com/wp-content/uploads/2023/01/image-302-1536x854.png 1536w, https://blog.finxter.com/wp-content/uploads/2023/01/image-302.png 1667w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p>Now copy the API key to your clipboard:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="538" src="https://blog.finxter.com/wp-content/uploads/2023/01/image-303-1024x538.png" alt="" class="wp-image-1081488" srcset="https://blog.finxter.com/wp-content/uploads/2023/01/image-303-1024x538.png 1024w, https://blog.finxter.com/wp-content/uploads/2023/01/image-303-300x158.png 300w, https://blog.finxter.com/wp-content/uploads/2023/01/image-303-768x404.png 768w, https://blog.finxter.com/wp-content/uploads/2023/01/image-303-1536x808.png 1536w, https://blog.finxter.com/wp-content/uploads/2023/01/image-303.png 1664w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<h2 class="wp-block-heading">Step 3: Pip Install OpenAI</h2>



<p>Use your version of pip to install the <code>openai</code> module by running a command similar to the following (depending on your local environment):</p>



<ul class="wp-block-list">
<li><code>pip install openai</code></li>



<li><code>pip3 install openai</code></li>



<li><code>pip3.11 install openai</code></li>
</ul>



<p>As I&#8217;ve installed Python 3.9 at the point of writing, I used <code>pip3.9 install openai</code>:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="810" src="https://blog.finxter.com/wp-content/uploads/2023/01/image-304-1024x810.png" alt="" class="wp-image-1081490" srcset="https://blog.finxter.com/wp-content/uploads/2023/01/image-304-1024x810.png 1024w, https://blog.finxter.com/wp-content/uploads/2023/01/image-304-300x237.png 300w, https://blog.finxter.com/wp-content/uploads/2023/01/image-304-768x608.png 768w, https://blog.finxter.com/wp-content/uploads/2023/01/image-304.png 1097w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p>You can <a href="https://blog.finxter.com/how-to-check-your-python-version/" data-type="post" data-id="1371" target="_blank" rel="noreferrer noopener">check your Python version here</a> and learn how to <a href="https://blog.finxter.com/how-to-install-xxx-in-python/" data-type="post" data-id="653128" target="_blank" rel="noreferrer noopener">install a module here</a>.</p>



<h2 class="wp-block-heading">Step 4: Python Code to Access OpenAI</h2>



<p>Copy and paste the following code into a Python script (e.g., named <code>code.py</code>) and also paste your API key from <strong>Step 2</strong> into the highlighted line (string):</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="5,9" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import os
import openai


openai.api_key = "&lt;copy your secret API key here>"

response = openai.Completion.create(
    model="text-davinci-003",
    prompt="What is the answer to all questions?",
    temperature=0.7,
    max_tokens=100,
    top_p=1,
    frequency_penalty=0,
    presence_penalty=0
)

print(response)</pre>



<p>You can modify the other highlighted line <code>"What is the answer to all questions?"</code> to customize your input prompt. The output after a few seconds will look like this:</p>



<pre class="wp-block-preformatted"><code>{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "logprobs": null,
<strong>      "text": "\n\nThere is no one answer to all questions as each question has its own unique answer."</strong>
    }
  ],
  "created": 1674579571,
  "id": "cmpl-6cGvr0TM2PGsExeyG3NEx43CrNwSx",
  "model": "text-davinci-003",
  "object": "text_completion",
  "usage": {
    "completion_tokens": 19,
    "prompt_tokens": 8,
    "total_tokens": 27
  }
}</code></pre>



<p>Unfortunately, it couldn&#8217;t figure out the answer 42. <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<p></p>
<p>The post <a href="https://blog.finxter.com/openai-api-or-how-i-made-my-python-code-intelligent/">OpenAI API &#8211; or How I Made My Python Code Intelligent</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Plotly Dash vs. Streamlit</title>
		<link>https://blog.finxter.com/plotly-dash-vs-streamlit/</link>
		
		<dc:creator><![CDATA[Stefan Neumann]]></dc:creator>
		<pubDate>Fri, 23 Dec 2022 18:46:13 +0000</pubDate>
				<category><![CDATA[App Development]]></category>
		<category><![CDATA[Dash]]></category>
		<category><![CDATA[Data Visualization]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Web Development]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=997098</guid>

					<description><![CDATA[<p>What are Plotly Dash and Streamlit? Plotly Dash and Streamlit are both open-source Python libraries for creating interactive web applications for data visualization and analysis. The libraries are designed to make it easy for developers to create visually appealing and informative dashboards and reports that can be shared with others through a web browser. Some ... <a title="Plotly Dash vs. Streamlit" class="read-more" href="https://blog.finxter.com/plotly-dash-vs-streamlit/" aria-label="Read more about Plotly Dash vs. Streamlit">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/plotly-dash-vs-streamlit/">Plotly Dash vs. Streamlit</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<h2 class="wp-block-heading">What are Plotly Dash and Streamlit?</h2>



<p class="has-global-color-8-background-color has-background">Plotly Dash and Streamlit are both open-source Python libraries for creating interactive web applications for data visualization and analysis. The libraries are designed to make it easy for developers to create visually appealing and informative dashboards and reports that can be shared with others through a web browser.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://plotly.com/dash/" target="_blank" rel="noreferrer noopener"><img loading="lazy" decoding="async" width="1024" height="589" src="https://blog.finxter.com/wp-content/uploads/2022/12/image-306-1024x589.png" alt="" class="wp-image-997124" srcset="https://blog.finxter.com/wp-content/uploads/2022/12/image-306-1024x589.png 1024w, https://blog.finxter.com/wp-content/uploads/2022/12/image-306-300x172.png 300w, https://blog.finxter.com/wp-content/uploads/2022/12/image-306-768x442.png 768w, https://blog.finxter.com/wp-content/uploads/2022/12/image-306-1536x883.png 1536w, https://blog.finxter.com/wp-content/uploads/2022/12/image-306-2048x1177.png 2048w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a></figure>
</div>


<p>Some key differences between <a href="https://blog.finxter.com/python-plotly-dash-cheat-sheet/" data-type="post" data-id="28074" target="_blank" rel="noreferrer noopener">Plotly Dash</a> and <a href="https://blog.finxter.com/learning-streamlits-buttons-features/" data-type="post" data-id="462652" target="_blank" rel="noreferrer noopener">Streamlit</a> include:</p>



<ul class="wp-block-list">
<li><strong>Dashboarding capabilities</strong>: Plotly Dash is a full-featured framework for building dashboards and applications, while Streamlit primarily focuses on creating data visualization and exploration tools.</li>



<li><strong>Programming style</strong>: Plotly Dash uses a traditional web application programming model, with a server-side rendering of the dashboard and client-side interactivity. Streamlit, on the other hand, uses a more interactive programming style, with the developer writing code in a script and the library automatically generating the web application.</li>



<li><strong>Data handling</strong>: Both libraries can handle large datasets and support streaming data, but Plotly Dash has more advanced capabilities for managing and manipulating data.</li>
</ul>



<p>Supported programming language: While Streamlit is limited to Python, Plotly Dash also supports <a href="https://blog.finxter.com/r-developer-income-and-opportunity/" data-type="post" data-id="202162" target="_blank" rel="noreferrer noopener">R</a>, <a href="https://blog.finxter.com/julia-developer-income-and-opportunity/" data-type="post" data-id="189355" target="_blank" rel="noreferrer noopener">Julia</a>, and <a href="https://blog.finxter.com/f-developer-income-and-opportunity/" data-type="post" data-id="189362" target="_blank" rel="noreferrer noopener">F#</a> (experimental).</p>



<p>Ultimately, the choice between Plotly Dash and Streamlit depends on your specific needs and preferences. </p>



<ul class="wp-block-list">
<li>If you are looking for a more full-featured framework for building complex dashboards and applications, Plotly Dash may be the better choice. </li>



<li>If you want a more streamlined tool for creating simple visualizations and data exploration tools, Streamlit may be a better fit.</li>
</ul>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f30d.png" alt="🌍" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended Tutorial</strong>: <a href="https://blog.finxter.com/python-dash-how-to-build-a-dashboard/" data-type="post" data-id="19632" target="_blank" rel="noreferrer noopener">Build Your First App with Plotly Dash</a></p>



<h2 class="wp-block-heading">Underlying Technology</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="915" height="610" src="https://blog.finxter.com/wp-content/uploads/2022/12/image-307.png" alt="" class="wp-image-997126" srcset="https://blog.finxter.com/wp-content/uploads/2022/12/image-307.png 915w, https://blog.finxter.com/wp-content/uploads/2022/12/image-307-300x200.png 300w, https://blog.finxter.com/wp-content/uploads/2022/12/image-307-768x512.png 768w" sizes="auto, (max-width: 915px) 100vw, 915px" /></figure>
</div>


<p>Plotly Dash is built on top of the <code>Plotly.js</code> library for creating interactive charts and plots, and the <a href="https://blog.finxter.com/build-website-with-flask-part-1/" data-type="post" data-id="238699" target="_blank" rel="noreferrer noopener">Flask web framework</a> for building web applications.</p>



<p class="has-global-color-8-background-color has-background"><strong>React</strong>: Streamlit uses the <a href="https://blog.finxter.com/react-js-developer-income-and-opportunity/" data-type="post" data-id="246095" target="_blank" rel="noreferrer noopener">React JavaScript</a> library to build interactive user interfaces. React allows you to build complex UI components using reusable and modular code, making it easy to build interactive dashboards and data visualization applications.</p>



<p>The application runs on the server side and the user interacts with it through a web browser.</p>



<p>The server sends the HTML, CSS, and JavaScript to the client, and the client&#8217;s web browser renders the application and handles user interactions.</p>



<p>Dash uses a declarative syntax called &#8220;<a rel="noreferrer noopener" href="https://blog.finxter.com/your-first-dash-app-how-to-get-started-in-4-minutes-or-less/" data-type="post" data-id="27820" target="_blank">Dash HTML Components</a>&#8221; to build the application, which allows developers to define the layout and interactivity of the application in a simple, intuitive way.</p>



<p>Under the hood, Streamlit uses several technologies and libraries to provide its functionality. Some of these technologies include:</p>



<ul class="wp-block-list">
<li>HTML, CSS, and JavaScript: Streamlit generates web pages that are rendered in the user&#8217;s web browser. These pages are written in HTML, CSS, and JavaScript, which are the three main technologies used to build modern web applications.</li>



<li>React: Streamlit uses the React JavaScript library to build interactive user interfaces.&nbsp;</li>
</ul>



<p>Both Plotly Dash and Streamlit use JavaScript libraries to provide interactivity and visualizations in the web browser. However, the way that these libraries are used and integrated into the overall application is different in the two frameworks.</p>



<h2 class="wp-block-heading">Pros and Cons Plotly Dash</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="418" height="610" src="https://blog.finxter.com/wp-content/uploads/2022/12/image-309.png" alt="" class="wp-image-997132" srcset="https://blog.finxter.com/wp-content/uploads/2022/12/image-309.png 418w, https://blog.finxter.com/wp-content/uploads/2022/12/image-309-206x300.png 206w" sizes="auto, (max-width: 418px) 100vw, 418px" /></figure>
</div>


<p>Here are some pros and cons of using Plotly Dash:</p>



<h3 class="wp-block-heading">Pros</h3>



<p>(1) <strong>Full-featured framework:</strong> Plotly Dash is a comprehensive framework for building dashboards and web applications. It provides various tools and features for creating interactive visualizations, handling and manipulating data, and building complex layouts and interactions.</p>



<p>(2) <strong>Strong visualization capabilities:</strong> Plotly Dash is built on top of the Plotly.js library, which provides a wide range of chart types and options for visually appealing and informative visualizations.</p>



<p>(3) <strong>Active community:</strong> Plotly Dash has a large and active user base, with extensive documentation and support resources available, including forums, tutorials, and examples.</p>



<h3 class="wp-block-heading">Cons</h3>



<p>(1) <strong>Steep learning curve:</strong> Plotly Dash is a powerful and feature-rich framework, which can make it a bit more difficult to learn than some other libraries. It may take some time to become familiar with all of the features and capabilities of the library.</p>



<p>(2) <strong>Performance:</strong> Depending on the complexity of the application and the amount of data being processed, Plotly Dash applications can sometimes be slower to render and interact with than some other libraries.</p>



<p>(3) <strong>Complexity:</strong> Because Plotly Dash is a full-featured framework, it can be somewhat more complex than other libraries focused on a specific use case. This can make it a bit more challenging for new users to get started with the library.</p>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f449.png" alt="👉" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://www.amazon.com/Python-Dash-Christian-Mayer-dp-1718502222/dp/1718502222" data-type="URL" data-id="https://www.amazon.com/Python-Dash-Christian-Mayer-dp-1718502222/dp/1718502222" target="_blank" rel="noreferrer noopener">The Book of Plotly Dash</a></p>



<h2 class="wp-block-heading">Pros and Cons Streamlit</h2>



<h3 class="wp-block-heading">Pros</h3>



<p>(1) <strong>Simplicity:</strong> Streamlit is designed to be easy to use and learn, with a streamlined API and automatic web application generation. This makes it a good choice for developers who want to quickly create simple visualizations and data exploration tools.</p>



<p>(2) <strong>Interactive programming style:</strong> Streamlit uses an interactive programming style, allowing the developer to write a script and see the results immediately in the web browser. This can be a more intuitive and interactive way of working compared to traditional web application frameworks.</p>



<p>(3) <strong>Good performance:</strong> Streamlit applications tend to be fast and responsive, even with large datasets and complex visualizations.</p>



<h3 class="wp-block-heading">Cons</h3>



<p>(1) <strong>Limited capabilities:</strong> Streamlit is primarily focused on creating simple visualizations and data exploration tools, and may not have all of the features and capabilities of a more full-featured framework like Plotly Dash.</p>



<p>(2) <strong>Limited layout options:</strong> Streamlit provides a limited set of layout options compared to some other libraries, which can make it more difficult to create complex layouts and interactions.</p>



<h2 class="wp-block-heading">Which Community Is Larger?</h2>



<p>It&#8217;s difficult to say for certain which community is larger, as both Plotly Dash and Streamlit have active user bases and are widely used in the data science and web development communities.</p>



<p>Both libraries have substantial documentation and support resources, including extensive documentation, tutorials, and examples on their websites, as well as active forums and communities where users can ask questions and get help.</p>



<p>In general, Plotly Dash may have a slightly larger community, as it has been around longer and is a more full-featured framework for building dashboards and web applications. Streamlit, on the other hand, has gained popularity more recently and is focused on a specific use case (creating data visualization and exploration tools) rather than being a general-purpose framework.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="1024" height="717" src="https://blog.finxter.com/wp-content/uploads/2022/12/image-301.png" alt="" class="wp-image-997113" srcset="https://blog.finxter.com/wp-content/uploads/2022/12/image-301.png 1024w, https://blog.finxter.com/wp-content/uploads/2022/12/image-301-300x210.png 300w, https://blog.finxter.com/wp-content/uploads/2022/12/image-301-768x538.png 768w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /><figcaption class="wp-element-caption"><strong>Fig. 1</strong>: Popularity of Plotly Dash and Streamlit (and other frameworks) on Github.</figcaption></figure>
</div>


<p></p>



<p>Ultimately, the choice between Plotly Dash and Streamlit will depend on your specific needs and preferences, as well as the resources and support available in the community for the library you choose.</p>



<h2 class="wp-block-heading">Plotly Dash code example line chart</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import dash
import dash_core_components as dcc
import dash_html_components as html

app = dash.Dash()

app.layout = html.Div([
    dcc.Graph(
        id='line-chart',
        figure={
            'data': [
                {'x': [1, 2, 3], 'y': [4, 1, 2], 'type': 'line', 'name': 'SF'},
                {'x': [1, 2, 3], 'y': [2, 4, 5], 'type': 'line', 'name': 'NYC'},
            ],
            'layout': {
                'title': 'Line Chart'
            }
        }
    )
])

if __name__ == '__main__':
    app.run_server(debug=True)
</pre>



<p>This code creates a Dash application with a single page containing a line chart. The chart is defined using the <code>dcc.Graph</code> component, which takes a figure argument that specifies the data and layout of the chart. The figure argument is a <a href="https://blog.finxter.com/python-dictionary/" data-type="post" data-id="5232" target="_blank" rel="noreferrer noopener">dictionary</a> containing two keys: </p>



<ul class="wp-block-list">
<li><code>data</code>, which is a list of traces (i.e. data series) to plot on the chart, and </li>



<li><code>layout</code>, which is a dictionary of layout options for the chart.</li>
</ul>



<p>In this example, the chart has two data series, <code>y1</code> and <code>y2</code>, with <code>x</code> and <code>y</code> values specified for each series. The type of each trace is set to <code>'line'</code> to create a line chart. The layout options specify a title for the chart.</p>



<p>Finally, the application is started by calling <code>app.run_server()</code>. This will start a local web server and open the application in a web browser. The <code>debug=True</code> argument enables debugging mode, which allows the application to be reloaded automatically when the code is changed.</p>



<p>You run the app via</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">python app.py</pre>



<p>In your terminal following message (or similar) should appear.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="595" height="118" src="https://blog.finxter.com/wp-content/uploads/2022/12/image-302.png" alt="" class="wp-image-997114" srcset="https://blog.finxter.com/wp-content/uploads/2022/12/image-302.png 595w, https://blog.finxter.com/wp-content/uploads/2022/12/image-302-300x59.png 300w" sizes="auto, (max-width: 595px) 100vw, 595px" /><figcaption class="wp-element-caption"><strong>Fig. 2</strong>: Typical terminal messages after starting the Dash app.</figcaption></figure>
</div>


<p></p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="556" height="425" src="https://blog.finxter.com/wp-content/uploads/2022/12/image-303.png" alt="" class="wp-image-997115" srcset="https://blog.finxter.com/wp-content/uploads/2022/12/image-303.png 556w, https://blog.finxter.com/wp-content/uploads/2022/12/image-303-300x229.png 300w" sizes="auto, (max-width: 556px) 100vw, 556px" /><figcaption class="wp-element-caption"><strong>Fig. 3</strong>: Screenshot of Dash app.</figcaption></figure>
</div>


<p></p>



<h2 class="wp-block-heading">Streamlit code example line chart</h2>



<p>A simple app displaying two line charts could be created by the following code:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import streamlit as st

data = {'x': [1,2,3], 'y1': [4,1,2], 'y2': [2,4,5]}
st.line_chart(data= data, x='x')
</pre>



<p>This code creates a line chart with two data series, <code>y1</code> and <code>y2</code>, using the <code>line_chart</code> function. The <code>x</code> and <code>y</code> values for each series are specified as separate lists. The <code>x_axis</code> parameter specifies the values for the x-axis.</p>



<p>Supposing you saved the above code as <code>‘app.py’</code> you start the app via</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">streamlit run app.py</pre>



<p>In your terminal following message (or similar) should appear.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="382" height="77" src="https://blog.finxter.com/wp-content/uploads/2022/12/image-304.png" alt="" class="wp-image-997118" srcset="https://blog.finxter.com/wp-content/uploads/2022/12/image-304.png 382w, https://blog.finxter.com/wp-content/uploads/2022/12/image-304-300x60.png 300w" sizes="auto, (max-width: 382px) 100vw, 382px" /><figcaption class="wp-element-caption"><strong>Fig. 4</strong>: Typical terminal messages after starting the Streamlit app.</figcaption></figure>
</div>


<p></p>



<p>In case the app doesn’t automatically open a tab in your browser you can open the app by following the ‘Local URL’ or ‘Network URL’ links.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="572" height="422" src="https://blog.finxter.com/wp-content/uploads/2022/12/image-305.png" alt="" class="wp-image-997119" srcset="https://blog.finxter.com/wp-content/uploads/2022/12/image-305.png 572w, https://blog.finxter.com/wp-content/uploads/2022/12/image-305-300x221.png 300w" sizes="auto, (max-width: 572px) 100vw, 572px" /><figcaption class="wp-element-caption"><strong>Fig. 5:</strong> Screenshot of Streamlit app.</figcaption></figure>
</div>


<p></p>



<p>The <code>line_chart</code> function automatically generates the web application and displays the chart in the browser. There is no need to write any code to define the layout or interactivity of the application.</p>



<p>Streamlit also provides a wide range of other functions for creating different types of charts and visualizations, as well as tools for building custom layouts and interactions. You can find more information and examples in the Streamlit documentation.</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<p></p>
<p>The post <a href="https://blog.finxter.com/plotly-dash-vs-streamlit/">Plotly Dash vs. Streamlit</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Play the Python Number Guessing Game &#8211; Can You Beat It?</title>
		<link>https://blog.finxter.com/creating-a-simple-guess-the-number-game-in-python/</link>
		
		<dc:creator><![CDATA[Emily Rosemary Collins]]></dc:creator>
		<pubDate>Sun, 11 Dec 2022 14:55:42 +0000</pubDate>
				<category><![CDATA[App Development]]></category>
		<category><![CDATA[Games]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Python String]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=970326</guid>

					<description><![CDATA[<p>In today&#8217;s quick session, I&#8217;ll show you a simple Python game that I found interesting because it helps you understand some simple Python concepts such as string formatting and user interaction. 🎲 The Game: The Python script will choose a random number between 1 and 10. You attempt to guess the number. The script gives ... <a title="Play the Python Number Guessing Game &#8211; Can You Beat It?" class="read-more" href="https://blog.finxter.com/creating-a-simple-guess-the-number-game-in-python/" aria-label="Read more about Play the Python Number Guessing Game &#8211; Can You Beat It?">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/creating-a-simple-guess-the-number-game-in-python/">Play the Python Number Guessing Game &#8211; Can You Beat It?</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>In today&#8217;s quick session, I&#8217;ll show you a simple Python game that I found interesting because it helps you understand some simple Python concepts such as string formatting and user interaction. </p>



<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f3b2.png" alt="🎲" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>The Game</strong>: The Python script will choose a random number between 1 and 10. You attempt to guess the number. The script gives you feedback whether your guess was too high, too low, or correct. It shows the number of trials when you&#8217;ve found the magic number!</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="683" src="https://blog.finxter.com/wp-content/uploads/2022/12/image-144-1024x683.png" alt="" class="wp-image-970356" srcset="https://blog.finxter.com/wp-content/uploads/2022/12/image-144-1024x683.png 1024w, https://blog.finxter.com/wp-content/uploads/2022/12/image-144-300x200.png 300w, https://blog.finxter.com/wp-content/uploads/2022/12/image-144-768x512.png 768w, https://blog.finxter.com/wp-content/uploads/2022/12/image-144.png 1026w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<h2 class="wp-block-heading">Visualization Test Run</h2>



<p>Here are two test runs of the game, so you know how it works: <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f447.png" alt="👇" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="705" height="497" src="https://blog.finxter.com/wp-content/uploads/2022/12/guess_number.gif" alt="" class="wp-image-970329"/></figure>



<p>Try it yourself in the following interactive Python shell (click &#8220;Run&#8221; <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/25b6.png" alt="▶" class="wp-smiley" style="height: 1em; max-height: 1em;" />):</p>





<iframe loading="lazy" src="https://trinket.io/embed/python/efeb1ef670" width="100%" height="356" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe>





<h2 class="wp-block-heading">Python Code to Implement &#8220;Guess The Number&#8221; Game</h2>



<p>I&#8217;ll give you the code right away and follow up with some explanations.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import random


max_number = 10
guesses_allowed = 5

print("Welcome to the guessing game!")
print("I'm thinking of a number between 1 and {}. Can you guess what it is?".format(max_number))
print(f"You have {} tries to do so.".format(guesses_allowed))

number = random.randint(1, max_number)

for i in range(guesses_allowed):
    guess = int(input("What's your guess? "))

    if guess == number:
        print("Congratulations, you guessed the number in {} tries!".format(i + 1))
        break
    else:
        if guess > number:
            print("Your guess is too high. Try again.")
        else:
            print("Your guess is too low. Try again.")

if guess != number:
    print("Sorry, you didn't guess the number in {} tries. The game is over.".format(guesses_allowed))
</pre>



<p>Let&#8217;s dive into the explanation of the code:</p>



<h2 class="wp-block-heading">Python Code Explanation</h2>



<p>The code starts by importing the <code><a href="https://blog.finxter.com/python-random-module/" data-type="post" data-id="5030" target="_blank" rel="noreferrer noopener">random</a></code> module, which is used to generate a random number. The <code>random</code> module does not have to be installed because it&#8217;s already part of Python&#8217;s standard library. So it&#8217;ll work with any Python installation!</p>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f30d.png" alt="🌍" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended Tutorial</strong>: <a href="https://blog.finxter.com/how-to-install-python/" data-type="post" data-id="17770" target="_blank" rel="noreferrer noopener">How to Install Python?</a></p>



<p>Then, two global variables are defined: </p>



<ul class="wp-block-list">
<li><code>max_number</code>, which is the maximum number that can be generated by the Python script. This is included, so <code>max_number</code> can be the &#8220;magic number&#8221; itself. <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f9d9-200d-2642-fe0f.png" alt="🧙‍♂️" class="wp-smiley" style="height: 1em; max-height: 1em;" /></li>



<li><code>guesses_allowed</code>, which is the number of guesses that the player is allowed to make. We set the maximum number of guesses to 5, so the player must find the number in 5 tries.</li>
</ul>



<p>Next, the game is introduced to the player with a brief message explaining the game:</p>



<pre class="wp-block-preformatted"><code>Welcome to the guessing game!
I'm thinking of a number between 1 and 10. Can you guess what it is?
You have 5 tries to do so.</code></pre>



<p>We use Python&#8217;s powerful string formatting capabilities to customize the message to the global variable&#8217;s values. </p>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f30d.png" alt="🌍" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended Tutorial</strong>: <a href="https://blog.finxter.com/python-string-format/" data-type="post" data-id="26013" target="_blank" rel="noreferrer noopener">Python String Formatting <code>string.format()</code> Method</a></p>



<p>Then, a random number is generated using the <code><a href="https://blog.finxter.com/how-to-generate-random-integers-in-python/" data-type="post" data-id="32791" target="_blank" rel="noreferrer noopener">random.randint()</a></code> function, and the game begins.</p>



<p>The game is implemented using a <code>for</code> <a href="https://blog.finxter.com/python-loops/" data-type="post" data-id="4596" target="_blank" rel="noreferrer noopener">loop</a> that runs for <code>guesses_allowed</code> iterations. On each iteration, the player is prompted to enter their guess using the <code><a href="https://blog.finxter.com/python-input-function/" data-type="post" data-id="24632" target="_blank" rel="noreferrer noopener">input()</a></code> function. This guess is then compared to the randomly generated number.</p>



<p>If the player&#8217;s guess is correct, the game ends and a congratulatory message is displayed. Otherwise, the player is told whether their guess is too high or too low, and the loop continues.</p>



<p>After the <code>for</code> loop ends, the code checks whether the player has successfully guessed the number. If not, the game is over, and a message is displayed to that effect.</p>
<p>The post <a href="https://blog.finxter.com/creating-a-simple-guess-the-number-game-in-python/">Play the Python Number Guessing Game &#8211; Can You Beat It?</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Creating an Advent Calendar App in Python with AI Image Creation</title>
		<link>https://blog.finxter.com/creating-an-advent-calendar-app-in-python-with-ai-image-creation/</link>
		
		<dc:creator><![CDATA[Iain Checkland]]></dc:creator>
		<pubDate>Wed, 07 Dec 2022 17:05:05 +0000</pubDate>
				<category><![CDATA[App Development]]></category>
		<category><![CDATA[Artificial Intelligence]]></category>
		<category><![CDATA[Image Processing]]></category>
		<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=960956</guid>

					<description><![CDATA[<p>This blog describes a fun mini Python project using AI image creation for creating artwork for an advent calendar implemented using PyGame. Context It&#8217;s December 1st, and my daughter has just opened the first door on her physical advent calendar, counting down the days of the festival of general consumerism that some people call Christmas. ... <a title="Creating an Advent Calendar App in Python with AI Image Creation" class="read-more" href="https://blog.finxter.com/creating-an-advent-calendar-app-in-python-with-ai-image-creation/" aria-label="Read more about Creating an Advent Calendar App in Python with AI Image Creation">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/creating-an-advent-calendar-app-in-python-with-ai-image-creation/">Creating an Advent Calendar App in Python with AI Image Creation</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="731" height="731" src="https://blog.finxter.com/wp-content/uploads/2022/12/image-115.png" alt="" class="wp-image-961010" srcset="https://blog.finxter.com/wp-content/uploads/2022/12/image-115.png 731w, https://blog.finxter.com/wp-content/uploads/2022/12/image-115-300x300.png 300w, https://blog.finxter.com/wp-content/uploads/2022/12/image-115-150x150.png 150w" sizes="auto, (max-width: 731px) 100vw, 731px" /><figcaption class="wp-element-caption"><em><strong>Example</strong>: AI-Generated Image</em></figcaption></figure>
</div>


<p>This blog describes a fun mini Python project using <strong>AI image creation</strong> for creating artwork for an advent calendar implemented using <a href="https://blog.finxter.com/how-to-install-pygame-on-pycharm/" data-type="post" data-id="35078" target="_blank" rel="noreferrer noopener">PyGame</a>.</p>



<h2 class="wp-block-heading">Context</h2>



<p>It&#8217;s December 1st, and my daughter has just opened the first door on her physical advent calendar, counting down the days of the festival of general consumerism that some people call Christmas. Out pops a small chocolate with a festive robin embossed onto it.</p>



<p>I don’t really recall when the chocolate treat became ubiquitous. Back in my childhood days, advent calendar doors just opened to reveal an image.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="504" src="https://blog.finxter.com/wp-content/uploads/2022/12/image-116-1024x504.png" alt="" class="wp-image-961017" srcset="https://blog.finxter.com/wp-content/uploads/2022/12/image-116-1024x504.png 1024w, https://blog.finxter.com/wp-content/uploads/2022/12/image-116-300x148.png 300w, https://blog.finxter.com/wp-content/uploads/2022/12/image-116-768x378.png 768w, https://blog.finxter.com/wp-content/uploads/2022/12/image-116.png 1460w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /><figcaption class="wp-element-caption"><em><strong>Example</strong>: AI-Generated Image</em></figcaption></figure>
</div>


<p>This article describes a mini project to generate a virtual old-school Advent calendar using royalty-free bespoke images generated from Python using a third-party AI service through an API.</p>



<p>All code and some AI-generated image samples are available on <a rel="noreferrer noopener" href="https://github.com/finxter/ai-painted-advent-calendar" data-type="URL" data-id="https://github.com/finxter/ai-painted-advent-calendar" target="_blank">GitHub</a>.</p>



<h2 class="wp-block-heading">Painting the Images</h2>



<p>There are now many AI engines for creating images from a text description. This project uses <em>deepai. </em>Creating an image with the <em>deepai </em>API is pretty simple. They provide code samples for several languages on their site.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="730" height="730" src="https://blog.finxter.com/wp-content/uploads/2022/12/image-117.png" alt="" class="wp-image-961021" srcset="https://blog.finxter.com/wp-content/uploads/2022/12/image-117.png 730w, https://blog.finxter.com/wp-content/uploads/2022/12/image-117-300x300.png 300w, https://blog.finxter.com/wp-content/uploads/2022/12/image-117-150x150.png 150w" sizes="auto, (max-width: 730px) 100vw, 730px" /></figure>
</div>


<p>I further selected the engine for producing art in the impressionism style but you can choose from a range of other styles at <a href="https://api.deepai.org" target="_blank" rel="noreferrer noopener">https://api.deepai.org</a>.</p>



<p>The <strong><code>aipaint</code> </strong>function below uses the <code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-requests-library/" data-type="post" data-id="37796" target="_blank">requests</a></code> library <code>post</code> method to send a description string e.g. <code>"Christmas presents under tree"</code> to the API endpoint <a href="https://api.deepai.org/api/impressionism-painting-generator">https://api.deepai.org/api/impressionism-painting-generator</a> with an API key included in the header. </p>



<p>Note that the AI artist style forms parts of the end-point URL.</p>



<p>An API key is used to control access to the API service. The quickstart <strong><code>api-key</code></strong> below is only good for about 10 free requests. You can pay $5 for a new API key and 100 more request calls if you so wish.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def aipaint(description):
    r = requests.post(
        "https://api.deepai.org/api/impressionism-painting-generator",
        data={
            'text': description,
        },
        headers={'api-key': 'quickstart-QUdJIGlzIGNvbWluZy4uLi4K'}
    )
 
    ret = r.json()
    return ret
</pre>



<p>The <strong><code>aipaint()</code> </strong>function will return a JSON object, including an element called <strong><code>output_url</code> </strong>from which the image can be viewed. </p>



<p>The following is an example AI painting created, in the impressionist style, for the description <code>"Christmas presents under tree"</code>:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="325" height="321" src="https://blog.finxter.com/wp-content/uploads/2022/12/image-111.png" alt="" class="wp-image-960978" srcset="https://blog.finxter.com/wp-content/uploads/2022/12/image-111.png 325w, https://blog.finxter.com/wp-content/uploads/2022/12/image-111-300x296.png 300w" sizes="auto, (max-width: 325px) 100vw, 325px" /></figure>
</div>


<p>The <strong><code>output_url</code> </strong>will look something like this <code>https://api.deepai.org/job-view-file/eb654821-f89c-4065-9302-a702ad942971/outputs/output.jpg</code></p>



<p>Be warned when you read this &#8211; the above URL will no longer exist. The created image is only hosted by <em>deepai </em>for a few hours, so our advent calendar code will need to download to a local folder.  </p>



<p>To download the image we can use <strong><code>urlretrieve</code>:</strong></p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">painting=aipaint(description)
 
urllib.request.urlretrieve(painting['output_url'], filename)</pre>



<h2 class="wp-block-heading">Caching 25 Images</h2>



<p>The original hope was to create images on the fly as an advent door is opened, but as there is a cost for each API request and up to 30 seconds is required for each image to be generated by the AI engine and downloaded, an alternative approach was adopted in writing a <strong><code>prepaint.py</code></strong> script to create and download 25 images.</p>



<p><strong><code>prepaint.py</code></strong></p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import urllib.request
import config
import requests
import urllib.request
from os.path import exists
 
def aipaint(description):
    r = requests.post(
        "https://api.deepai.org/api/impressionism-painting-generator",
        data={
            'text': description,
        },
        headers={'api-key': 'quickstart-QUdJIGlzIGNvbWluZy4uLi4K'}
    )
 
    ret = r.json()
    return ret
 
count=1
 
while count&lt;=25:
   
    # pop off the first image description
    description=config.descriptions.pop(0)
    # push it back on at end (this ensures we cycle through descriptions and never run out )
    # obviously best if there are 25 descriptions though
    config.descriptions.append(description)
   
    filename='./images/image'+ (f"{count:02d}") +".jpg"
    if(exists(filename)):
        print(filename + " already exists")
    else:
        print("Painting: "+description)
        try:
            painting=aipaint(description)
            if(len(painting)&lt;2):
                if(painting['status']):
                    print("You've probably run out of deepai (free) credits.")
                    print("Status returned "+painting['status'])
            else:
                print("Storing as "+filename)
                urllib.request.urlretrieve(painting['output_url'], filename)
                print("Paint now dried on "+filename)    
        except Exception as ex:
            print("Paint "+filename+" failed")
            print(ex)
 
    count+=1
 
print("Paintings complete and paint has dried!")
print("Now run main.py to access the Advent calendar")</pre>



<p><strong><code>config.descriptions</code></strong> is a list of Christmas image descriptions. </p>



<p>Ideally, there should be 25 descriptions, but we treat the array as a circular queue so that every time we pop an item off the front, we push back at the end of the queue. </p>



<p>This just ensures we can generate 25 images even without 25 descriptions. My experimentation suggests you will not get the same image back from two requests with the same image description anyway!</p>



<p>Images are cached in an images folder with 25 filenames <strong><code>image01.jpg</code></strong> through <strong><code>image25.jpg</code></strong></p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">filename='./images/image'+ (f"{count:02d}") +".jpg"</pre>



<p>The script first checks whether an image already exists &#8211; if yes we just loop through to the next image.</p>



<p>With the code in <a href="https://github.com/finxter/ai-painted-advent-calendar" data-type="URL" data-id="https://github.com/finxter/ai-painted-advent-calendar" target="_blank" rel="noreferrer noopener">GitHub</a> I’ve included 25 images. If you want to generate your own just delete some or all from the images folder and edit the descriptions in <strong><code>config.py</code></strong>.</p>



<p>If you don’t yet want to purchase <em>deepai </em>credits &#8211; I recommend you just delete a few to experiment.</p>



<p>Sample output from the prepaint.py script</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="567" height="327" src="https://blog.finxter.com/wp-content/uploads/2022/12/image-112.png" alt="" class="wp-image-960984" srcset="https://blog.finxter.com/wp-content/uploads/2022/12/image-112.png 567w, https://blog.finxter.com/wp-content/uploads/2022/12/image-112-300x173.png 300w" sizes="auto, (max-width: 567px) 100vw, 567px" /></figure>
</div>


<h2 class="wp-block-heading">The Advent app</h2>



<p>I chose to use the PyGame library to produce the virtual Advent app. </p>



<p>Running<strong> <code>main.py</code></strong> launches a window with a grid of 25 doors. </p>



<p>Red doors indicate available doors to open based on the current date of the month. When a red labeled door is opened, a festive image is displayed along with a short promotion text that can be customized in <strong><code>config.py</code></strong></p>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow"><div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="503" height="534" src="https://blog.finxter.com/wp-content/uploads/2022/12/image-113.png" alt="" class="wp-image-960988" srcset="https://blog.finxter.com/wp-content/uploads/2022/12/image-113.png 503w, https://blog.finxter.com/wp-content/uploads/2022/12/image-113-283x300.png 283w" sizes="auto, (max-width: 503px) 100vw, 503px" /></figure>
</div></div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow"><div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="506" height="537" src="https://blog.finxter.com/wp-content/uploads/2022/12/image-114.png" alt="" class="wp-image-960990" srcset="https://blog.finxter.com/wp-content/uploads/2022/12/image-114.png 506w, https://blog.finxter.com/wp-content/uploads/2022/12/image-114-283x300.png 283w" sizes="auto, (max-width: 506px) 100vw, 506px" /></figure>
</div></div>
</div>



<p>A click on the image re-displays the grid of calendar doors.&nbsp;</p>



<p>A click on the lower portion of the screen opens a browser with the configured URL.</p>



<p>The PyGame script itself is fairly straightforward. Just one interesting snippet to highlight: To arrange the doors in a ‘random’ order. An array of the numbers 1 to 25 is created (constants <strong>HEIGHT</strong> and <strong>WIDTH</strong> are both defined as 5 in <strong><code>config.py</code></strong>). </p>



<p>This array is shuffled using <strong><code><a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-shuffle-two-arrays-in-unison-in-python/" data-type="post" data-id="671520" target="_blank">random.shuffle</a></code></strong>. By pre-setting the random seed to a set figure (here 1 was chosen), the same random shuffle is produced every time the <strong><code>main.py</code></strong> is run.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">doormap=list(range(1,HEIGHT*WIDTH+1))
random.seed(1)
random.shuffle(doormap)</pre>



<h2 class="wp-block-heading">Appendix &#8211; Full Code</h2>



<p>Here are the two code files:</p>



<p><code><strong>config.py</strong></code>:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">HEIGHT = 5
WIDTH = 5

descriptions=["Christmas presents under tree",
                "Santas Elf",
                "Santa in sleigh flying over a town delivering gifts on christmas eve",
                "candy cane on an christmas tree",
                "a festive robin redbreast",
                "a snowman with carrot nose and presents",
                "fairy on top of a christmas tree",
                "children playing with christmas presents",
                "christmas lunch",
                "christmas carol singers", 
                "christmas bells in a christmas tree",
                "rudolph the red nosed reindeer",
                "Santa in sleigh",
                "two snowmen with presents", 
                "snowy village scene",
                "christmas decoration",
                "christmas bells",
                "christmas snowflake",
                "christmas pudding with custard",
                "christmas feast with turkey",
                "father christmas laughing", 
                "christmas baby in a manger",
                "christmas mulled wine",
                "children enjoying playing with a new toy train",
                ]

gifts=[('8 python cheat sheets','https://blog.finxter.com/python-cheat-sheets/'),
('the finxter academy','https://academy.finxter.com/'),
('the finxter app','https://app.finxter.com/learn/computer/science/'),
('the finxster freelancer course','https://finxter.gumroad.com/l/python-freelancer/'),
('The Ultimate Guide to Start Learning Python','https://blog.finxter.com/start-learning-python/'),
('Coffee Break Numpy book','https://www.amazon.com/gp/product/B07WHB8FWC/ref=as_li_tl?ie=UTF8&amp;tag=finxter-20&amp;camp=1789&amp;creative=9325&amp;linkCode=as2&amp;creativeASIN=B07WHB8FWC&amp;linkId=447a5019492081d1b2892d9470bb29fc'),
('Leaving the Rat Race with Python book','https://www.amazon.com/Leaving-Rat-Race-Python-Developing-ebook/dp/B08G1XLDNB/ref=sr_1_5?qid=1670149592&amp;refinements=p_27%3AChristian+Mayer&amp;s=digital-text&amp;sr=1-5&amp;text=Christian+Mayer'),
('Coffee break Python book','https://www.amazon.com/Coffee-Break-Python-Kickstart-Understanding-ebook/dp/B07GSTJPFD/ref=sr_1_4?qid=1670149592&amp;refinements=p_27%3AChristian+Mayer&amp;s=digital-text&amp;sr=1-4&amp;text=Christian+Mayer'),
('Coffee Break Python Slicing','https://www.amazon.com/Coffee-Break-Python-Slicing-Workouts-ebook/dp/B07KSHLLG5/ref=sr_1_8?qid=1670149592&amp;refinements=p_27%3AChristian+Mayer&amp;s=digital-text&amp;sr=1-8&amp;text=Christian+Mayer'),
('Coffee Break Pandas','https://www.amazon.com/Coffee-Break-Pandas-Puzzles-Superpower-ebook/dp/B08NG8QHW7/ref=sr_1_9?qid=1670149592&amp;refinements=p_27%3AChristian+Mayer&amp;s=digital-text&amp;sr=1-9&amp;text=Christian+Mayer'),
('',''),</pre>



<p><code><strong>main.py</strong></code>:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import pygame
import sys
import time
import random
import datetime
import webbrowser
import config

HEIGHT = config.HEIGHT
WIDTH = config.WIDTH
LINEHEIGHT = 30
CLICKABLEHEIGHT = 150
FONT = 'verdana'

# Colors
BLACK = (0, 0, 0)
GRAY = (200, 200, 200)
WHITE = (255, 255, 255)
RED = (200, 0, 0)

# use a seeded random shuffle on numbers 1 to 25 
# specify seed to always generate the same random sequence of door labels for our 5x5 grid
doormap=list(range(1,HEIGHT*WIDTH+1))
random.seed(1) 
random.shuffle(doormap)

#get current time
d = datetime.datetime.now()
#get the day of month
datemax=int(d.strftime("%d"))

#lambda function to convert eg 1 to 1st, 2 to 2nd
ordinal = lambda n: "%d%s" % (n,"tsnrhtdd"[(n//10%10!=1)*(n%10&lt;4)*n%10::4])


# Create game
pygame.init()
size = width, height = 500, 500
screen = pygame.display.set_mode(size)
pygame.display.set_caption('Finxter Advent Calendar')

#font_name = 'calibr'#pygame.font.get_default_font()
bigfont = pygame.font.SysFont(FONT, 20)
hugefont = pygame.font.SysFont(FONT, 40)

# Compute board size
BOARD_PADDING = 10
board_width = width - (BOARD_PADDING * 2)
board_height = height - (BOARD_PADDING * 2)
cell_size = int(min(board_width / WIDTH, board_height / HEIGHT))
halfcell_size=cell_size/2+10
board_origin = (BOARD_PADDING, BOARD_PADDING)

# utility function to add text to screen
def addText(text, position, color):
    giftText = bigfont.render(text, True, color)
    giftRect = giftText.get_rect()
    giftRect.center = position
    screen.blit(giftText, giftRect)

# start from the main grid when dooropen>0 it indicate the door/image to display
dooropen=0

while True:

    # Check if game quit
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

    screen.fill(BLACK)

    if dooropen:

        # paint the correct image onto the screen
        filename='images/image'+ (f"{dooropen:02d}") +".jpg"
        image = pygame.image.load(filename)
        rect = image.get_rect()
        screen.blit(image, rect)

        # going to create a semi transparent clickable area which can link to a URL 
        # the URL 'gifts' are stored in the imported config
        giftlabel,gifturl = config.gifts[dooropen%len(config.gifts)]
        s = pygame.Surface((width,CLICKABLEHEIGHT))  
        s.set_alpha(200)            
        s.fill(GRAY)
        screen.blit(s, (0,height-CLICKABLEHEIGHT))
        clickable = pygame.Rect(0,height-CLICKABLEHEIGHT,width,CLICKABLEHEIGHT)

        # add text to the clickable area
        if(dooropen==25):
            addText("It's Christmas!", ((width / 2), 4*cell_size+LINEHEIGHT), RED)
        else: 
            addText("On the "+ ordinal(25-dooropen) +" night before xmas", ((width / 2), 4*cell_size), WHITE)
            addText("Finxter brought unto me:", ((width / 2), 4*cell_size+LINEHEIGHT), WHITE)
            addText(giftlabel, ((width / 2), 4*cell_size+(2*LINEHEIGHT)), RED)

        # open URL in browser if clickable area clicked
        # otherwise close the door by setting dooropen to 0
        click, _, _ = pygame.mouse.get_pressed()
        if click == 1:
            mouse = pygame.mouse.get_pos()
            if clickable.collidepoint(mouse) :
                time.sleep(0.2)
                webbrowser.open(gifturl, new=dooropen, autoraise=True)
            else:
               dooropen = 0
            time.sleep(0.2)

        pygame.display.flip()
        continue

    # Draw board
    cells = []
    for i in range(HEIGHT):
        row = []
        for j in range(WIDTH):

            # Draw rectangle for cell
            rect = pygame.Rect(
                board_origin[0] + j * cell_size,
                board_origin[1] + i * cell_size,
                cell_size, cell_size
            )
            pygame.draw.rect(screen, GRAY, rect)
            pygame.draw.rect(screen, WHITE, rect, 3)

            doornumber=doormap[(j*HEIGHT)+i]

            label = hugefont.render(str(doornumber), True, RED if doornumber&lt;=datemax else WHITE)
            labelRect = label.get_rect()
            labelRect.center = (j * cell_size+halfcell_size, i * cell_size+halfcell_size)
            screen.blit(label, labelRect)

            row.append(rect)
        cells.append(row)

    left, _, right = pygame.mouse.get_pressed()

    if left:
        mouse = pygame.mouse.get_pos()
        for i in range(HEIGHT):
            for j in range(WIDTH):
                if cells[i][j].collidepoint(mouse) and dooropen==0:
                    dooropen=doormap[(j*HEIGHT)+i]
                    # did they attempt to open a door ahead of current date
                    # dont allow that!
                    if dooropen>datemax:
                        dooropen=0
                    time.sleep(0.2)

    pygame.display.flip()</pre>



<p><code><strong>prepaint.py</strong></code>:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import urllib.request
import config
import requests
from os.path import exists

def aipaint(description):
    r = requests.post(
        "https://api.deepai.org/api/impressionism-painting-generator",
        data={
            'text': description,
        },
        headers={'api-key': 'quickstart-QUdJIGlzIGNvbWluZy4uLi4K'}
    )

    ret = r.json()
    return ret

count=1

while count&lt;=25:
    
    # pop off the first image description 
    description=config.descriptions.pop(0)
    # push it back on at end (this ensures we cycle through descriptions and never run out )
    # obviously best is there are 25 descriptions though
    config.descriptions.append(description)
    
    filename='./images/image'+ (f"{count:02d}") +".jpg"
    
    if(exists(filename)):
        print(filename+" already exists")
    else:
        print("Painting: "+description)
        try:
            painting=aipaint(description)
            if(len(painting)&lt;2):
                if(painting['status']):
                    print("You've probably run out of deepai (free) credits.")
                    print("Status returned "+painting['status'])
            else:
                print("Storing as "+filename)
                urllib.request.urlretrieve(painting['output_url'], filename)
                print("Paint now dried on "+filename)     
        except Exception as ex:
            print("Paint "+filename+" failed")
            print(ex)

    count+=1

print("Paintings complete and paint has dried!")
print("Now run main.py to access the Advent calendar")</pre>
<p>The post <a href="https://blog.finxter.com/creating-an-advent-calendar-app-in-python-with-ai-image-creation/">Creating an Advent Calendar App in Python with AI Image Creation</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>

<!--
Performance optimized by W3 Total Cache. Learn more: https://www.boldgrid.com/w3-total-cache/?utm_source=w3tc&utm_medium=footer_comment&utm_campaign=free_plugin

Page Caching using Disk: Enhanced 
Minified using Disk

Served from: blog.finxter.com @ 2026-04-27 01:14:28 by W3 Total Cache
-->