Beginners Python Project: How to generate QR codes?

Hello world 👋🏻 my name is Francisco, fcoterroba on the Internet and today I bring you a post in which we are going to make, as always, step by step, with good handwriting and explaining each line of the code, a QR code generator that will also allow Save the image to share it later on your social networks or website. ⬜⬛

Before starting, although I will explain what it is later, I recommend you visit a post that I uploaded more than a month ago, in which I explain many of the computer terms most used in our daily lives. (Yes, QR included.) 😁. You can reed the post here.

I also want to remind you that a few months ago I uploaded a video to my YouTube channel, very interesting, focused on home automation. Specifically, we connect, configure and install a smart light bulb 💡 with which you can change its color, turn it off, turn it on and much more simply by using your mobile phone and/or voice assistants such as Google, Alexa, etc. 👇🏻

To conclude, I also recommend read my post from last week in which we also did a project for beginners in Python. Specifically, a fully functional calculator.
In addition, at the beginning of the post we give several guidelines to get started in this language, as well as the installation of environment variables, IDE configuration, etc. 😵

Now yes, let's start!

What are QR codes?

A QR code is a square two-dimensional barcode that can store encoded data. Most of the time the data is a link to a website (URL).
Nowadays, QR codes can be seen on brochures, posters, magazines, etc. You can easily detect these two-dimensional barcodes around you. QR codes allow you to interact with the world through your smartphone.
Specifically, a QR Code extends the data available to any physical object and creates a digital measure for marketing operations. This technology allows and accelerates the use of mobile web services: it is a very creative digital tool.

In short, a QR code is a code similar to a barcode, but with a square shape in which a word, image, link or any other type of file is encoded. 🔛

Nowadays, QR codes are the order of the day and this is notably seen in restaurants or bars, in which a menu is no longer delivered to the consumer but rather a code of these characteristics is seen attached to the table, to that the user scans said code and can see the letter from their own mobile device. 📱

That is, in part, why I do this project, for all those people who want to learn how to program their own QR code encoder for their own business without depending on any third party. 😀

QR DECODER ON THE COMMAND LINE

Firstly, as we always do here, I am going to show you a small GIF of what you are going to learn to program by reading this simple post! 😁

It's cool, right? Well let's get started! 👀

The first thing we should do is open our favorite IDE (in my case it is Visual Studio Code) 💙

Although I say it every time I make a post about Python, I remember that in this programming language it is not necessary to specify what type the variable will be (Char, float, integer,...), unlike many other programming languages since, Python 🐍, it will automatically understand the type of variable depending on what we save in it.

For this project (and for almost all of them, really) I like to import both the package time (import time) ⌚ like the package sys Since, I like to set a few seconds to make it easier for the user to read the screen. Its use is simply writing time.sleep(x) changing the by a certain number, in seconds.
The sys package is used to perform operating system functions, among many, the one I mainly use is sys.exit() to close the program when the user requests it.
Finally, for this specific project we must import the package qrcode, which is what will perform the code generation function.

Comments in Python are written by putting the symbol at the beginning of the line #

With print, as in almost all programming languages, we are going to write on the screen ✍🏻.

Lastly, but probably most importantly. In this project we are going to see the functions in programming. Functions, in short, are a piece of code that, even if written, will never be activated until it is invoked. 🧙🏻‍♂️

Well, after explaining all that previously, commenting on a few lines of code, importing the necessary packages, preparing the first function and making a presentation to the program, we will have something like this:

#Importado de los paquetes necesarios
import time
import qrcode
import sys

#Función para generar el código QR
def generado_Codigo(): 
    print("***********************************************************************************************") 
    print("Hola mundo! Soy fcoterroba, puedes visitar mi web en www.fcoterroba.com")
    time.sleep(2)
    print("Este es un programa que te pide un enlace o texto y te genera un código QR en formato PNG.")
    time.sleep(3)

With this we will have created a very fast, interesting and minimalist main screen.

We now need to ask the user to write the link or text that they want to encode to QR.

To do this we must create the name of the variable followed by an input. 📥

Subsequently, comes the important part of coding in which we will create a qrcode.make object (variable in question). Giving it a name, obviously. 🤓

Almost to finish, we open said image to add the name correctly using the option open("fileName.extension", "wb").
Finally, we save said image using the method save. 🤯

We should have something like this 👇🏻

 	#Preguntamos al usuario qué quiere codificar
	codificar = input(f"COMENCEMOS!\n¿Qué palabra o enlace quieres que te codifique en QR? ")
    print("Codificando...")
    time.sleep(3)
    img = qrcode.make(codificar)
    f = open(codificar+"_QR.png", "wb")
    img.save(f)
    print(f"LISTO!\nTienes la imagen correctamente creado con el nombre {codificar}_QR.png")
    time.sleep(2)
	preguntar_Opcion()

With this we would have correctly created the file and it would have been saved in the folder in question where the python script is hosted. 🐍

Later I made another function that asked the user (hence the invocation in the last line), at the end of each QR generation, if they wanted to make some more code or if they wanted to exit the program directly. (Now is where the package comes into play sys). 👦🏻

This function is very simple, it only has one input for the user to write the option they want to do and two if/else conditions to exit the program or invoke the function. generado_Codigo().

Finally, let us not forget, outside of the functions and as the last line of code, we must invoke the function again generado_Codigo() because, otherwise, the program would never start. ♾

def preguntar_Opcion():
    opcion = input(f"¿Qué quieres hacer ahora? (H)acer otro código | (S)alir del programa\n")
    if opcion=='h' or opcion=='H':
        generado_Codigo()
    else:
        time.sleep(0.4)
        print("Hasta pronto! No olvides visitar mi web www.fcoterroba.com")
        sys.exit()

generado_Codigo()

We would have something like this:

And that's all for today guys, I hope you liked this interesting post! You can tell me in the comments anything you want: doubts, queries, advice, etc. Don't forget to follow me on TwitterFacebookInstagram and LinkedIn. See you next week!

Leave a Reply

Your email address will not be published. Required fields are marked *