Interface LCD 16x2 with Raspberry Pi 4

Hello friends, I hope you all are doing great. Today, I am going to share the 6th lecture in the Raspberry Pi 4 Programming series. We're glad you could join us for another lesson in our comprehensive Raspberry Pi programming guide. In today's guide, I'll show you how to interface a 16x2 LCD screen with Raspberry Pi 4.

So, let's get started:

Interface LCD 16x2 with Raspberry Pi 4

Today, we are going to interface a 16x2 LCD screen with Raspberry Pi 4. At first, we will print the "Hello World" text on the LCD, and in the last section, we will implement the scrolling and blinking of text on the LCD.

  • Here's the video tutorial on LCD interfacing with Raspberry Pi 4:


Components Required

We will need the following components for today's project:

    • Raspberry Pi 4.
    • Micro SD Card.
    • 16x2 LCD.
    • Breadboard.
    • Jumper wires.

    LCD 16x2 Display

    • A liquid crystal display, or LCD, is a versatile electronic display module. The 16x2 LCD module is used in electronic gadgets and circuits to display data normally sensor values.
    • LCD 16x2 has 16 columns and 2 rows, which means we can write 32 characters on it.
    • This LCD uses a 5x7 pixel matrix to show each character and 224 distinct characters/symbols can be displayed on the 16x2 programmable alphanumeric dot matrix display.
    • The Command register and Data register are the two command types in this LCD.
    • Simple LCD screens use a controller from the HD44780 family.
    • LCDs have supplanted CRTs (Catalyst Ray Tubes) in the screen manufacturing industry because CRTs are bulkier, heavier, and consume more energy than LCDs. LCD screens are more slender than their CRT counterparts.
    • Since LCDs are based on a light-blocking rather than a light-dissipating technology, they require less electricity than LED panels.
    • LCDs are everywhere, from CD, DVD players and digital watches to computers and televisions.

    LCD 16×2 Pinout

    • LCD 16x2 has 16 pins in total, where 8 pins are used for data transmission, while the remaining 8 pins are used to control LCD.
    • LCD 16x2 Pinout is shown in the below figure:
    • Pin 1 and 2 are power pins and we need to provide GND and +5V to these pins respectively.
    • Pin 3 is Contrast Pin and controls the brightness of LCD, so we normally place a potentiometer at this pin, to get the desired brightness.
    • Pin 4 is the register select pin, used to select the Command Register or Data Register.
    • Pin 5 is the Read/Write Pin, it needs to set LOW if you want to write on the LCD and needs to set HIGH if you want to read from the LCD.
    • Pin 6 is Enable Pin, used to enable the LCD by setting it HIGH.
    • Pins 7-14 are data pins(labeled D0-D7) and are used to get data for the LCD.
    • Pin 15 & 16 are power pins and are used for the backlight of the LCD.
    • Below you'll find a diagram depicting a standard LCD board's pin configuration.

    The header pins of 16x2 monitors are not pre-soldered. Normally a male header pin is soldered to the LCD pin holes.

    Modes of Communication

    We can perform 2 types of communication modes in LCDs, named:

    • 8-Bit Mode.
    • 4-Bit Mode.

    In 8-Bit mode, all 8 data pins are used to send data, while in 4-Bit mode, the last 4 pins(D4-D7) are used for data transmission.

    LCD Registers

    LCDs employ two distinct registers:

    • Data register.
    • Command register.

    You can use the RS pin on LCD to alter the register. If RS is High, we are accessing the data register and if it's Low, we are accessing the command register.

    The LCD's command register keeps track of the user's command. Pre-display data is saved in the data register. In order to manipulate the display, one must first load the instruction register with commands and then load the data registers to display the data. If you're working on a Raspberry Pi project and want to avoid learning low-level commands, you can use the Liquid Crystal Library instead.

    LCD Brightness

    The screen's brightness can be adjusted from Pin 3, normally a potentiometer is placed at Pin 3 to adjust the brightness. You can also use a resistor if you don't have a potentiometer. If a resistor is used, try one between 5k-10k ohms. You should experiment with a few different values to get the optimal resistance.

    Working Principle

    LCD works on the principle of light transmission from one layer to the next via molecules. These units vibrate and align themselves in a way that the polarized sheet gets at an angle of 90 degrees, allowing light to pass through. In other words, these molecules inspect the information on every pixel. Every single pixel uses the light absorption technique to display the digits. It is necessary to adjust the molecular orientation to the incident light angle in order to show the value.

    Circuit Diagram of RPi4 with LCD

    The 16x2 LCD screen can easily be connected to the Raspberry Pi 4. There will be a lot of cables to connect because LCD has 16 pins, but nothing too complicated. Here's the schematic of the pin connections between RPi4 and LCD:

    1. Connect Pin 1, 5(R/W Pin) and 16 of the LCD module to the Ground(GND).
    2. Connect Pin 2 and 15 of the LCD screen to Vcc(+5V).
    3. Connect Pin 3 to the Potentiometer's middle Pin, while the remaining two pins of the potentiometer need to connect to Vcc and GND.
    4. Connect Pin 4 of the LCD screen to the GPIO25(Pin 22) of Raspberry Pi 4.
    5. Connect Pin 6 of the LCD module to the GPIO24(Pin 18) of Raspberry Pi 4.
    6. Pin 11(D4) is connected to GPIO23(Pin 16).
    7. Pin 12(D5) is connected to  GPIO17(Pin 11).
    8. Pin 13(D6) is connected to GPIO18(Pin 12).
    9. Pin 14(D7) is connected to GPIO22(Pin 15).

    Having done so, the screen should power up and establish a connection with the RPi.

    Python Code for Rpi4 with LCD 16x2

    The newest Raspbian release has all the necessary packages loaded out of the box to allow for GPIO communication. But we need to install the Liquid Crystal Library to work on the LCD. Let's do that:

    Python Library for LCD

    • We will install the Adafruit LCD library.
    • It was made with Adafruit LCD boards in mind, but it can also be used with boards from other manufacturers. If the controller on your display board is an HD44780, you shouldn't have any problems.
    • First of all, use the below command to clone the necessary git directory onto the Raspberry Pi:

    git clone https://github.com/pimylifeup/Adafruit_Python_CharLCD.git

    • After that, navigate to the directory where the clone was created and double-click the setup file or use the below commands to install the library:

    cd ./Adafruit_Python_CharLCD

    sudo python setup.py install

    After the installation, you can use the Adafruit library from any Python program on the Pi. Just paste this line into the beginning of your Python file to make use of the library.

    import Adafruit_CharLCD as LCD

    Interacting with the LCD Screen

    The Adafruit LCD library makes it simple to display data from Raspberry Pi to LCD screen. The library package also has several working examples of utilizing the LCD. Before running any of these examples, make sure the pin parameters at the top of the program reflect your setup. My Circuit should yield the following results.

    lcd_rs        = 25 

    lcd_en        = 24

    lcd_d4        = 23

    lcd_d5        = 17

    lcd_d6        = 18

    lcd_d7        = 22

    lcd_backlight = 4

    lcd_columns = 16

    lcd_rows = 2

    • Enter the below commands to access one of the sample files:

    cd ~/Adafruit_Python_CharLCD/examples/

    sudo nano char_lcd.py

    Change the values in this section to match the ones described above for the pin configuration. To save the code, hit CTRL+X+Y on your keyboard. To execute this code, open a terminal and type Python followed by the name of the file (including the extension).

    python char_lcd.py

    Functions and Python Code

    In this session, I'll go over the fundamental Python methods for interacting with the screen. To initialize the pins, it is necessary to invoke the following class. Before calling the class, make sure all the parameters have been defined.

    lcd = LCD.Adafruit_CharLCD(lcd_rs, lcd_en, lcd_d4, lcd_d5, lcd_d6, lcd_d7, lcd_columns, lcd_rows, lcd_backlight)

    After that, you can adjust the screen to your liking. In this short guide, I'll give you a taste of what you can do with the Adafruit library.

    • By calling "home()", you can return the cursor to its original position in the first column of the first line.
    • The command "clear()", wipes the LCD clean, making it completely blank.
    • Set the current cursor position using "set cursor(col, row)". The column, as well as row numbers, are supplied as arguments, which determine the location i.e. "set cursor (1,4)".
    • The display can be turned on or off with the enabled "display(enable)" function.
    • The cursor can be displayed or hidden with the "cursor(show)" function. If you wish to see the pointer, set this to true.
    • The cursor blinks on and off with the "blink(blink)" command. Setting this to true will cause the cursor to blink.
    • The move left() and move right() functions, shift the pointer to the left and right by one cell.
    • The cursor direction can be changed using set right to the left() or set left to right().
    • If "autoscroll" is true, the text will right align from the cursor. The text will be aligned to the left if this option is false.
    • Message (text) - Outputs the given text on the screen. Include new lines (n) in your message if you'd like.

    The Ardafruit CharLCD.py file in the Adafruit CharLCD folder of the Adafruit Python CharLCD folder will list all the accessible methods.

    sudo nano ~/Adafruit_Python_CharLCD/Adafruit_CharLCD/Ardafruit_CharLCD.py

    My simple script for displaying user-entered text is included below.

    #!/usr/bin/python

    # Example using a character LCD connected to a Raspberry Pi

    import time

    import Adafruit_CharLCD as LCD

    # Raspberry Pi pin setup

    lcd_rs = 25

    lcd_en = 24

    lcd_d4 = 23

    lcd_d5 = 17

    lcd_d6 = 18

    lcd_d7 = 22

    lcd_backlight = 2

    # Define LCD column and row size for 16x2 LCD.

    lcd_columns = 16

    lcd_rows = 2

    lcd = LCD.Adafruit_CharLCD(lcd_rs, lcd_en, lcd_d4, lcd_d5, lcd_d6, lcd_d7, lcd_columns, lcd_rows, lcd_backlight)

    lcd.message('Hello\nworld!')

    # Wait 5 seconds

    time.sleep(5.0)

    LCD.clear()

    text = raw_input("Type your name in the terminal ")

    LCD.message(text)

    # Wait 5 seconds

    time.sleep(5.0)

    LCD.clear()

    lcd.message('Goodbye\nWorld!')

    time.sleep(5.0)

    LCD.clear()

    If everything's fine, you will get something printed on your screen, as shown in the below figure:

    If your Python script isn't producing any output on the screen, it's probably due to incorrectly configured pins.

    Conclusion

    This guide walked you through connecting the Pi 4 to a 16x2 LCD. You can accomplish so much more with this sleek screen. You may set up a script to run at boot time and show useful information like the IP address, time, temperature, and more.

    You can also incorporate a wide variety of interesting sensors with this screen. A temperature sensor like the DS18B20 would be ideally suited for use with the screen. Refresh the screen every few seconds to reflect the current temperature.

    Please let me know how successful you were in putting up a Pi 4 with LCD 16x2 display with the help of this tutorial. In the next tutorial, we will interface Keypad 4x4 with Raspberry Pi 4. Till then, take care. Have fun !!!

    Interface RFID Module RC522 with Raspberry Pi 4

    We're glad you could join us for another lesson in our comprehensive Raspberry Pi programming guide. I will show you how to install and connect the RFID card chip to your Raspberry Pi through step-by-step instructions.

    Modern security systems would only be complete using radio frequency (RFID) devices. To control who can enter a facility or which rooms they can access, RFID chips and card readers are employed. The RFID card's unique identification number can be read wirelessly with a wall-mounted RFID reader. A door will only unlock and allow entry if the RFID card's unique identification number matches a list of approved cards.

    It's fun to tinker with this circuit, and it may be used in many other applications, from opening locks to taking attendance. The MFRC522 microcontroller underpins the RFID RC522, a cheap RFID (Radio-frequency identification) reader/writer. The RFID tags can connect with this microcontroller using an electromagnetic field it generates at 13.56MHz and sends to them via the SPI protocol. If you want to use your RFID RC522 with tags, you must ensure that they are 13.56MHz compatible. We'll walk you through the wiring of the RC522 and the creation of Python programs to communicate with the chip, allowing you to read and write RFID tags. Adding a 16x2 LCD to the Raspberry Pi is a simple extension of this tutorial, and it can be helpful if you need to show the user some information or provide a visual prompt.

    Where To Buy?
    No.ComponentsDistributorLink To Buy
    1BreadboardAmazonBuy Now
    2Jumper WiresAmazonBuy Now
    3Raspberry Pi 4AmazonBuy Now

    Components

    • Raspberry Pi

    • Micro SD Card

    • Power Supply

    • RC522 RFID Reader

    • Breadboard

    • Breadboard Wire

    What is an RFID RC522

    An RFID reader reads the tag's data when a Rfid card is attached to a specific object. An RFID tag communicates with a reader via radio waves.

    In theory, RFID is comparable to bar codes because it uses radio frequency identification. While a reader's line of sight to the RFID tag is preferable, it is not required to be directly scanned by the reader. You can only read an RFID tag up to three feet away from the reader. The RFID tech quickly scans many objects, making it possible to identify a specific product rapidly and effortlessly, even if it is sandwiched between several other things.

    Explained: the functioning of rfid readers and writers

    Major components of Cards and tags include an integrated circuit (IC) that stores the unique identification value and a copper that acts as the antenna.

    Inside the Rfid reader is another copper wire coil. This coil produces a magnetic field when current flows through it. Magnetic flux creates a current inside the wire coil when the card is brought close to the reader. This current can power the card's internal integrated circuit. The reader then takes in the card's serial number. A card reader will send the card's serial number to a central processing unit (CPU) like a Raspberry Pi for further processing.

    Assembling the RFID RC522

    When you buy an RFID RC522 Reader, you may discover that 90% of them do not have the header pins pre-installed. Due to a lack of pins, you'll have to solder them yourself; however, this is a relatively easy task, even for amateurs. Assuming the header pins that came with your RC522 are too large, you may snap them in half to reduce them to a single column of eight.

    Start by inserting the header pins into the RC522 from the top. The circuit may be easily placed on top of the connector pins by inserting the large side of the pins onto a breadboard. The breadboard's secure holding of the pins will make soldering them to the RFID circuit much simpler.

    Solder each pin individually by carefully heating your soldering iron and applying it to the pins. Remember that heating the junction slightly before to solder application increases the solder's adhesion and decreases the likelihood of generating a cold joint. When using solder, we advise you to be conservative. When you've finished soldering the header pins onto your RFID circuit, you'll be ready to move on with the guide.

    Wiring the RFID RC522

    There are eight different connectors on the RFID RC522. Except for the IRQ, we need to connect all these to the GPIO pins on our Raspberry Pi.

    This guide shows how to connect an RFID RC522 to a Breadboard and then to the Raspberry Pi's GPIO Pins, although you could also wire the components straight to the Pi.

    Simply connecting 7 of the Raspberry Pi's GPIO pins to the RFID RC522 reader is all needed to get it up and to run. Refer to the GPIO pin locations detailed in our tutorial and the table below when deciding how to wire your RC522.

    • SDA connects to Pin 24.

    • SCK connects to Pin 23.

    • MOSI connects to Pin 19.

    • MISO connects to Pin 21.

    • GND connects to Pin 6.

    • RST connects to Pin 22.

    • 3.3v connects to Pin 1.

    Setting up Raspbian for the RFID RC522

    We need to adjust the Raspberry Pi's settings before we can use the RFID RC522. Inconveniently, our RFID reader circuit relies on the Raspberry Pi's SPI (Serial Peripheral Interface), which is disabled by default. Worry not, though, as it is easy to restore this interface; follow our instructions below to set up your RPi and Raspbian to use the SPI port. Launch the raspi-config utility by opening a terminal and typing the following command.

    sudo raspi-config

    A menu of choices will appear when you use this tool. You may read up on all of these options in the raspi-config documentation. Choose "5 Interfacing Options" using the arrow keys. Select this choice, and then hit the Enter key. Once "P4 SPI" is selected in the next screen, press Enter once more to confirm your selection. To continue, use the arrow keys to choose "Yes" and then press Enter when prompted to confirm that you want to activate the SPI Interface. For the raspi-config utility to finish enabling SPI, you'll have to be patient for a while.

    The raspi-config tool's success in enabling the SPI interface will be shown by the display of the message "The SPI interface is enabled." Activating the SPI Interface requires a full reboot of the Raspberry Pi. Press Enter, and then ESC, to return to the terminal. If you want to restart the RPi, enter the following Unix instruction into the terminal.

    sudo reboot

    It is time to verify that Raspberry Pi has been activated now that it has rebooted. Checking if spi bcm2835 is available is as simple as running the following command.

    lsmod | grep spi

    If you get spi bcm2835, you're good to go with the rest of the tutorial. If you tried the preceding command and it didn't work, try the following three things. If the SPI component is not enabled, we can manually modify the boot config file by issuing the following code to our RPi.

    sudo nano /boot/config.txt

    You can use CTRL + W to search the configuration file for "dtparam=spi=on" If you think you have discovered it, look if it has a number in front of it. If there is, delete it because it disables the code. If you cannot find the line, add "dtparam=spi=on" to the very end of the file. To commit your modifications, use CTRL + X, followed by Y and Enter. You can double-check that the module has been activated by restarting your Raspberry Pi, as in Step 5.

    Getting Python ready for the RFID RC522

    After connecting our RFID circuit to the RPi, we can turn it on and start writing Python scripts to communicate with the chip. You'll learn how to read and write information to RFID chips by composing scripts like the ones we'll provide. These will serve as the foundation for future RFID RC522 tutorials and provide you with a fundamental understanding of how data is handled. The Raspberry Pi must be brought up to date with the most recent software versions before we can begin programming. Get the latest version of Raspbian for your Pi by running these two commands.

    sudo apt update

    sudo apt upgrade

    Installing the python3-dev, python-pip, and git packages is the last thing to do before moving forward. To get your RFID reader set up with this guide, type the following command into your Raspberry Pi's terminal.

    sudo apt install python3-dev python3-pip

    Now that we have python "pip" installed on our Raspberry Pi, we can install the spidev Python library. An integral part of this guide, the spidev library allows the RPi to communicate with the RFID via the SPI. Run the following command to get spidev set up on your Raspberry Pi via pip. It's important to remember that we're using sudo to guarantee that the package gets installed for everyone's usage, not just the logged-in user.

    sudo pip3 install spidev

    After getting the spidev library up and running on our Raspberry Pi, we'll move on to setting up the MFRC522 library with pip. Two files, in particular, are used by us, both of which are part of the MFRC522 library:

    This library, MFRC522.py, implements the RC522 interface for communicating with RFIDs via Raspberry Pi's SPI port.

    Simplifying the MFRC522.py file so that you only need to work with a small subset of its many functions, SimpleMFRC522.py is a significant time saver.

    Enter this command into your terminal to have pip setup the MFRC522 library on your Pi 4:

    sudo pip3 install mfrc522

    Now that the library has been transferred to the Pi, we can start writing code for the RFID RC522. First, we'll explore how to use the RC522 to program your RFID cards. Move on to the following part, where we will write our first Python code.

    Writing with the RFID RC522

    In this first Python script, we'll go over the steps needed to send information from the RC522 to RFID tags. This is made more accessible by the SimpleMFRC522 script, but we'll still break down the code's individual components for you. To begin, let's create a directory to hold the scripts we'll be using. Create the "pi-RFID" folder by using the following command.

    mkdir ~/pi-rfid

    To get started, navigate to the folder you just cloned and create the Write.py script in Python.

    cd ~/pi-RFID

    sudo nano Write.py

    Add the following blocks of code to this file. This code prompts you for some text, which it then uses to update the RFID Tag.

    #!/usr/bin/env python

    import RPi.GPIO as GPIO

    from mfrc522 import SimpleMFRC522

    The very first line of the code snippet instructs the terminal to use Python rather than another scripting language like Bash to parse and run the file. To guarantee that the GPIO Pins are reset when the script terminates, we must first import the RPi.GPIO package contains all the necessary functions for communicating with the GPIO Pins. The second import is our SimpleMFRC522 library, which will be used to communicate with the RFID RC522. Compared to the standard MFRC522 library, it dramatically simplifies working with the chip.

    reader = SimpleMFRC522()

    In this line, we make a new instance of the SimpleMFRC522 object, use its setup function, and save the result in our readers variable.

    try:

            text = input('New data:')

            print("Now place your tag to write")

            reader.write(text)

            print("Written")

    We enclose the following section of code with a try statement to ensure that any unforeseen problems are handled, and the code is cleaned up correctly. Python is whitespace sensitive; it uses tabs to distinguish between code sections, so keep them after trying. In this case, the second line reads a command-line input and stores it in a text variable using Python 3's input function.

    The third line makes advantage of print() to prompt the user to set the RFID tag onto the reader. After that, on line 4, we utilize our scanner object to instruct the RFID Circuit to write the text field's contents to a certain sector of the RFID tag. On line 5, after successfully writing to the RFID tag, we call print() once more to inform the user.

    finally:

            GPIO.cleanup()

    The script will terminate in the last two lines of code. The finally statement always follows the try statement. Thus the GPIO.cleanup() method is called after each iteration of the try block. These lines are essential because improper cleanup can disrupt the functionality of other programs. Upon completion, your script should be like the example given below.

    The file can be saved by pressing CTRL Plus X, Y, then ENTER once you've double-checked the code and are convinced it's correct. Now that the script is written, we need to put it through some testing. Get an RFID tag ready before running the script for testing. When you're ready, open the terminal on your Raspberry Pi and enter the following command.

    sudo python3 Write.py

    In this situation, we're just going to type in "any word" because it's easy to remember and short. Press the Enter key when you have finished writing and are ready to send. After that, your RFID Tag can be placed directly above your RFID circuit. It will immediately update the tag with fresh information when it does. You'd see the word "Written" on the command prompt if it worked. Now that you have your Write.py script completed, we can move on to explaining how to read information from the RFID RC522.

    Reading with the RFID RC522

    We have successfully programmed our RC522 to print to RFID tags and can now move on to writing a script to retrieve the data from the tags. First, we'll make sure we're in the correct location by switching directories, and then we'll use nano to start drafting the Read.py script.

    cd ~/pi-rfid

    sudo nano Read.py

    Incorporate the following code into this document. When an RFID tag is placed in the RFID reader, the script will wait until the tag's data has been read before displaying the results.

    This file's first line of code instructs the operating system on how to proceed when the user clicks the "Run" button. If you don't specify that it's a Python file, it'll try to run it like any other script. An initial RPi.GPIO import is made. Importing this library ensures that the Raspberry Pi's GPIO pins are cleaned up after script termination, as it contains all the necessary functions. SimpleMFRC522 is the second import. With the assistance functions included in this script, reading and writing to an RFID RC522 is a breeze, whereas, with them, the scripts would quickly grow to be manageable.

    This line is crucial because it invokes SimpleMFRC522's creation method, which returns an object that is subsequently stored in our reader variable.

    try:

            id, text = reader.read()

            print(id)

            print(text)

    The following code section will be encapsulated in a try block to allow us to handle any unforeseen errors gracefully. Because Python is sensitive to whitespace, you must use the 'tabs' as displayed following try:

    In this scenario, the second line of this code block initiates a call on our scanner object, instructing the circuits to begin scanning any Rfid card that is positioned on top of the reader. On the third and forth lines, we use print() to display the data we gleaned from the RFID Chip; this includes the tag's unique identifier and any text it may consist of.

    finally:

            GPIO.cleanup()

    The script ends with the last two lines of code. No of what happens inside the try block, the final statement is always executed afterward. No matter what, the GPIO.cleanup() code will be executed thanks to this try statement. It's vitally important, as not doing so can disrupt the proper operation of other scripts that rely on the GPIO. Your completed Read.py script for the RFID RC522 should resemble the example below.

    When you've double-checked your code and are satisfied with it, press Ctrl + X, then Y, and finally ENTER to save the file. The time has come to put our completed Read.py script to the test. Get ready to test the script by picking up any of the RFID tags. If you're all set, enter this command into the terminal on your Raspberry Pi.

    sudo python3 Read.py

    Now that the script is active, you can set your RFID Tag atop your RFID circuit. When the RFID tag is placed on top, the Python program will immediately begin reading the information from the tag and display the results on the screen. What a finished product might look like is shown below as an illustration.

    To test whether your Raspberry Pi is properly connected on the RFID RC522 Circuit, run the Read.py script and see if it returns any data that matches the text you wrote to the card in the Write.py script.

    Conclusion

    Connecting an RC522 RFID module to a Pi 4 makes reading MIFARE chips and cards is now possible. This might be very useful in security systems and other applications where identifying an item or person is required without the user having to physically interact with the device by pressing buttons, switching, or activating any sensors. Eventually, you should be able to use this to decipher the UID encoded on your MIFARE tags. You should know that these cards can be duplicated and assigned a new unique identifier (UID) if you plan on employing this technique in a security system. To ensure the safety of your system, you must ensure that no one learns your UID or gains remote access to your devices. The contactless tags are convenient because they can be attached to a keychain, and the cards are convenient because they can be carried in a wallet. Both things can be concealed inside others to give them a hidden identifier that the Pi can access. With the help of our Pi 4-powered RFID attendance systems guide, you can learn how to set up your RFID Reader/Writer for use in checking attendance. Our exploration of the RFID chip and the scripts above will continue in subsequent guides. A door security system is one of the fantastic DIY Pi ideas we'll look into. The next lesson will teach you how to connect a 16x2 LCD screen to a Raspberry Pi 4.

    4 Reasons Your Engineering Firm Needs Fleet Maintenance Software

    No matter your company's industry, you need fleet maintenance software. It’s something you need if your engineering firm has a fleet of vehicles. Failing to get the necessary tools is a bit like driving blind -- not the best course of action by any stretch of the imagination.

    If you’re not sold on the benefits of investing in fleet maintenance software, keep reading to learn more about four reasons you need it.

    1. Preventative Maintenance

    Fleet maintenance software will help your engineering firm with preventative maintenance. The software will make it easy to schedule maintenance so that your fleet of cars stays in good shape. 

    One of the worst things you can do is delay or ignore preventative maintenance. That will ultimately cost you in terms of downtime stemming from repairs. Preventative maintenance won’t eliminate the possibility of repairs, but it will reduce the odds of breakdowns . And breakdowns can become expensive if you also find yourself unable to use the company vehicles for business. Unplanned downtime is a no-no.

    2. Lower Repair Costs

    When your business invests in fleet maintenance software, you’ll also enjoy lower vehicle repair costs. Putting off maintenance means that small problems can morph into major issues that cost an arm and a leg to fix. So, it’s more cost-effective to invest in preventive maintenance than to postpone doing so and having to spend many times more to fund major repairs. 

    When considering the importance of your fleet, you can appreciate the need to ensure the vehicles are available and in good repair whenever they’re needed. You can increase uptime and reduce downtime by tackling issues as soon as they’re discovered so that they don’t worsen.

    3. Better Fuel Efficiency

    When you get one of the best fleet maintenance software applications, you’ll also benefit from better fuel efficiency. Proper maintenance and repairs will ensure your fleet of vehicles operates more efficiently, resulting in better fuel efficiency. You can also optimize routes so that drivers don’t take longer routes than necessary. And by keeping track of driver behavior, like speeding or hard braking, you can notify drivers of necessary changes. You can save a lot on fuel just by getting drivers to operate the fleet vehicles more responsibly.

    4. Fewer Headaches

    Who has time to worry about their fleet of vehicles? You have other things to worry about such as operating your engineering firm. When you’re taking good care of your cars, you won’t be left worrying about them. Instead of having to make frequent arrangements to have your inoperational cars towed to automotive facilities for repairs, you’ll be able to use them for business purposes. They’ll spend more time on the road and less time out of commission.

    That means you’ll have fewer headaches with your fleet of vehicles. Using a fleet maintenance software solution, you’ll be able to stay on top of things. And if things don’t get out of control, you’re less likely to have headaches over something going horribly wrong.

    If your engineering firm has a fleet of vehicles, it’s essential to consider the benefits of fleet maintenance software. Protecting your assets is a must if you want them to remain in good repair over the long haul. Getting a fleet of vehicles requires a tangible investment. If you want to protect your investment, then investing in fleet maintenance software is a good idea.

    Before settling on a platform, you’ll want to do research to find something that meets your company’s needs. When you find the right software, you’ll see up close and personal what the benefits of fleet maintenance software are all about.

    Tuple DataType in Python

    Hey peeps! Welcome to another tutorial on data types in Python. Our purpose in Python education is to get a grip on the basic concepts so that we may work on deep learning easily. In the previous lecture, we read a lot about lists as we are working on the subtypes of the sequence data type. In the present lecture, you are going to understand more types of sequences. If you know the list well, this lecture will be a piece of cake for you. We will start the introductions in just a bit, but before that, there must be a quick review of the topics that you are going to understand:

    • How do you introduce the tuples in Python?

    • What are some important characteristics of a tuple that must be kept in mind when we are dealing with it?

    • How can you practically perform the tuples in TensorFlow?

    • How do you associate tuples with the list?

    • Can you delete, update, add, or delete the elements in a tuple? If yes, then how?

    • Which is the way to delete the tuple entirely?

    All of these are important interview questions about the tuple and if you are dealing with these data types, you must know and perform these by yourself in TensorFlow. All the information about tuples will be discussed with you and you have to practice more and more in the code to understand the concepts.

    Tuple in Sequence 

    For the concept of a list, we have given you the reference of an array. This time, we will be mentioning the name of the list for better understanding. If we talk about the topic of today, a tuple is also a group of items that are arranged when required in Python. The working and the definition of the tuple seem like a list because both of them are types of a single data type, which is the sequence. But there are some differences that make them ideal for different kinds of situations. The following points will make this more clear:

    • The tuple is represented by enclosing the data in parentheses. 

    • A tuple is immutable, which means that once you declare the items in the tuple, you can not change them as you can in a list. 

    • When you try to change the value of the element in the tuple, an error is shown on the screen, so while declaring the new tuple, you have to be very clear about what is on your mind and what you want to do with the tuple. 

    • In a tuple, you can also use the function in the tuple and it becomes easy to perform different tasks through codes.

    • A single element in the tuple is necessary to build the tuple. In other words, unlike the strings, the tuple must contain at least one element in it.

    • In the tuple, any data type can be saved whether it is boolean, int, or string. Moreover, there is a possibility to add different types of data in a single tuple. So we can conclude that we can have a homogeneous or heterogeneous tuple according to our choice. 

      Order of The Tuple

      As we have mentioned, when using the tuple, we get the ordered list of objects, which means we get the specific order, and this order, once mentioned, can not be changed, unlike other data types of the sequence. 

      Unchangeable Tuple

      Not just the order, but the size, sequence, and entries are unchangeable, so during the initialization and declaration of the tuple, the concept must be clear about what you want from the particular tuple. 

      Duplication in Tuple

      Another thing that must be kept in mind is, the tuple has the index form, and therefore, every element has a specific number of indexes. This is the reason, the elements are easily accessible, and hence, you can also have duplication in the tuple. The elements are recognized by the index number, and therefore, the compiler knows when which element is being called.  

      Length of the Tuple

      The length is the number of elements in the tuple, and we have read about the length function in the previous lecture. Similar to the list, a tuple can also be used in the length function, and the programmer gets the length of the tuple. Right now, this function is not looking very attractive because we are dealing with small tuples. But take the case in your mind when the tuple contains hundreds or thousands of elements and get the length of the tuple in just a few moments. 

      Tuple in TensorFlow

      It is now time to go over some basic tuple-related code using TensorFlow. The steps for starting it are the same as those we always follow; have a look at these steps:

      • Open your Anaconda Navigator by browsing it from your window panel. 

      • Search for the Jupyter lab in the environment section. 

      • Wait for the PC to open the new tab in your browser. 

      • Go to the new cell.

      • Start coding.

      With the help of code, we will try to create a tuple, and then, by using the function on it we will try to retrieve the data from the tuple in different ways. So, have a look at the code given next and then guess the output in your mind.

      print('Make a tuple with stationaries item')

      myTuple=('pen', 'paper', 'eraser', 'pencil', 'sharpener', 'notebooks')

      print('The tuple has following items: ',myTuple)

      print()

      print('print only the third item of the tuple:', myTuple[3])

      print()

      print('print the item by using the index: ',myTuple[1])

      Now, have a look at the output. Is it exactly the same as you were expecting?

      You can see how simple it is to get the item from the tuple when it is declared in the tuple. This is the same as what we did with the list. But what if we want more than one element from the tuple at the same time?

      print('Make a tuple with fruits and prices in dollars')

      myTuple=('strawberry','kiwi','banana','orange','apple', 2.5,3,12, 4,6)

      print('The following items in the fruit shop are available: ',myTuple)

      print()

      print('print only the forth fruit of the fruit shop:', myTuple[-7])

      print()

      print('print the name of only fruits: ',myTuple[0:5])

      Looking at the code, you will observe that the negative number is used in the index. This is the way to tell the compiler that we are counting from the end of the index. Moreover, the index on the end side starts at 1 instead of zero. Another point to notice is that the start and end limits are specified by separating them with the colon, and as a result, we get the whole tuple in the output. 

      A new concept that is to be shared is that when you are providing the limits to the tuple, you have to take care that the right numbers are being used because it will then not work properly. You must be thinking that the compiler will throw the error when you feed the wrong limits in the tuple, but instead, the output will be empty, and you will get the parentheses with nothing in them.

      Another thing that must be mentioned here is that you can check whether the tuple has a specific element or not. For this, we get the help of a statement. We know that, until now, we have not learned about the statements, and therefore, we suggest just looking at the code and output to understand the concept. 

      print('Make a tuple with fruits and prices in dollars')

      myTuple=('strawberry','kiwi','banana','orange','apple', 2.5,3,12, 4,6)

      print('The following items in the fruit shop are available: ',myTuple)

      if "apple" in myTuple:

        print("Yes, 'apple' is in the present in the fruit shop")

      This program searches for the elements specified in the “if condition” and then prints the result on the screen. 

      How to Make Changes in A Tuple

       If you are reading this lecture from the beginning, you must be thinking we have mentioned again and again that a tuple is immutable and unchangeable. Yet, programmers have the logic and solutions to every problem, and if the programmers have specified the tuple and want some changes made to it, they can do so with the help of the list. It is one of the reasons why we have discussed the list before in this series. Have a look at the following code and output, and then we will discuss it in detail.

      print('Make a tuple with fruits and prices in dollars')

      myTuple=('strawberry','kiwi','banana','orange','apple', 2.5,3,12, 4,6)

      print('The following items in the fruit shop are available: ',myTuple)

      myList=list(myTuple)

      print(myList)

      myList[2]='pear'

      print(myList)

      myTuple=tuple(myList)

      print(myTuple)

      Copy this code and run it on your TensorFlow, you will get the following output:

      First, look at the brackets carefully and check the output in a sequence with the points given next:

      • At the start, the string message is shown, which shows the main title of the tuple. 

      • The name of the tuple here is “myTuple” and it contains the fruits’ names and prices.

      • To make the changes in the tuple, we have to use another approach, and we know the reason why. For this, we are using the list. It is possible to convert the list into a tuple and vice versa, and we are doing the same in this. We are just using the name of the data type as a function and inputting the name of the data type to be changed. So, we changed the tuple into a list and then made the changes according to our choice. 

      • By using the index number and feeding the value into the list, the list is updated. This can be observed with the help of square brackets.

      • Once we have seen the updated list, we can now easily convert it into a tuple again. 

      • The conversion is done with the same procedure, and we get the updated tuple. 

      This was a simple example, other operations such as the addition of the new element, deleting the elements from the tuple, removing the single elements from the tuple, etc. are done with the help of lists. 

      Deleting the Tuple Entirely

      Now that you know all the ways to initiate, use, and update the tuple in detail, a last method for the tuple is ready for you. In some cases, when you do not want to use a particular tuple for any reason, such as if you are no longer using it, you can do so in just a simple step. This is used in the programs when long calculations and collections of data types are needed for a particular time and then there is no need for them anymore. So for this, we use the delete operation. The programmers have to simply use the del keyword before the name of the tuple to be, and the compiler has to do its job well. Have a look at the example given next:

      Tuple = ("Artificial Intelligence", "Machine Learning", "Deep Learning")

      print(Tuple)

      del(Tuple)

      print(Tuple)

      So, when the compiler was on the second line, it showed us the results, but on the next line, when we deleted the declared tuple, the compiler was not able to show us the result because it had been removed from its memory.

      So, it was an informative data types lecture in which we clarified many concepts about tuples. These are the data types that belong to the class of sequences. We read a lot about it and started the discussion with the introduction. The tuple characteristics were thoroughly discussed, and then, with these in mind, we tested the functions of the tuple using TensorFlow examples. We attempted similar examples and carefully observed the operation of tuples, which also involved the list. In the next lecture, you will know more about the data types in Python, so stay connected with us.

      Automatic Garage Door with PLC Ladder Logic

      Hello my friends! I hope your doing very good. Today we are going to practice what we have learnt through the ladder logic tutorial series. We bring a new .project which is mostly exist in our daily life that is electrical door control. in garage for domestic and public garage, you should found automatic garage gate or door that is controlled by the PLC ladder logic program. So today we are going to implement the project including determining the input and output components, design the logic, programming and testing using the simulator.

      Project details

      Figure 1 shows the project’s components, inputs and outputs that are included in controlling the garage door. As you can see my friends, there are inputs like open, close, and stop requested by push buttons. Also, you can see sensors like the two limit switches on the bottom and on the top to prevent overload that might have occurred on the motors. Moving to the outputs, there are motor up and down directions, open, close, and ajar status indicators lamps. So what is the next step in our plan to achieve such job? Of course we need to list these inputs and outputs and give them addresses. Then we design the logic based on the user requirements and the safe operation.

      Inputs and Outputs list

      Table 1 lists the inputs and outputs showing the name in the first column, the description In the second column, while the addresses are listed in the last column.


      Component 

      Description 

      Address00

      Open push button

      One of the inputs to request open operation  

      I: 1 / 00

      Close push button

      One of the inputs that enables user to shut down the door

      I: 1 / 01

      Stop push button

      The push button to stop operation at any time

      I: 1 / 02

      Limit switch 1

      A sensor to stop opening operation beyond the opening limits

      I : 1 / 03

      Limit switch 2

      A sensor to stop closing operation beyond the closing limits

      I : 1 / 04

      Shut down indicator  

      One of the outputs that tells the shutdown operation is in progress using an Indicator lamp 

      O: 2 / 04

      Open door indicator

      One of the outputs that tells the opening door operation is in progress using an Indicator lamp 

      O: 2 / 03

      Ajar door status

      One of the outputs that tells the door is ajar using an Indicator lamp 

      O: 2 / 02

      Motor Up

      A relay that directs the door in opening direction 

      O: 2 / 00

      Motor Down

      A relay that directs the door in closing direction 

      O: 2 / 01

      The logic operation

      After receiving the requirements of the client that tell how the door will be operated, managed, and controlled, we need to add the restrictions and safety conditions that secure the equipment like the motor, supply, sensing components. So the following lines state the operation and restrictions that need to be followed to achieve the designated task as follows:

      • The door opening and or closing shall be stopped at any time user / operator hit stop push button

      • The door shall open by requesting opening operation using the designated push button

      • The door shall close by requesting shut down operation using the designated push button

      • The indicator lamp of opening operation shall be lit while opening operation is in progress

      • The indicator lamp of closing operation shall be lit while shut down operation is in progress

      • The ajar status lamp shall be lit at any time the door is not fully opened or totally closed

      Restrictions:

      • The opening operation can not be requested while shut down process is in progress

      • The shut down operation can not be requested while opening operation is in progress

      • The opening operation can not proceed any further beyond the designated limit to avoid any overload on the motor

      • The shut down operation can not proceed any further beyond the designated limit to avoid any overload on the motor.

      Ladder Logic Code for Garage Door Project

      The ladder logic program of the project is shown by figure 2. It shows two rungs, one for opening process and second for the shut down operation. The program can be more lengthy but we professionally resumed it in only two main rungs. The first rung represents the door opening operation in which, open push button initiates the opening process and the latching is there to let the opening process continue till the limit switch LS1 contacted or the stop is requested by hitting the stop push button. In addition, security of the process has been considered by including the condition of not having a shutdown process in progress represented by O:2/1. On the other hand, the shut down process is represented by the second rung. The shut down process initiated by the shut down push button and latching the door closing relay for continuing the shut down process unless one of the restriction conditions is met. The restriction conditions of shut down are the limit switch LS2, the door opening in progress, or a stop has been requested by operator using the stop push button. Also, indicator of the process status are included to show the opening operation thanks to the door opening indicator and the shutdown indicator. But we missed the ajar status of the door so let us add one rung for that.

      As you see guys, the third rung has been added to implement the ajar status. It is simply clear that when the opening is in progress without reaching to the fully open indicator, or the shut down process is in progress without reaching to the totally closed, the ajar lamp is energized. Now let us go testing what we have coded so far and see if it is correct or not. But first you guys should sit and list the test cases that you should try to make sure the system is going to perform correctly and safely as well.

      Testing the project

      Door Opening test

      In this test , we hit the opening door push button to request opening the door. As you see my friends, the door is opening as in figure 3 and the opening indicator is lit. also you can see the ajar indicator is lighted because the door is not reached the final opening position.

      Figure 5 shows the state of the process after reaching the final position for opening the door. It is clear the process safely completed and the limit switch LS1 is gone green. Also the ajar status and opening indicators have been turned off.

      Door closing test

      In this test , we hit the door shut down push button to request closing the door. As you see my friends, the door is closing as in figure 6 and the closing indicator is lit. also you can see the ajar indicator is lighted because the door has not reached the final shut down position.

      Figure 7 shows the state of the process after reaching to the final position for closing the door. It is clear the process safely completed and the limit switch LS2 is gone red. Also the ajar status and shut down indicators have been turned off.

      Security and Safety Test

      In this test case we want to request opening .the door while it is shuting down and try to request shut down the door while it is opening to see is there any issue or not. Figure 8 shows what is going on when we requested opening the door while a shuting down process is inprogress. You can see guys in rung number one, the opening push button ,is pressed as circled and highlighted see I:1/0. However, the requested process has not performed due to the restriction that the shutdown process should not be in progress. Same thing when opening door is in progress, shut down requests are forbidden.

      String DataType in Python

      Hey, peep! This is a connected tutorial from the previous one where we saw the detail of numeric data types. This time, we are moving forward with the other data types in Python. We are understanding all these concepts with the help of examples and practising the little but understandable codes in TensorFlow. Different types of operations are also performed on these data types so that you may have an idea of why we are differentiating all these data types and how we can categorize all of them into different groups. Keep in mind that all of these concepts are for deep learning, and we want to make sure that we will not face any problems in the complex work of deep learning; therefore, we are moving slowly and steadily in Python.  So, have a look at the content you are learning in this tutorial, and after that, we’ll start the introduction. 

      • What are the strings in Python?

      • How do you declare the string in different ways while working in Python?

      • What are escape sequences in Python?

      • How can you use the triple quotation in Python and why it is useful?

      Each concept will be discussed with the help of simple and easy codes and the description of each of them is discussed in detail in this lecture. This is a connected part of the lecture that was discussed in the last lecture and other data types will be mentioned in the next lecture. 

      Strings in Python

      A string is nothing but the combination of different alphabets in a specific sequence. In programming, the concepts are a little bit different from those in the real world. The way we speak in English is said to be "string" in the programming language, and it is an important data type in any programming language for non-programmers, anything that comes on the screen must be easy to understand, and string is the best way to print the message on the screen. Let us define the string in simple words.

      "The string is the sequence of characters or alphabets that specify the message on the screen and it is denoted by 'str' in Python."

      We always say that python is simpler and easier than other programming languages, and it is true for the concept of string as well. In Python, the string can be denoted by using single or double quotation marks and the usage of commas is according to the choice of the programmer. In other words, you can use the single or double inverted commas around the alphabet to represent the string. Moreover, you must know that string has no limited length same as in the case of integers. The only thing that limits the length of the string is the memory space of the system you are using. Have a look at the syntax of the string while you are working on Python. 

      Python String in TensorFlow

      First of all, you have to look at the syntax of the string. The syntax of all the data types is the same; therefore, we are mentioning just this one, and after that, you will have an idea of how to implement the other data types. We have mentioned in the previous lectures that you just need the name of the variable and then the value of the variable in the form of any data type you want, so the syntax is given as

      string = "I am learning Python for Deep learning."

      The name may be anything, but it is important to use inverted commas (either single or double). TensorFlow will make this clearer, but there is a short procedure to get TensorFlow up and running.

      • Search for the “Anaconda Navigator” on your PC. 

      • In the environment section, click on the Jupyter lab and launch TensorFlow. 

      • The new tab will open in your browser with the name “Local host.”

      • Go to the new cell and start coding there. 

      Now, you have to write the following code in the new cell and run the program to get the output.

      string="I am learning at TheEngineeringProjects"

      print(string)

      a=" "

      print(a)

      b='Python is best for Deep learning'

      print(b)

      The output of this code is given as:

      From the code and output, we can conclude with the following point:

      • The name of the variable may be anything. 

      • We can use single or double inverted commas for the string and the result will be the same.

      • A string may be an empty space so we can say that length of the string is zero to positive infinity.

      • The output of each print function is always shown in the next line in normal conditions. 

      So, the best way to show any message to non-programmers is in the form of a string. 

      Escape Sequence in Python

      In most high-level programming languages, there are certain words that are chosen to be used for a special task in Python with the help of their special sequence. These are known as the escape sequence. These are defined as:

      "The escape sequence in Python is the combination of characters that, when used inside a string or character, does not show itself but does the specific task according to its functionality."

      It is important to notice that these are important concepts in Python because it is very difficult and in some cases, impossible to do the same task without using the escape sequence. Now, have a look at some of these in the next section and you will get the detail of some important escape sequences. 

      New Line in Text Using TensorFlow

      As you can see, in the previous code, we made a space between two lines with the help of an empty string. But, what if we want to print a new line in the message? For this, we use a special operator in the string message and it is used in places when the output is long or there is the need for more than one line to represent the message more clearly. The operator is a backslash with an “n” that can be used at any place in the text. Have a look at one example to do so.

      print('The backslash with "n" is used to \nprint a new line')

      The output of this single-line program is interesting.

      It is important to notice that if you want to work with this operator, you have to use it properly. You can not use any additional space between the text and this new line operator; otherwise, you will get an error message from the compiler.

      Tab Operator in Python

      We all use the tab on the keyboard but what if you want a space between the text? You can do so by applying the space between the text while you are printing the message but it is not the professional way. To do this with convenience, just like some other programming languages, Python has a special operator. Same as we use the n in the new line operator, if you use the t with the backslash, you can print the space between the text that is equal to eight space bars.

      print('The backslash with "t" is used to \tprint a tab space in the line')

      Let’s see what we have in the output of this code.

      Same as these operators, we also have some other commands that do the work similar to this and the syntax of all of these is the same. For the convenience of the reader, we have made a table that contains all the information about these operators. Have a look at the table and after that, we will run all of these at once in our code in TensorFlow.


      Name

      Representation

      Description

      New line

      \n

      It creates a new line in the text even if you are using it in the middle of the line.  

      Tab space

      \t

      It is used for the space tab between the text. 

      Bullet

      \a

      For the bullets in the text, we use this operator. 

      Delete space

      \b

      To delete the space in the text, we use this operator. In this way, the text obtained only removes the space from the place where this operator is being used and the other text remains the same. 

      Ignore the line 

      \r

      By using the working of this operator, the text before the operator is deleted, and you will get the text after this operator only in the output. 

      Arrow

      \v

      If you want to show a small arrow in the text, you will use this operator. 


      To test each of the commands discussed before, we are rushing towards the TensorFlow, where we are using all of these in a similar ways to show the difference between all of these. Keep in mind, the syntax of each of them is the same. These are not the proper functions but are the pre-defined commands that are used less commonly in Python. Here is the homework task for you. You have to look at the code we are giving below and without cheating will guess the output.

      print('We use \ncups for tea')

      print('The tab create \teight spaces in the text')

      print('\aBullets can be made using this operator in Python')

      print('If you want to delete the \bspace, you can use the operator in Python')

      print('This part will be ignore \ronly this will be printed on the screen')

      print('\vThis small arrow looks cute')


      Once you have guessed the output, now check this in your compiler, and then match the output with the one that is given next in the image.

      The last arrow can also be used as the bullet in the text you want to show on the screen. Another task for you is use the different text and practice the code and string with your own message. It is the simplest and interesting task that you must try on your TensorFlow. 

      Triple Quotation String in Python

      Here is another way to indicate that you want to declare the string. This is a less common way to represent the string, but if you are studying the string, you must know this. You can use double and single inverted commas around the text at the same time, and this will not cause any errors. Let me tell you about the workings of this kind of string. After that, I’ll show you how you can use it for different purposes.

      print('''Deep learning is the subclass of the artificial intelligance''')

      So, we are using three quotation marks around our text and getting the same output as for the single and double inverted commas. Here is the output:

      The advantage of using this method is, you do not need any new line operators to start the text on a new line, but you will write the code as you want the output.

      This is a more interesting and convenient way to write your text. Right now, you must be wondering why we are highlighting such uses and creating this hype. Yet, you must know, the aforementioned ways of writing the codes will help you a lot when you will go to the complex and long codes for the deep learning. One of the application of this way to declare the string is in this lecture. We can use this way to declare the string and can perform all the escape sequence command by declaring a single string in different lines so that we may not have to write “print command” every time when we are working with a new escape sequence.

      Hence, we have read a lot about strings today. It was an interesting lecture where we saw what strings are and how we can use them in our coding in different ways. We say the representation, working, and the escape sequence between the string. The syntax of each case was clarified with the help of examples in TensorFlow. You will get information about more data types in the next lecture.

      List DataType in Python with TensorFlow

      Hey fellow! Welcome to the next episode of the Python series, where we are learning the basics of Python to implement them in deep learning. In the previous lecture, our focus was on string data types. With the practical implementation of TensorFlow, many interesting points were discussed in depth. I hope you completed the home task that I assigned you during that lecture. Today, we are moving forward with the next data type, which is a sequence. You will know the different sub-groups of this data type as well in the next lecture, but today, the focus will be totally on the list because, once you understand them well, other data types of the sequence will be at your fingertips. Yet before starting, it's time to look at the content that you will learn today:

      • What is a sequence?

      • How do you classify the sequence into different types?

      • How do you understand the list?

      • What are some characteristics of this list that make it useful and different from the others?

      The workings and characteristics of the list are interesting, and these will be well understood when we start our TensorFlow for different examples taken from our daily lives. We hope you have a strong grip on the integers, strings, and floats because, in our example, we will use them and will try to make changes in the list to show the difference in detail. So, without using your time, I am going to start the learning phase in Python.

      Introduction to Sequence in Python

      In programming languages, we use a lot of items, objects, classes, and related concepts, and when we talk about the sequence, that is a data type that provides us with the concept of a collection of things. These are useful concepts that allow us to work with them in a useful way. We define the sequence in the following way:

      "The sequence in Python is a generic term that defines the ordered set of items in such a way that any of the items can be easily referred to."

      Here, the word “ordered set” is important to notice. We’ll talk about it in detail in just a bit, but before that, let me tell you that the string is also considered to be the sequence because it contains the sequence of the characters. We have read a lot about the string, and therefore, we know that the ordered sequence of the characters, or alphabets, is called the string. Yet, I had a lot of data to tell you about these concepts; therefore, I have discussed them separately. There are two natures of the sequence that are listed below:

      1. Homogeneous sequence

      2. Heterogeneous sequence

      The difference between these two is that a homogeneous sequence contains a group of items of the same kind.


      Homogeneous Sequence

      Heterogeneous Sequence

      A homogeneous sequence contains a group of items of the same kind. 

      A heterogeneous sequence contains a group of items of different kinds. 

      {"Apple", "Banana", "Cherry"}

      [Cup, knife, banana]


      It is important to know this difference because, on the basis of it, you will get the further types of the sequence. 

      Types of Sequence in Python

      The collection of the data can be represented in different ways, and on the basis of these types, we can divide the sequence into six major types. All of these are important to understand because we use the sequence often while programming and when dealing with complex subjects such as deep learning (in which we are interested), and the sequence plays a vital role in organizing the data in an understandable way. So, have a look at the types of sequences:

      1. String

      2. List

      3. Tuple

      4. Byte sequence

      5. Byte array

      6. Range objects

      Out of them, the strings have been discussed in detail in the previous lecture. So, we are skipping that for now. You will be familiar with the remaining ones in depth, and things will become clearer to you with the help of examples. Thus, have a look at them: 

      List in Sequence

      In some other programming languages, such as C++ and C#, there is the concept of arrays that we study a lot. Yet, in the Python programming language, this concept is not used; instead, lists are used. The list is indicated by the square brackets just like the arrays, but it is a little bit different from them. The list is the type of sequence that contains an ordered group of different items. More information about the list can be found in the table below:


      Name

      Attribute

      Representation

      Square brackets

      Nature

      Heterogenous sequence

      Example 

      [‘cups’, ‘eggs’, ‘yolk’, ‘tea’]


      Here, it is important to notice the representation of the list with the square bracket because the bracket is the only way to differentiate it from the other types of sequence that you will learn in the coming lectures. The operation of the list will be explained in simple steps in a moment, but first, let us open the Python workspace for practical implementation. For this, you simply have to follow the steps again that we always mention:

      • Search for the Anaconda Navigator on your personal computer. 

      • Go to the environment section and look for the “Jupyter lab” or “Jupyter notebook." For this tutorial, we are using the Jupyter lab. 

      • Go to the new cell and get ready for the coding.

      The list's information does not end with the table mentioned above. Certain characteristics make the lists useful, and you will learn about them in the following section.

      Mutable list in Python

      One of the most significant features of Python is its mutable nature. To know the meaning of the line we have just said, you must know that when we declare a list, we define the size of that particular list by mentioning the number or directly feeding the elements in it. The list's advantage is that the programmer can change the elements at any time to meet the needs of the situation. In addition to this, if you want to change the individual value of the list, you can do so easily. Not only this, but you can also change the order of the elements while working on the code. It means if you want to swipe or change the position of elements 1 and 3, you can do so easily. In short, you can say that, while working with the list, all the controls are in your hands. 

      MyIntList=[1,56,8,12,56,90,3,67]

      print('The homogenous integer list is : ', MyIntList)

      MyFloatList=[1.2,56.2,8.2,12.2,56.2,90.2,3.2,67.2]

      print('The homogenous float list is : ', MyFloatList)

      You can see that all the elements belong to the same data type, so we are calling it the homogeneous list. In the second code, we want to do something different, so have a look at the code.

      list=['eggs', 2.0, 34, 'plates']

      print('The elements of the list are : ', list)

      print('The element at position 2 is : ', list[2])

      print('The elements before the second position are : ', list[:3])

      list=[ 34,2.0, 'eggs', 'plates']

      print('Now the new list is: ', list)

      By looking at the code given above, we can conclude the following points:

      • To declare more than one type in a single list, the programmer simply has to use the accurate way to declare them in the list, and nothing special has to be done during the declaration of the list. 

      • To get a specific element from the list, simply the position of the element is mentioned. 

      • The position in the elements start from the 0 just like the arrays and you have to declare the element accordingly. 

      • The order of the elements can be changed easily and to do this, the programmer have to merely change the elements according to the will with the same number. Here we have used two types of lists with the same name but by changing the order of the elements and the code is working well.

      • To get the elements of the list to a certain limit, there is a need of mentioning that number of position along with a colon. Keep in mind, here we specify the position 2 and all the elements before the third position are shown to us. Same can be done to get the elements after the mentioned number and it is your homework to know how can you do so. 

      Dynamic Nature of List in Python

      When you compare the list to the array, you can better understand Python's dynamic nature. Let me remind you that arrays have a fixed size and cannot be changed once declared in your code. But in the case of the list, once you start working on it and need to change its size, you can increase or decrease its size by merely mentioning it in just one line. In other words, your list can grow or shrink according to your choice. To understand this you must know about a built-in function in Python.

      List Length Function 

      The length is a built-in function in Python that provides the length of the functions made in the code. You simply have to input the name of the function in it and it will show you the number of elements specified in that particular function. The syntax of the length function is:

      len(name)

      By using this function in the list mentioned above, the number of elements can be obtained with the help of this code:

      list=['eggs', 2.0, 34, 'plates']

      print('The length of list is : ',len(list))

      list=[34,2.0, 'eggs']

      print('The new length of list is : ',len(list))

      The output of the code is given next:

      Heterogeneous List in Python

      Keep this in mind the next time you go grocery shopping and want to buy something else; make a list for it. It will contain vegetables, meat, cloth, spices, and other things of the natural world. Because of its heterogeneous nature, the list is the same. It feels like a relief that you can make a list that contains strings, integers, and any other data types in one place. In this way, you can deal with multiple types of data at once. In arrays, this is not possible. You can also add functions to the list that contain elements of different types. You have understood it well with the previous examples in TensorFlow, but I want to show you this by mentioning a built-in function in it. 

      Mylist=[23,'decoration', False ]

      print(Mylist)

      Yet, there is a bit of difference between the keywords and loops; therefore, you can not mention the loops in the list; otherwise, you will face the same error as given next:

      Here, the error is demanding that you write the code in the valid syntax. It is because the compiler is not able to understand that the for loop is an element of the list, but it demands the proper syntax for the for loop and is expecting an iterative procedure. Another thing to notice here is the color of the word “False” in the list. All the keywords, while coding, are shown in green, showing that it is a built-in function or keyword and that the compiler has understood the default functionality of that particular keyword.

      Hence, it was an interesting tutorial, through which we learned a lot about the list data type. We initially understood what list data types were and why we were learning them. After that, a detailed overview of the list was discussed, through which we found the characteristics of the list. It was easy to understand as we practically performed each step of the TensorFlow with the help of different examples that were related to the general examples, so we were able to understand it well. If you have a clear understanding of the list, the following lectures will be simple to grasp because they are related concepts. So, stay tuned with us to get more information about Python.

      Python DataTypes

      Hello learners! Welcome to the engineering projects where we are working on deep learning. In this series, we are at the part where Python is under our observation. In the last session, we saw the Python built-in functions and the practical implementation of some important pre-defined functions of Python. In the current lecture, you will learn about the fundamental concept of Python. It is not wrong to say that if you want to work in any high-level programming language, you have to understand its data types; otherwise, you will not be able to code complex or long programs using it. More details will be discussed in the next section, but before this, you should have a glance at the concepts you will learn in this tutorial.

      • What are the data types?

      • How are Python data types different from other programming languages?

      • What is the syntax to use the data types in Python?

      • What is the difference between floats and integers?

      • How can you practice other concepts along with the complex number in TensorFlow?

      • What is the casting process in the Python programming language and how can you use it for changing the type of data you enter?

      • What is the “type” function in Python and how do you use it?

      For your convenience and detailed learning, we are just discussing the numeric data types in this lecture, and you will learn more types in the next lecture because I want to discuss each type with the practical implementation of different operations on these data types.

      What are Data Types?

      Consider the case where we use different types of numbers in mathematics and apply the operations to these different types of numbers. We know that only numbers can be added, subtracted, multiplied, etc. The same is true for data types. When dealing with programming languages, we have to deal with different kinds of objects, and it is important to use them wisely because of the memory storage. Have a look at the basic definition of the data types in the programming languages:

      "In programming languages, the data type is the basic concept that declares the type of object being used in a specific way, and based upon the data types, the memory space is occupied by the compiler."

      In simple programs, such as the ones we used in our examples, we don't notice much of a difference when we occupy more space in the program, but this is not the best practice because, in long and complex programs, we need to use the exact data type. Hence, the compiler runs perfectly and we can apply the specific operations to the particular data type. 

      The declaration of the data type is always required in most programming languages so that the compiler can fully understand the data type. So, you can declare the integer as a float and vice versa according to our will, but it causes problems in the compilation.  

      Data Types in Python:

       As we always say that Python is an easy programming language, and here is one of the main reasons why. In Python, the compiler itself is intelligent enough to understand the type of data you are putting into it, so your program may run well if the code is well-written. It feels like a relief that you do not have to remember the names of different data types, and there is no need to memorize the space occupied by the data type so that you may compare and choose the perfect data type for your code. The name of the data types is almost the same as the other programming languages that we have mentioned before, but the way these work with different operations may seem a little bit different. The declaration of different data types in the Python programming language is given in the next section.

      Syntax of Data Types in Python

      The best way to learn any concept in programming is to learn the syntax first instead of going into the example and understanding how that concept works. When we talk about the syntax of data types in Python, this section is very important. You have to keep in mind that unlike some other high-level programming languages such as C++ and C#, you have only two items:

      1. Variable name

      2. Value of the data type

      Now it's time to go over the various data types one by one. The syntax of all of these appears to be the same, but the examples will demonstrate the differences in how each of them works. For your convenience, the different data types are divided into six categories:

      • Numeric

      • String

      • Sequence

      • Mapping

      • Boolean

      • Set

      These categories also have sub-categories, and the same category works in the same way, but you have to keep the differences in mind, especially if you are a beginner because it becomes easy to understand the code and the way you work with it. Other details will be clear when you see the implementation in the tensor flow. For this, I want to share the procedure for starting code in TensorFlow in a straightforward way:

      • Fire up your Anaconda navigator.

      • In the environment sector, you have to search for “Jupyter Lab” and hit the launch button there.

      • A new local host will appear in your browser. Go to this local host. 

      • In the new cell, begin coding. 

      Numeric Data Types in Python

      We all know what the numbers are, and there is no need to provide you with the details of the numbers, but to refresh the concept in your mind, we have to tell you that there are three classes of numeric data types that are introduced in Python:

      1. Integer

      2. Float

      3. Complex

      A short description of each of them is given next:

      Integers in Python

      The first and simplest data type that you will see in every tutorial is an integer. These are whole numbers and do not contain any extra parts. These are the signed integers that have a non-limited length. It means that on the positive side of the numbers, you can have the length of an integer as long as you want. One thing that has to be considered here is the memory of the system you are using, but when purely talking about the integer, it does not have any limit in length.  

      Python Integers in TensorFlow

      Are you ready with your TensorFlow to practice all the data types and apply the different operations on them? Ok, we hope your TensorFlow is launched, and have a look at the simple representation of the integer in it. 

      integer=1257859304284756327

      a=3824374269873874

      print("integer= ", integer)

      print("a = ", a)

      add=integer+a

      print("integer+a = " ,add)

      Here, you can see that:

      • We can name the variable anything we want, whether it is a special name or any combination of the alphabet, but it must follow the rules that we specified in the previous lecture. The results of the code are given next:

      • The length of the integer does not matter, as integers can be long or short according to the requirement. 

      • The addition can take place with the integers. Similarly, other operations such as subtraction, and multiplication is also possible. 

      Float in Python

      The next is the float, which in some cases looks like an integer, but if you are a science student, you must have the idea that integers and floats are not the same. The floats contain a decimal floating number just after the integer part. So, even if the number after the decimal point is zero, it will still be called the "float." Another thing to be noticed in the floats is, you can use the 15 digits in the float, and these are not unlimited as the integers are. 

      Python Float in TensorFlow 

      In TensorFlow, I want to perform the subtraction on the float this time, and I want to show you by code that when we do not add any decimal part to the float, the compiler itself adds the zero in the decimal part and provides us with the result. Moreover, you will observe that it takes the most significant number after the decimal part; therefore, in the code, when we add the zero as the last digit, it ignores it and the results are shown with the significant numbers.

      Complex Numbers in the Python

      We've all learned about complex numbers in math class, and according to the requirements, these complex numbers play an important role in programming. The representation of the complex number in Python is a little bit different than in mathematics class. Have a look at the code, and after that, we will discuss it in detail. 

      Complex Numbers Using TensorFlow

      The representation of the complex number is the same as what you were expecting. We have to use the i and j for the complex part, and the sign of addition or subtraction represents the difference between the real and complex parts. 

      # Step 1

      z = complex(a,b);

      print(z)

      # Step 

      print ("The real part of complex number is : ",c.real)

      #Step 3

      print ("The imaginary part of the complex number is : ", c.imag)

      • Here is the first step, we have assigned the duty to the compiler to make a complex number for us. For this, we have used the “complex” built-in function. We have discussed it in lecture number 10 of this series. 

      • The step is completed when we print the complex number to show you how the functions are working here. 

      • We are naming the complex number “c” and keep in mind, it consists of the real and imaginary parts. 

      • In the next step, we are simply using the “real” and “img” keywords to separate these parts of the complex number. 

      • The good thing is, we are using the same line to print the description and the result of the code. You can also do so by using the additional line of print, but I like simple and shortcodes. 

      So, the overall result can be observed in the following image:

      The result is shown in the form of floating numbers, and in our case, the real part is 0 by default. 


      Casting in Python

      Till now, we have seen simple declarations in the Python programming language, but now it's time to discuss another method of variable declaration, which is casting. Because of the various forms in which metals are cast, we've heard of this term before. The concept of casting is related to the same idea. In Python, this process is defined as:

      "Casting in Python is a process in which the original type of the variable is changed to any other type by specifying it in the code in a particular way."

      We have mentioned before that the Python compiler automatically detects the type of content, and therefore, in some special cases, we want to occupy the space from memory that does not match the value you are entering. If still it is confusing for you, do not worry because it will be clear in just a bit when you will look at a simple example to do so in TensorFlow.

      a=23.56

      b=type(a)

      print("Here 'a' is a float", b)

      c=int(23)

      d=type(a)

      print("After using the casting, the result is" , d)

      Here is the output of this code, which tells you the details by itself.

      The type function was covered in the previous lecture, so I hope you understand what it does. If not, you can review the previous lectures. Since the data types are so long that it becomes difficult to explain in a single lecture, you will get the details of other data types in the next lecture. Until then, you must continue to practice with these data types. We have seen the introduction of the data types and the ways to work with the data types in Python. We've also seen a comparison of other languages and Python on the same topic, and this lecture is heavy on numeric data types. I hope it was fruitful for you and that you will go to the next lecture for more data types.

      Python Built-in Functions in TensorFlow

      Hey peeps! Welcome to an exciting tutorial on Python in which you will learn about the Python reverse list. We are on a series of deep learning phases where Python is under our observation. In the last tutorial, we saw the variables in Python and practised many codes in the TensorFlow. Today, we are interested to practice many interesting methods in an easy way. These are the built-in functions and you do not have to be an expert in the programming to perform them in TensorFlow. All you need is to read this tutorial and have the TensorFlow working fine. Before going deep into the topic, it is important to have a look at the list of content that you will learn today:

      • How do you define the python reverse list?

      • Why we should know about the python reverse list or keywords?

      • How do you practice the codes of Python reverse list in TensorFlow?

      • What is the core difference between some related keywords that seems to be work relatively?

      • How do you run some loops in the Python while working on the TensorFlow?

      All these concepts will be cleared by discussing them in detail and while using the codes, you must keep in mind, there are more than one way to run the program in your own way but the one that we have defined in this lecture are the precise one and these are enough to understand the concept that we want to share with you. So work smarter then to word harder.

      Python Reverse List

      We know that there are some rules that have to be followed when you are naming your variables in python. Usually, these rules are applied to almost all the present programming languages but we are specifying Python because we want to connect this discussion with the Python reverse list. There are some restricted words that cannot be used as variable names. These are pre-defined in each language. You can define it in the following way:

      "The Python reverse list (also known as keywords) is the complete list of pre-defined functions that are already stored in Python and these particular names are not allowed to be used as the name of variables while coding."

      If you go into the detail, there are hundreds of reverse words in Python but this will be out of the scope of this course. For your information, we have added some very common keywords that you have to learn and practice to keep in mind. IT WILL HELP YOU A LOT WHEN YOU WILL WORK WITH THE COMPLEX AND LONG CODES. In Python, the following table is useful to understand what kinds of names are not allowed.

      Python Reserve List

      True

      del

      false

      def

      not

      elif

      as

      class

      if

      break

      return

        None

      else

      with

      for

      lambda

      except

      yield


      The list does not end here, but I think it is enough to understand what types of variable names must not be used when you are practising deep learning with the help of TensorFlow (in our case). 

      Python Reverse List in TensorFlow

      Once you have read about the reverse list, you must practice it for the practice. Here, we are using some of the variables from the list given above. To practice it on TensorFlow, you have to follow the steps given next:

      • Open your Anaconda navigator to use TensorFlow.

      • Navigate to the environments and start the Jupyter lab.

      • The screen here will show you the cells where you can write the codes. 

      • Start writing the codes using the keywords from the list mentioned in the above table. 

      Def in Python

      The declaration of a function is done by using the “def” keyword. There is no need to tell the compiler the type of variable. After that, you can use this variable in other operations. Have a look at the code.

      def welcome(name):

      print (f"{name}, Welcome to theEngineeringProjects")

      welcome ("Student")

      The output of this program is given next:

      Hence, you can see that we have declared the variable “welcome” and then provided the string in which we are using the function that we specified for ourselves. In the next line, we simply provide the value of the variable for that given string. You can simply change the value of a function in the last line to change the name with the same string. 

      False in Python

      This is a different type of keyword than in the previous case. The value “false” is declared by the compiler if we are providing information that is universally wrong. The best example in this regard is the one in which we are trying to equilibrate two different values of numbers.

      The compiler is intelligent enough to clarify that the command given by you is not right. 

      true in Python

      This is the other simple keyword that is shown by the compiler itself, and if you are familiar with the keyword “false” given above, then it is obvious that if a universal truth or condition is fulfilled, the compiler will provide the answer in the form of the “true” keyword, as can be seen in the next image:

      Another thing to notice here is, the string, or other data types may also be used with teh equality operation but as we are mentioning again and again, the Python is the case sensitive therefore, if the alphabets are the same but the case is different, the result will be contrary to the one given above:

      The “L” of the second name is capitalized and therefore, the compiler is recognizing it as a different letter. It is the reason we are getting the “false” keyword as result. 

      del in Python

       As you can see, del is the short form of the “Delete” operation, and therefore, you can use this to delete any specific entry, value, or object from the list or the code. Here is an example of how to do so:

      subjects = ['Physics', 'Chemistry', 'Biology']

      print(subjects)

          #applying the delete option

      del subjects[1]

      print (subjects)

      When we put this code in our cells, you will get the results as expected:

      At the start of the code, we declared an array of named subjects. You will learn more about these concepts in detail, but for now, just keep in mind that we have a group of sciences in our array, the index of which starts from 0. So, when you delete the first entry that is under the second name, you will get the list with only two entries.

      None in Python

      Here is another keyword that is used in Python for your convenience. You can think of the “None” keyword as a blank space or an empty container. Take the example of the case when the user does not put the information required on a survey that is necessary to answer, then he/she gets the error from the website that this is a required field and therefore, the user has to put the information in it to move forward. This is best understood by the code given next:

      Here, you can see the error message that appears when the required field is empty and the user wants to proceed. 

      If statement in Python

      The “if” is a special keyword in Python, and you cannot name it as a variable because it is against the rules. This is the name of a loop, and you must know that loops will be discussed in detail when you proceed in this series; therefore, we will not explain too much about this keyword. But for now, have a look at the code given next to get an idea about the workings of this reverse word

      number = 300

      if number >= 18:

       print("You are eligible to become an Engineer")

      Output of this code is given as:

      raise in Python

      Here is an interesting keyword that uses words in a very useful way. We have seen the error indication in different websites and other platforms where the user input the data and if it is not according to the rules of the input data then the screen shows the warning about the error. It can be done with the help of the raise keyword in Python. Let us take the case in mind where you have to provide your name in the form, and if the user provides the numbers rather than the name, then it will throw an error at you. 

      name = 123

      if not type(name) is str:

             raise TypeError("Only strings are allowed.")

      So, it is clear that you have to put the name in the form of a combination of alphabets. By looking at this program deeply, we have seen the following points:

      • It is important to specify the type of content that you want to allow.

      • The “if statement” is also used in this program so that we can use more than one keyword in one line. 

      • You can also change the type of content by specifying it in the first line. 

      • The name of the variable does not matter. 

      • By deleting the word “not” in the second line, you can invert the whole program. 

      • In advanced programs, you can add more than one condition to apply all the necessary information so that any illegal way to type the name can be detected and the error may be shown. 

      return in Python

      The return keyword looks like the print function in the code, but both of them are not the same. The return function combines two or more results, and then control is given to the print function, which displays the results on the screen. Here is the program to do so. 

      def sum(x, y,z):

             return x + y + z

      print (sum(55,7,34))

      The TensorFlow output is as follows:

      Here, we have written a program that calculates the sum of three numbers. The start is done by using the define function, and here, we define a function that defines the pattern. This pattern will be used in the future. In the second step, the “return" function specifies the way the three components will work. In the third and last step, the values are put into the print function so that it may show us the result. This can be done in another way if we initialize another variable in which the result of summation is stored, and then we put that particular variable into the print function. The second way is more practical, but it occupies more space. 

      In addition to this, you must know that you can specify any number of elements in the formula in the first step. If the pattern contains more than three elements and you do not have a large number of elements to test, you can enter "0" in place of the extra elements, but you must follow the pattern and cannot enter fewer than the specified number of elements.

      elif in Python

      Here is the last keyword to explain in this lecture. It is the combination of two words, “else” and "if,” and it is used in the loops. You will practice a lot about the loops in the coming sessions; therefore, I am not explaining it much. But for now, you must know that when you want to add more than two conditions to a program, you use this keyword. In the language of C++, we use the else if the keyword for the same purpose. So, have a look at this program:

      So, the user with knowledge of artificial intelligence is more likely to get the skills of deep learning, and we have made this program to show you this.

      So, it was a helpful tutorial to learn a lot about the Python reverse list. These are the keywords that are pre-defined in Python, so it is not advisable to name your variable exactly like these. If you do not follow this rule, the compiler will be confused between your defined variable and the keyword saved in it, and therefore, it will throw the error. You must know that there are more words in the list, but for now, it is enough to understand and practice the words mentioned here.

      Types of Python Variables in TensorFlow

      Hey learners! Welcome to the new lecture on deep learning, where we are using TensorFlow to learn it with the help of Python. Previously, we worked on the syntax of Python, and now it's time to discuss the variables in detail. There are some variables that you will learn about as well as get hands-on experience within TensorFlow. These are important concepts that will help you throughout your coding career. If you are new to programming, this is a crucial concept for you, and if you know it already, you can use this tutorial to polish your concepts. We will move forward after looking at the list of content for this lecture:

      • What are the variables in Python?

      • How do you assign the value to the name of the variable in Python?

      • What are some rules to define the name of the variables?

      • How do you declare or initialize the variables in Python?

      • Can you get the type of variable that is declared before?

      • What is the difference between statically and dynamically typed programs?

      • What is the purpose of re-declaration in Python?

      Introduction to Variables in Python

      In the previous lecture, we mentioned the name string, and the difference between the string and character is just the amount of storage these two occupy. The reason these are important to understand is to use an accurate way to store our data. This will be clearer when you see the introduction of the variables in Python:

      "In Python, the variables are the containers that store the information in them and are defined as the name given to the location in the memory."

      We all know that when a program is saved in the compiler, it allocates a specific amount of memory. Variables in Python work differently than variables in other programming languages such as C++ and C#. In these languages, the programmer has to define the type of the variable and allocate the specified amount of memory required to store that variable. Still, in Python, the program statically types. The other type of program in this regard is dynamically typed programming. For your convenience, I have made a comparison between these two types:

      Sr#

      Statistically Typed Programs

      Dynamically Typed Programs

      1

      The checking in the code for the error is done before running the program. 

      The checking for the error is ignored at the compile time and is done in the run time. 

      2

      The type of the object is known by the variables. 

      The variable does not know the type of object but the object knows itself. 

      3

      At compile time, the “Unsafe operation” is rejected. 

      The “Unsafe” operation is rejected at the runtime. 

      4

      Example: C++, C

      Example: Python, PHP


      So, Python is easy to understand, and you do not have to work hard for the declaration of variables of a different kind; most of the time, the declaration is super easy. You will see this when we work on the examples of the variables in just a bit. 

      Assigning the Values to the Variables

      When declaring the variables, you have to be very careful about the data you are placing in different containers. The reason behind this is, there are hundreds or more than it variables in the code when we start professional coding in Python. In such cases, it is important to memorize the name and working of the variables instantly. It is not advisable to name the variable without following any logic to memorise the exact information about that particular variable. The list of the variable is shown on the side of the TensorFlow but the working must be shown with the name of your variable.

      For example, if you are declaring the variable that calculates the sum of numbers then the name of that particular variable must be “sum” or “addition”, or any other word that describes the function otherwise if you are naming it as “x”, or “var1” then you have to think for some moment that why you had initialized these variables. This rule is also beneficial to the case when the code is read by the other person or if you are sharing your code with the other person to work further on it.

      Here, you must know, the code that we are practising is tiny and these are easy to understand to make the points clear to the beginners as well but at a professional level, the coding is different and you have to make sure that you are writing a clear, clear, and easy to understand code as the code in such cases are too long and contain many concepts in a single line sometimes.

      Rules For the Variables in Python 

      For the declaration of the variables in the Python programming language, you have to follow certain rules, and for the convenience of the reader, we have made the points, and there is no need to memorize them; you just have to read them first.

      • The name of the variable must always start with the alphabet or the underscore character; otherwise, it is against the rules. 

      • The variable name does not start with the number. You can use the number in between the alphabets of the variable name, but not at the beginning. 

      • Symbols are not allowed to be used in the variable name. In other words, you can use only alphabets (A to z, in which the case of the alphabet does not matter), numbers from 0 to 9, and the underscore only. As a result, you can't use symbols like @, #, and $.

      • Variables name is case sensitive. This can be understood with the example that the variables Type, Type, and Type are totally different, and these are the names of three variables. 

      • The declaration of the variable may be done with the help of a single alphabet as well such as x, j, y, etc. But it can't be a single number such as 1, 2 3, and so on.

      These are the universal rules, and usually, the programmer creates his or her own code of conduct in order to ensure that he or she always follows the same route to write the code, making it easier to understand the old codes written by him.

      Variable Declaration in Python vs. Other Programming Languages

      Another reason why we say that Python is an easy and convenient programming language is that the declaration of different types of objects is easy in it. As we are studying the variables right now, I must tell you that in other programming languages, you have to declare the type of the variable first and then give it a name. You can set the variable's value either at the declaration or on the following line by providing the name and value. An example of the variable declaration in C++ is given below:

      Int x=78;

      or int x;

      x=78

      In contrast, when working with variables in Python, you do not need to define the type of the variable and can simply give it a name and a value. As a result, the program's work is simplified because the Python compiler is intelligent enough to recognize the type of the variable on its own and does not require the user to specify it. Here is the example that verifies the information given here:

      Similarly, when you are declaring the string or character, you will simply declare it with the name and value without specifying the type. 

      #Declaring the Character

      character='Python'

      print('Character is "', character,'"')

      #Declaring the String

      string="We want to work with deep learning through Python."

      print('string is "', string,'"')

      Just look at the output, and then I'll discuss the details of the code.

      The following points are proven with this code:

      • The name of a variable may be anything, and the value determines the type of variable in Python. It can be understood with the fact that even if we name of a string is declared as a character but detail the value has double quotation marks around the values, the compiler will read it as the string and it will occupy the space in the memory accordingly. 

      • Comments in the code are totally ignored by the compiler, and these are helpful to understand the block of code defined by it. 

      • In the print function, if you want to show the values as they are, you write them in single quotation marks, and if you want to declare the value stored in the variable, the variable is written as it is. 

      • To separate the printed message and the name of the variable, we use a comma between them. 

      • Using the single "print" function, you can print multiple variables or messages. 

      • While printing more than one output on the screen, you do not have to use indentation these print functions are non-consecutive. 

      • In Python, the single quotation marks are equal to the double quotation marks but as we have seen that both of these are different in other programming languages, to illustrate the type, we have used both examples. 

      The types of data will be given in the next session, where you will learn a lot about them.

      Getting the Type of The Variable in Python

      If you do not know the type of variable and want to get the related information for different types of operations, Python has a special pre-defined function that works in a simple way. You just have to put the value you want into the “type” function. The syntax of the “type” function is given next:

      print(type(variable name))

      Hence, the type of the variable will be printed on the screen. This can be best understood when you see some examples in TensorFlow. To do this, write the following code in the TensorFlow cell:

      a=56

      b="Deep Learning is easy with TheEngineeringProjects.com"

      print(type(a))

      print(type(b))

      As soon as you will pop the play button, you will get the results as follow:

      The reason why “class” words are used here is that Python is an Object-Oriented programming language, and it makes the classes perform the operations; therefore, it has presented the results in the form of classes. 

      Re-declaration of Variable in Python

      Once you have learned about the declaration of the variable, you might be thinking that the single value may be assigned to the single name only, but it is not true all the time. Suppose if you are using a large number of values in a program that will be used only once and you do not want to suggest single name to a single value, you can declare the variable again and this method is called the re-declaration. Have a look at the example to do so:

      a=45

      print("The value of the variable is", a)

      a=90

      print("The value of the same variable is now", a)

      So, you have simply masked the first value and given the same name of the variable to any other value. But in such cases, you cannot get the previous value back until you provide the first value to the name again. This is the reason why we call them "variables,” which means the non-fixed process. The values in the variable keep changing over time according to the needs of the program and the code written by the programmer.

      Hence, it was the day when we learned a lot about the variables in the Python programming language. We have seen a lot of information about the variables and seen how you can introduce and work with the Python variables in different ways. We have compared the declaration of the Python variables with the other programming languages and also got information about the statistically typed programs versus the dynamically typed programs. Moreover, it was interesting to know about the type function and the declaration of the variables in Python. I hope it was an informative tutorial for you and that you will practice more to get experience coding in Python.

      Syed Zain Nasir

      I am Syed Zain Nasir, the founder of <a href=https://www.TheEngineeringProjects.com/>The Engineering Projects</a> (TEP). I am a programmer since 2009 before that I just search things, make small projects and now I am sharing my knowledge through this platform.I also work as a freelancer and did many projects related to programming and electrical circuitry. <a href=https://plus.google.com/+SyedZainNasir/>My Google Profile+</a>

      Share
      Published by
      Syed Zain Nasir