Image from: https://www.pexels.com/photo/a-person-holing-a-sticker-in-close-up-photography-11035380/
Programmers use different programming languages so that they can create front-end and back-end applications well. One of the people’s main choices is Node.js. This particular programming language allows the creation of applications using JavaScript.
Image from: https://www.pexels.com/photo/person-using-macbook-air-5496463/
Node.js is usually the choice of programmers because it is open-source. What does this mean? It means that the source code for it is readily available. Contributors from different parts of the world are maintaining the source code.
Node.js cannot be properly used without the right developer. A dedicated Nodejs developer is always in demand. More people are learning how to use this programming language. Yet, a person should always be interested, dedicated, and passionate about it.
Some programmers who are still searching for a programming language to focus on can start learning Node.js for the following advantages:
This can be used for both the front-end and the back-end of the application. This means that programming can be done and fixed on both the client and server side.
The community of this programming language has grown steadily over the past years. It is still expected to grow bigger and better with more contributions to help any Nodejs developer .
The demand is only expected to grow as more well-known applications are using Node.js to improve their features.
The first thing to do is to make sure that your account has administrator privileges. This means that you can choose the software that you want, download it, and install it on your device.
Download Node.js Installer – Make sure to download the latest version.
Install Node.js and NPM from your chosen web browser – The moment that download is complete, launch it. Follow the instructions that will be given to you.
Verify the installation of Node.js – A command prompt will enter and you need to place “node-v”
You may ask yourself what type of JavaScript IDE will you use for Node.js? Different text editors are available but these are some things that can help:
Look for something that can be used by the whole node js development team. Some are more user-friendly than others.
Find the IDE that can help with syntax highlighting.
Refactoring options will always be very helpful. This will help you restructure the codes that you already have. It can make the editing of existing projects easier.
You can find react programmer that can make their knowledge and skills on providing what you need. Node.js is known for being event-driven and non-blocking which is confusing for people who haven’t learned enough about this yet.
When you say event-driven, it means that this can understand the request and do the task accordingly. A function will be created and will be registered instead of getting all the data. The function will work once it is triggered.
When you say non-blocking, it means that the request will be sent to the required function immediately. The request will not be blocked so it will be received at the soonest possible time.
When you say modules in Node.js, you are referring to a type of functionality that can be used in the Node.js application. Take note that the functionality can be simple or complex. It will depend on the number of JavaScript files that are available.
Callbacks, on the other hand, are the type of responses to an event. For example, when the user clicks on a button, the callback will make sure that something will happen. The application can take note that the same response should happen no matter who is using it.
Asynchronous programming works in such a way that other functions are already happening before the main function is done. This can make the response faster. To make this happen, Node.js needs to make use of the event loop that will dispatch the requests to C++. Once it receives the results, it will be sent back to JavaScript. This might seem long but this will only take a short time.
Image from: https://www.pexels.com/photo/hand-holding-red-sticker-11035369/
The HTTP module can be used by the node.js programmer to get an immediate response. To do this, the programmer simply needs to use the createServer ( ) method. This will run whenever someone tries to use the same computer.
Other important things to note are the following:
Routing – This is figuring out how the application will react to the client’s actions. Different routes are available and the route that the function will take depends on the action.
Middleware – This will have all the access to request or respond to an object.
Request Processing – You need to have the right command ready so that the request will be processed accordingly.
Express.js is the web application framework that is commonly used when you are using Node.js. This is the choice of a lot of people because it is simple yet flexible. Different features are available and they can be used for both apps and websites.
Remember that you cannot set up Express.js unless you already have Node.js on your device. Once this is done, you can do the following:
Create a directory and make sure that it is working.
Use the npim init command.
Enter the name of the main file.
Install Express in your directory.
Node js development can always be improved as long as all the bases are covered. To connect with the database, the programmer should have the appropriate drivers for it. The driver can be installed through a command prompt using the chosen text box. Once you have access, you will be able to go through your needed data.
The ORM can be used to represent the items that are available in the data. It will help you understand the relationship between the programs and the database. Some say that it is the layer that will hold all the information together.
Unit testing is one of the most important things that programmers can do. This will ensure that even the smallest units are working properly. Each code will be isolated and tested so that if discrepancies are going to arise, these will be fixed. To make tests, some fake implementations will be inserted. The testers will check if the codes still react to those fake implementations.
There are different Node.js frameworks that you can choose from. Each framework has pros and cons. You need to consider the deployment options as well as how well the data will perform. You can choose from the following frameworks:
Jasmine
AVA
Mocha
Jest
Image from: https://www.pexels.com/photo/unrecognizable-hacker-with-smartphone-typing-on-laptop-at-desk-5935791/
Different vulnerabilities will always threaten your database. One of the most common vulnerabilities is loose comparison. This happens when the attacker will create something that will make the condition to be always true. True values will be returned to the attacker which can make the data more vulnerable. If the database is tricked, data from the users of the database will be retrieved. The best thing to do is to use mixed data types.
Another common vulnerability is prototype pollution. This type of vulnerability allows the attacker to take control of the data. The tampered data will not work the way that it is supposed to. The best thing to do to counter this is to use the object.assign method. This will help retrieve the data from the user so that it will be updated and corrected.
We learned in the previous tutorial how to connect a joystick to a Raspberry Pi 4 using an mcp3008 and an op-amp IC, the LM324A. For each of the interface methods we studied, we created a python script allowing us to interact with the circuit. This tutorial will show you how to connect a 4-channel relay module with a Raspberry Pi to carry out switching.
A relay's primary function is to allow a circuit to be controlled by a weak signal. High-current applications necessitate relays to separate the low-voltage control circuit from the high-power driving circuits. Because of this, understanding it is crucial for those interested in industrial or household automation.
If you've been tinkering with a raspberry pi for a while, consider the various ways in which you might put it to use.
So let’s dive in!
Four-channel 5V Relay Module
Raspberry pi 4
A Few Jumper cables
5v power source
The raspberry pi has real-world uses, such as remotely turning a device on or off over the internet, sensors, or a mobile app communicating with the pi via Bluetooth. If we can master this, we will open up a world of possibilities.
Anybody who has experimented with a Raspberry Pi knows it has a GPIO.
The 40-pin general-purpose input/output (GPIO) connector is great for connecting various output devices. Since it is a digital computer, Raspberry Pi's GPIO pins can provide logic outputs. Logic 0 and 1 are the terms used to describe these two possible results from a logic circuit. If you write a program to make a Raspberry Pi pin write logic zero, you'll get a real-world GND potential. Likewise, when logic 1 is written on the Raspberry Pi pin, +3.3V is produced.
Logic 0 (gnd) and logic 1 (+3.3v) may be generated on any Raspberry Pi output pin with some programming. However, the output voltage is too low to power any real-world equipment. A maximum of 20 mA can be drawn from the output pin, as the 3.3V generated is currently limited. This only means that we can connect an LED straight to a Raspberry Pi gpio pin. In addition to the DC motor, no other output device can be connected directly to the raspberry pi's pin. Because of this, a different method is required when connecting an AC device.
This image is a cross-sectional diagram of a relay's inner workings. A control coil encloses a core made of iron. When power is supplied to the control coil, an electromagnet begins to energize, boosting the strength of the magnetic field it produces. As a result, the top contact arm attracts the lower fixed arm, closing the contacts and completing the circuit. However, if the relay were de-energized before the connections were closed, the contacts would travel the opposite way, creating an open circuit. When the coil current is shut off, the spring will return the movable armature to its original position.
The operation of a relay is identical to that of a switch. This also means that the same principle applies. When a relay is used, one or even more poles are flipped. Each pole has two primary contact directions. They have NO contact, commonly known as the Normal Open Contact configuration. Connecting with someone is another name for this action. On activation, the relay completes the circuit. Once the relay is deactivated, the circuit is broken.
NC contact is short for normally closed contact. This is synonymous with the term "break contact." In contrast to "NO contact," communication will occur. By switching on the relay, the circuit is broken. As soon as the relay is turned off, the circuit is complete.
A relay's COM contact is shared by the normally closed (NC) and normally open (NO) contacts.
An example of a relay module with two channels is displayed here. As its name implies, a two-channel relay module consists of a circuit with two independent relays built in. This enables the simultaneous manipulation of two distinct gadgets. It follows that the greater the available channels, the more gadgets we can link together.
Let's connect the Pi 4 to the 2-channel relay now. With its four corresponding pins, the 2-channel relay may communicate with a Raspberry Pi. VCC, GND, IN1, and IN2 are the inputs. Current input higher than 30 mA and an input voltage of 5 V is required to power the relay module. As a result of this glaring current shortfall, we must rely on an external power source. Here, we'll employ the widely used MB102 Breadboard Power Supply, an external power supply board. If you're curious about this power source and why we decided to use it, there are some helpful links below. A 3.3 V Relay is what you'll need to operate with Relays without an external power supply.
The relay module's VCC pin must be connected to the power supply's 5 V pin. Then Join the Raspberry Pi 4's ground pin (GND) to the power supply's ground pin (GND). The next step is to attach a jumper wire between the power supply's second GND port and the Raspberry Pi's second GND port. As a result, the ground pin on the Pi 4, the relay switch, and the power source are now all connected. Last but not least, connect a push button to GPIO 2 to activate the relay. Let's connect a few high-powered gadgets across the relay's output now. As seen in the circuit schematic, a CFL is connected to the NC and COM ports.
As was previously mentioned, the RPi is a computer with an output range of only +3.3v to 0v. We need a dedicated electronic switching circuit to link any real-world device to the Raspberry Pi and enable it to switch. Assume throughout this lesson that you want to control an electrical lamp using raspberry pi. A switching circuit is required because we cannot wire the light bulb directly to the raspberry pi. There must be a switching circuit, such as a relay, to turn on and off AC appliances.
The following graphic depicts the internal structure of a relay.
Above, you can see that a basic relay has five connections. The electromagnetic coil's two ends, L1 and L2, serve as the magnet within the relay. Directly connecting the L1 Or L2 to a DC power supply is possible. The coil becomes an electromagnet when it is supplied with an electric current. Unlike the usually closed (NC) and ordinarily open (NO) terminals, the Common terminal can be moved.
The NC terminal serves as the home of the common terminal, which is held in place using sprint tension. This is the relay's initial setting. In a standard setup, the NC and COM terminals of a relay are linked when the device is positioned on a flat surface. The coil becomes magnetized whenever a voltage is placed between coil terminals L1 and L2. The spring tension is opposed by the magnetic force that pulls the common terminal off of NC and onto NO. As long as the relay is live, there will be continuity between NO and COM. Magnetization ceases when the coil voltage is removed, and the common terminal reverts to the NC Terminal, as depicted below.
To conclude, we can switch any AC device on and off with a relay if we know how to do so effectively. However, the issue of activating the relay itself remains to be seen. Typically, relays require a voltage of 12v or 24v, which the Raspberry Pi cannot produce. A microprocessor cannot supply the 30-50mA current required for relays that operate on +5v coil voltage. Consequently, a relay switching circuit is required rather than a direct connection to the raspberry pi.
By adjusting the voltage at the GPIO pins, you may toggle the state of any relay module, whether it's attached directly to the ports or via a relay HAT. Using Python in conjunction with the GPIO library is the simplest solution.
After establishing a connection to the desired GPIO pin, changing its state is as simple as issuing a single command in Python. Pins 26, 20, and 21 on the GPIO header are used for the Waveshare HAT relays. For this reason, for instance, the first relay's power supply can be switched after a delay of just one second.
Sample code
import time
import RPi.GPIO as GPIO
relay_ch = 26
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(relay_ch, GPIO.OUT)
GPIO.output(relay_ch, GPIO.LOW)
time.sleep(1)
GPIO.output(relay_ch, GPIO.HIGH)
GPIO.cleanup()
Using a signal from a microcontroller like a Raspberry Pi, we can switch a DC load with a transistorized switching circuit. Just below, you'll find a quick breakdown of how transistors function.
Here is the complete circuit for using a transistor to switch a relay using a Raspberry Pi.
As demonstrated in the diagram above, the transistor controls the switching of the relay coil, while the relay terminals control the AC load. Any AC load can be connected to a Raspberry Pi using the circuit above and turned on or off remotely.
This setup makes use of the following Components:
Q1 = It can be any regular NPN transistor; we chose a BC548.
R1 = The resistor has a 330-ohm value.
D1 = inexpensive switching diodes such as 4148
RL1 = 12v Relay
Diode D1 is a protection device that allows the relay to be easily turned off, as shown in the diagram.
The transistor base resistor will receive the signal from the raspberry pi pin. Here's a program that will turn on a relay when the output is set to HIGH and turn it off when the output is set to LOW.
led1 = 21 #GPIO pin to connect to relay
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(led1, GPIO.OUT)
while True:
GPIO.output(led1, True)
time.sleep(2)
GPIO.output(led1, False)
time.sleep(2)
A transistor can open and close an electronic gate millions of times per second, allowing electrical signals to pass through and out. As long as electricity flows, the circuit is active; otherwise, it is cut off. Modern telecommunications systems are built on complicated switching circuits that rely on transistors. Circuits can also flip at extremely fast rates, with some offering switching speeds of over 100 billion on/off cycles per second or hundreds of gigahertz.
A logic gate, constructed from several transistors, compares input currents and generates a unique result. Logic gates allow computers to use Boolean algebra to make straightforward decisions. Modern computers and software applications are built on these methods.
A relay module can be easily controlled by connecting its signal pin to the GPIO on a Raspberry Pi and then applying the rated input voltage from the power supply. The necessary transistors and switching circuitry are already on this board. All you have to do to use such a relay module is connect the GND of the power source that powers the relay module (5v/12v/24v) to the GND of the raspberry pi.
import RPi.GPIO as GPIO
import time
Relay_Ch1 = 26
Relay_Ch2 = 20
Relay_Ch3 = 21
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(Relay_Ch1,GPIO.OUT)
GPIO.setup(Relay_Ch2,GPIO.OUT)
GPIO.setup(Relay_Ch3,GPIO.OUT)
print("Setup The Relay Module is [success]")
try:
while True:
#Control the Channel 1
GPIO.output(Relay_Ch1,GPIO.LOW)
print("Channel 1:The Common Contact is access to the Normal Open Contact!")
time.sleep(0.5)
GPIO.output(Relay_Ch1,GPIO.HIGH)
print("Channel 1:The Common Contact is access to the Normal Closed Contact!\n")
time.sleep(0.5)
#Control the Channel 2
GPIO.output(Relay_Ch2,GPIO.LOW)
print("Channel 2:The Common Contact is access to the Normal Open Contact!")
time.sleep(0.5)
GPIO.output(Relay_Ch2,GPIO.HIGH)
print("Channel 2:The Common Contact is access to the Normal Closed Contact!\n")
time.sleep(0.5)
#Control the Channel 3
GPIO.output(Relay_Ch3,GPIO.LOW)
print("Channel 3:The Common Contact is access to the Normal Open Contact!")
time.sleep(0.5)
GPIO.output(Relay_Ch3,GPIO.HIGH)
print("Channel 3:The Common Contact is access to the Normal Closed Contact!\n")
time.sleep(0.5)
except:
print("except")
GPIO.cleanup()
Though I only connected to a single module, adding three more lights to the 4-channel relay board is as simple as looping the live wire from module to module and sharing a common ground, as illustrated in the diagram below.
At this point, the raspberry pi 4 controls the 4-channel relay module. Closed-loop control for high-powered equipment is made possible by incorporating such code in considerably more complex scripts that consider human input or sensor readings.
Due to human fallibility, it is necessary to install home automation systems to ensure electricity is used efficiently and safely wherever possible. As an intelligent platform, Raspberry Pi enables the interconnection and remote control of many home appliances over a single network infrastructure—specifically, the internet. Because of the convenience provided by these appliances.
Home automation systems are a promising new trend in appliance manufacturing to reduce energy use and human error. Raspberry pi-based automation is cutting-edge and innovative. Automating tasks is easier with a Raspberry Pi.
Tell me if you had trouble understanding it or connecting your relay module to your Raspberry Pi 4 in the comments. The next tutorial will teach you how to connect a GPS module to a Raspberry Pi 4.
Greetings, and welcome to the next tutorial in our series on programming for the Raspberry Pi 4. The previous tutorial showed us how to connect a 4x4 keypad to a Raspberry Pi 4. In the previous tutorial, we examined the inner workings of the 4-by-4 keyboard; in this one, we'll use the MCP3008 and the LM324 Op-amp IC to connect a joystick to the Raspberry Pi 4. The Joystick is the primary input device for many gaming systems. The Joystick we'll be connecting to the Raspberry Pi today plugs into a USB port, but there are plenty of situations when having access to the Pi's GPIO pins would be useful. We'll review the steps for preparing the circuit for each interface technique and creating a corresponding python script.
So let’s dive in!
The hardware utilized in this instance is a Pi 4 running Raspbian. All the prerequisites for hardware and software have already been covered, and you can find them in the Raspberry Pi Introduction; other than that, we need:
1000µF capacitor
MCP3008
Joystick Module
LM324 Op-amp IC
1KΩ resistor
LED
2.2KΩ resistor
Jumper wires.
There is a wide variety of joysticks to choose from. In the diagram below, we see a common Joystick module. The Analog Outputs generated by this Joystick module often fluctuate in response to the orientation of the Joystick. Furthermore, we can determine the movement's direction by analyzing these voltage fluctuations with a microcontroller.
In my setup, pressing down on the Joystick toggles an on/off state for the button, so you may use any standard GPIO pin to connect yours. I'll connect it in the same way as the potentiometers, though.
You'll need to familiarize yourself with the Serial Peripheral Interface bus protocol and understand how to configure it on the Pi before connecting the analog controllers to the Pi with a little chip that employs SPI as a communication medium. You can find excellent guides on accomplishing this on the Pi 4 Spy website.
The SPI bus will be activated on specific GPIO pins, which will be the first thing you learn. In my experience, Method 1 (opening a config panel in Raspbian and choosing the SPI option) worked flawlessly. Then, you'll need to ensure the MCP3008 chip is wired properly. That will serve as the connection between your Joystick and the Pi. Pulse-width modulation is worth investigating if you want to change your RGB LED (PWM) colours.
In case you get stuck, I've included some screenshots and a layout of my setup below.
Upon enabling SPI, you should have double-checked that pi-spyder was installed. That is required so that the analog device's input may be read. Setting the LED's colour to correspond with the Joystick's location on the RGB colour wheel may be fun. Let's pretend the X-axis is horizontal over Yellow and the Y-axis is vertical over Orange.
import math
import RPi.GPIO as GPIO
import spidev
# Open SPI bus
spi = spidev.SpiDev()
spi.open(0, 0)
# Define sensor channels (3 to 7 are unused)
mcp3008_switch_channel = 0
mcp3008_x_voltage_channel = 1
mcp3008_y_voltage_channel = 2
# Define RGB channels
red_led = 36
green_led = 31
blue_led = 37
def read_spi_data_channel(channel):
adc = spi.xfer2([1, (8+channel) << 4, 0])
return ((adc[1] & 3) << 8) + adc[2]
def convert_coordinates_to_angle(x, y, center_x_pos, center_y_pos):
dx = x - center_x_pos
dy = y - center_y_pos
rads = math.atan2(-dy, dx)
rads %= 2 * math.pi
return math.degrees(rads)
def adjust_angle_for_perspective_of_current_led(angle, led):
led_peak_angle = 90 if led == 'R' else (210 if led == 'B' else 330)
return ((angle - led_peak_angle) + 360) % 360
def calculate_next_pwm_duty_cycle_for_led(angle, led):
angle = adjust_angle_for_perspective_of_current_led(angle, led)
if 120 < angle < 240:
return 0
elif angle <= 120:
return 100 - (angle * (100 / 120.0))
else:
return 100 - ((360 - angle) * (100 / 120.0))
def is_joystick_near_center(x, y, center_x_pos, center_y_pos):
dx = math.fabs(x - center_x_pos)
dy = math.fabs(y - center_y_pos)
return dx < 20 and dy < 20
def main():
# Center positions when Joystick is at rest
center_x_pos = 530
center_y_pos = 504
GPIO.setmode(GPIO.BOARD)
GPIO.setup([red_led, green_led, blue_led], GPIO.OUT, initial=GPIO.LOW)
pwm_r = GPIO.PWM(red_led, 300)
pwm_g = GPIO.PWM(green_led, 300)
pwm_b = GPIO.PWM(blue_led, 300)
pwm_instances = [pwm_r, pwm_g, pwm_b]
for p in pwm_instances:
p.start(0)
try:
while True:
# If the joystick switch is pressed down, turn off the LEDs
switch = read_spi_data_channel(mcp3008_switch_channel)
if switch == 0:
for p in pwm_instances:
p.ChangeDutyCycle(0)
continue
# Read the joystick position data
x_pos = read_spi_data_channel(mcp3008_x_voltage_channel)
y_pos = read_spi_data_channel(mcp3008_y_voltage_channel)
# If Joystick is at rest in the center, turn on all LEDs at max
if is_joystick_near_center(x_pos, y_pos, center_x_pos, center_y_pos):
for p in pwm_instances:
p.ChangeDutyCycle(100)
continue
# Adjust the duty cycle of LEDs based on the joystick position
angle = convert_coordinates_to_angle(x_pos, y_pos, center_x_pos, center_y_pos)
pwm_r.ChangeDutyCycle(calculate_next_pwm_duty_cycle_for_led(angle, 'R'))
pwm_g.ChangeDutyCycle(calculate_next_pwm_duty_cycle_for_led(angle, 'G'))
pwm_b.ChangeDutyCycle(calculate_next_pwm_duty_cycle_for_led(angle, 'B'))
# print("Position : ({},{}) -- Angle : {}".format(x_pos, y_pos, round(angle, 2)))
except KeyboardInterrupt:
pass
finally:
for p in pwm_instances:
p.stop()
spi.close()
GPIO.cleanup()
if __name__ == '__main__':
main()
So that these methods' input, output, and goals are as apparent as possible, I've put in more effort than normal to comment on the code.
Both the X and Y axes are in use. A potentiometer, or "pot," is attached to each axis of the JOY STICK. Rx and Ry are the resulting midpoints of these pots. It follows that Ry and Rx are the movable centers of these kettles. While the Joystick is idle, Rx and Ry serve as voltage dividers.
The voltage at the Rx pin shifts as the Joystick is pushed along the horizontal axis. Similarly, the value at the Ry pin shifts as the device is tilted or turned vertically. The Joystick can be moved in four directions, with two ADC outputs. The voltage at each pin increases or decreases in response to the stick's orientation changes.
As is well-known, Raspberry Pi lacks any built-in Analog Digital Converter hardware. The Pi would be unable to recognize this module if it were attached directly. We shall employ comparators based on operational amplifiers to verify the voltage outputs. These OP-Amps send signals to the Raspberry Pi, and the Pi uses those signals to turn on and off the LEDs. Here, we've implemented a set of four LEDs to represent the four possible Joystick orientations. Please view the accompanying demonstration video.
All 17 GPIO pins have a maximum voltage rating of +3.3V, meaning that any outputs from the Op-amps must be less than that. We needed an op-amp that could operate at 3V, and the LM324 met both requirements. This IC's pins are a good match for the Raspberry Pi's GPIO connectors.
It has been said that operational amplifiers are the "workhorse" of analog circuits. The LM358 and the LM741 are widely utilized as the most popular varieties of Op-Amp IC. Many functions, such as an amplifier, integrators, differentiators, summers, voltage followers, and more, can be achieved with a single operational amplifier (Op-Amp) by altering the circuitry. Below is a list compiled by Circuit Digest of many Op-amp Circuits, each of which includes a tidy circuit diagram and a practical DIY hardware description to help you learn all about operational amplifiers.
When utilized in Open-loop mode, the Operational Amplifier (or "Op-amp" for short) can be a perfect amplifier with a typical DC gain of over 100,000 or 100dB.
In its most fundamental form, an operational amplifier (Op-amp) is a three-terminal device with two inputs and a single output (excluding power connections).
The power supply for an operational amplifier can be either a single DC voltage or a pair of supplies, one positive (+V) and one negative (-V).
There can be "no current that flows through either of its two inputs" because of the operational amplifier's zero input offset voltage, V1 = V2, and its infinite input impedance, Z = infinity.
Also, the output impedance of an operational amplifier is zero (Z = 0).
Differential amplifiers, or op-amps, are voltage-sensing amplifiers that magnify the voltage difference between their input terminals by a fixed factor called Gain ( A ).
Sometimes called "Open-loop Gain," (A) is a common measure of an amplifier's effectiveness.
This open-loop gain can be considerably reduced and controlled by connecting the op-output amp to one of its input terminals to close the loop.
There are two common ways to wire operational amplifiers, known as inverting and non-inverting.
The LM324 IC includes four OP-AMP comparators to identify Joystick's four possible inputs. Here is the LM324 IC schematic straight from the datasheet.
The following circuit diagram shows the components that make up the Joystick module and the connections that allow it to communicate with the Raspberry Pi. All four comparators within the LM324 are denoted by the U1:A, U1:B, U1:C, and U1:D pins. In the circuit schematic, we have labelled the LM324 IC's comparator pins so that you can easily identify which one goes to which comparator.
We have OP-AMP1 (or U1:A) and OP-AMP2 (or U1:B) for sensing Joystick motion in the Y axis, and OP-AMP3 (or U1:C) and OP-AMP4 (or U1:D) for sensing Joystick motion in the X axis.
The 2.3V (produced by a voltage divider circuit consisting of 1K and 2.2K) is attached to the negative electrode of comparator U1:A, while the positive terminal is wired to Ry. There is an increase in Ry voltage as the Joystick is moved downward along its Y axis. If the input voltage exceeds 2.3V, the OP-AMP will output +3.3V at the output Pin. In response to the OP-HIGH AMP's logic output, the Raspberry Pi will turn on and off an LED.
The 1.0V (supplied by a voltage divider circuit consisting of 2.2K and 1K) is connected to the comparator U1: negative B's terminal, while the positive terminal is wired to Ry. As you raise the Joystick's Y axis, the voltage on Ry will drop. The OP-AMP output will go Low when this voltage falls below 1.0V. When the Raspberry Pi sees the LOW logic output from the OP-AMP, it will respond by turning on and off an LED.
The comparator U1: negative C's terminal is given 2.3V (1K and 2.2K via a voltage divider circuit), while the positive terminal is linked to Rx. Increasing Rx voltage occurs when the Joystick is moved to the left along its x-axis. If the input voltage exceeds 2.3V, the OP-AMP will output +3.3V at the output Pin. In response to the OP-HIGH AMP's logic output, the Raspberry Pi will turn on and off an LED.
U1:4's negative terminal is given 1.0V (through a voltage divider circuit of 2.2K and 1K), while the positive terminal is linked to Rx. Rx voltage drops as the Joystick is moved to the right along its x-axis. The OP-AMP output will go Low when this voltage falls below 1.0V. When the Raspberry Pi sees the LOW logic output from the OP-AMP, it will respond by turning on and off an LED.
This allows Raspberry Pi to receive input from all four logic that controls the Joystick's four directions. Raspberry Pi uses inputs from these comparators to control the state of the LEDs. Here are the terminal outputs from our Raspberry Pi program, which also prints the Joystick's orientation to the screen.
A Python script is available below. The code is simple, and the comments make it easy to understand.
import RPi.GPIO as IO # calling for the header file, which helps in using GPIOs of PI
import time # we are calling for time to provide delays in the program
IO.setwarnings(False) # do not show any warnings
IO.setmode (IO.BCM) #programming the GPIO by BCM PINs (like PIN29 as GPIO5)
IO.setup(21,IO.OUT) # initialize GPIO21 as an output
IO.setup(20,IO.OUT)
IO.setup(16,IO.OUT)
IO.setup(12,IO.OUT)
IO.setup(27,IO.IN) # initialize GPIO27 as an input
IO.setup(4,IO.IN)
IO.setup(22,IO.IN)
IO.setup(17,IO.IN)
while 1:
if (IO.input(27) == 0): #If GPIO 27 goes low toggle LED on 21pin and print RIGHT
IO.output(21,1)
time.sleep(0.01)
IO.output(21,0)
print ("RIGHT")
if (IO.input(4) == 1): #If GPIO 4 goes high toggle LED on 20pin and print LEFT
IO.output(20,1)
time.sleep(0.01)
IO.output(20,0)
print ("LEFT")
if (IO.input(22) == 0): #If GPIO 22 goes low toggle LED on 16pin and print UP
IO.output(16,1)
time.sleep(0.01)
IO.output(16,0)
print ("UP")
if (IO.input(17) == 1): #If GPIO 17 goes high toggle LED on 12pin and print DOW
IO.output(12,1)
time.sleep(0.01)
IO.output(12,0)
print ("DOWN")
As we've seen in this guide, the Pi 4 computer lacks an analog input. The only data it can process is digital. Contrast it with the plentiful analog inputs of common microcontrollers like Arduino, AVR, or PIC. Many sensors produce analog outputs; therefore, we need a method to make the Pi analog-friendly. To that end, we have considered two alternatives. Connecting an MCP3008 microcontroller and an LM324 operational amplifier integrated circuit creates a "bridge" between analog and digital signals. If you have any questions regarding the setup or the code, or if you run into any problems, please let me know in the comments, and I'll do my best to help. The next article will teach you how to use a Raspberry Pi 4 to operate a relay board with four independent outputs.
Welcome to the next tutorial of our raspberry pi programming tutorial. The previous tutorial showed us how to set up a weather station using the Internet of Things (IoT) on a Raspberry Pi 4. First, we studied how a weather station works on a fundamental level. Then we developed a Python script to collect data from the station. In contrast, we'll construct an automatic gate using a Raspberry Pi, a load cell, and an HX711 weight sensor.
These pressure-sensitive gates are common in shopping centers and showrooms; they open when someone is in the immediate vicinity and close again when the person is out of sight. Like the Automatic Gate, we just made, this one will open in response to weight or pressure and stay that way until the force is removed. If you remove the load from this gate, it will close independently.
In this example, a DC motor is the gate, and a piece of rigid cardboard is the load-bearing surface.
Raspberry Pi 4
DC motor
electric gate or DVD trolley
16x2 LCD
Power supply or power bank
HX711 Load Cell Amplifier Module
L293D Motor Driver IC
Jumper wires
Breadboard
A load cell transducer converts mechanical input (force or pressure) into an electric signal. For example, many strain gauges are fastened to an elastic element (with a highly repeatable deflection waveform) to create a load cell.
The load cell depicted in the figure above features four strain gauges, two on each top and bottom surface.
The elastic element of the resistive load cell illustrated above deflects under the applied force, causing a strain at the stress points. For example, see how the animation below depicts how two strain gauges are under tension while the other two are under compression.
The load cell's metal spring element undergoes elastic deformation due to the weight being measured. Its electrical output scales linearly with the applied force. Load cells contain a strain gauge that bends under stress. Strain gauges produce an electrical signal upon deformation due to a change in their effective resistance. Four strain gauges configured as a Wheatstone bridge make up a typical load cell. While load cells can measure loads as small as 5 kilograms or as much as 100 kilograms, we utilized one that measured up to 40 kilograms.
As the Load cell's output electrical signals are only a few millivolts, an amplifier is required; enter the HX711 Weighing Sensor. The HX711 chip inside the HX711 Weight Sensor Module is a 24 high-precision A/D converter. The HX711 features two channels for analog input, and their gain can be programmed up to 128. The HX711 Module boosts the Load cells' light electrical output. The Arduino uses that amplified, digitally transformed signal to calculate the weight.
Four wires lead from the load cell to the HX711 Load cell Amplifier. Red, black, white, and green/blue are the colors of these four wires. Certain modules may have different wire colors than others. Please find the diagram and connecting information below:
RED Wire is connected to E+
BLACK Wire is connected to E-
WHITE Wire is connected to A-
GREEN/BLUE Wire is connected to A+
Channel A or Channel B differential input is chosen by the input multiplexer and fed into the low-noise programmable gain amplifier (PGA). When a 5V supply is connected to the AVDD analog power supply pin, the gain of Channel A can be set to 128 or 64, yielding a full-scale differential input voltage of 20mV or 40mV, respectively. A constant gain of 32 is applied to Channel B. Since the regulator for the analog power used by the Analog-digital converter and the sensor is integrated into the chip, there is no longer any need for a separate supply regulator. The clock input can be set manually. It can come from a crystal or on-chip oscillator that doesn't need anything extra to function. The initialization of digital interfaces is made more accessible by on-chip power-on reset circuitry. The internal registers can be used immediately without any programming. The HX711's pins are used for all of its controls.
To make this system function, a Load Cell must be buried beneath the door's threshold to detect the weight of someone standing nearby. But, for the sake of demonstration, we have secured the load cell beneath a sturdy piece of cardboard. This will allow us to test the gate by placing a weight on the cell. The load cell has been securely fastened to the wooden base with nuts and bolts. Several images of the setup can be seen below:
The resistive load cell is based on the piezo-resistive concept. The sensor's resistance changes as a function of the applied force or stress. When an external voltage is introduced, the output voltage will fluctuate due to the change in resistance.
A capacitive load cell measures the load by measuring the voltage required to cause a change in the capacitance of a system. The capacitance of a standard parallel plate capacitor scales inversely with the distance between both the plates and proportionally with the area of overlap between the plates relative to the dielectric between them.
The wiring is simple for this automatic gate, and a diagram is included for reference. The GPIO pins 18, 23, 24, 25, 8, and 7 of the Raspberry Pi are connected to the RS, EN, d4, d5, and d7 pins of the 16x2 LCD. The DT and SCK pins of the HX711 Module are wired to GPIO pins 27 and 17, respectively, on the Raspberry Pi. In contrast, the DATA and SCK pins of the Motor Driver L293D are wired to GPIO pins 12 and 16, respectively. Already stated and depicted in the circuit diagram below are the load cell connections necessary to use the HX711 Module.
A differential input channel connects straight to the differential signal sent by a bridge sensor. Gain settings of 128 or 64 are selectable via programming. Since the sensor output signal is typically somewhat weak, high gains are required. These improvements translate to an input differential voltage of 20mV or 40mV at full scale when a 5V supply is connected to the AVDD port. The gain of the differential input on channel B is always 32. With a 5V supply at the AVDD pin, an input voltage of 80mV is possible.
Raspberry Pi 4 was used as the central processing unit for this project. First, the pressure near the gate is measured by a load cell, which then sends an analog voltage signal to the HX711 Load sensor Module. Next, the output from the Load cell is amplified and converted to digital form by the HX711, a 24-bit analog-to-digital converter. After that, the Raspberry Pi receives the magnified value. The HX711 output is now converted to a weight value by Raspberry Pi. The motor driver IC L293D is then used by the Raspberry Pi to control the gate based on a comparison with the reference weight. In this case, we're using a DC motor as the gate.
We've set the threshold at 100 grams to ensure that only people weighing more than that are allowed through the gate. Once we've removed the 100 grams or the individual is no longer present, the gate will lock. The standard weighting can be adjusted to fit your needs. The state of the gate can be shown on a 16x2 LCD screen (optional). We have created Python software to automate the entire procedure; the program's source code is available for download, along with a video demonstration.
In this case, Python will be used for the coding. We did not use a library to connect the HX711 load sensor to the Raspberry Pi in this project. Our only guide was the HX711 datasheet and the accompanying application notes. Nonetheless, libraries are available for this purpose; by including the library, you can obtain the weight with minimal effort.
Then, the GPIO Library was implemented, with pins for the LCD, HX711, and DC motor defined and various calculation variables being declared.
import RPi.GPIO as gpio
import time
RS =18
EN =23
D4 =24
D5 =25
D6 =8
D7 =7
DT =27
SCK=17
m1=12
m2=1
Following that, the below code will retrieve information from the HX711 Module.
def readCount():
i=0
Count=0
gpio.setup(DT, gpio.OUT)
gpio.output(DT,1)
gpio.output(SCK,0)
gpio.setup(DT, gpio.IN)
while gpio.input(DT) == 1:
i=0
for i in range(24):
gpio.output(SCK,1)
Count=Count<<1
gpio.output(SCK,0)
#time.sleep(0.001)
if gpio.input(DT) == 0:
Count=Count+1
gpio.output(SCK,1)
Count=Count^0x800000
gpio.output(SCK,0)
return Count
To open or shut the gate, we now compare the HX711 Module's data with a reference weight in the main function.
while 1:
count= readCount()
w=0
w=(count-sample)/106
print w,"g"
if w>100:
setCursor(0,0)
lcdprint("Gate Opened ")
if flag == 0:
gpio.output(m1, 1)
gpio.output(m2, 0)
time.sleep(1.3)
gpio.output(m1, 0)
gpio.output(m2, 0)
time.sleep(1.5)
flag=1;
lcdclear()
elif w<100:
setCursor(0,0)
lcdprint("Gate Closed ")
if flag==1:
gpio.output(m1, 0)
gpio.output(m2, 1)
time.sleep(1.3)
gpio.output(m1, 0)
gpio.output(m2, 0)
time.sleep(2)
flag=0
time.sleep(0.5)
In addition, we define several LCD-specific methods, such as begin(), which initializes the display, lcdcmd(ch), which sends commands to the display, lcdwrite(ch), which prints a single character on the display, lcdclear(), which clears the display, and lcdprint(Str), which prints a string. The complete code is included below for your perusal.
As we have shown, an Automated Gate that detects weight using a Raspberry Pi and a load cell is relatively easy to make.
import RPi.GPIO as gpio
import time
RS =18
EN =23
D4 =24
D5 =25
D6 =8
D7 =7
DT =27
SCK=17
m1=12
m2=16
HIGH=1
LOW=0
sample=0
val=0
gpio.setwarnings(False)
gpio.setmode(gpio.BCM)
gpio.setup(RS, gpio.OUT)
gpio.setup(EN, gpio.OUT)
gpio.setup(D4, gpio.OUT)
gpio.setup(D5, gpio.OUT)
gpio.setup(D6, gpio.OUT)
gpio.setup(D7, gpio.OUT)
gpio.setup(m1, gpio.OUT)
gpio.setup(m2, gpio.OUT)
gpio.setup(SCK, gpio.OUT)
gpio.output(m1 , 0)
gpio.output(m2 , 0)
def begin():
lcdcmd(0x33)
lcdcmd(0x32)
lcdcmd(0x06)
lcdcmd(0x0C)
lcdcmd(0x28)
lcdcmd(0x01)
time.sleep(0.0005)
def lcdcmd(ch):
gpio.output(RS, 0)
gpio.output(D4, 0)
gpio.output(D5, 0)
gpio.output(D6, 0)
gpio.output(D7, 0)
if ch&0x10==0x10:
gpio.output(D4, 1)
if ch&0x20==0x20:
gpio.output(D5, 1)
if ch&0x40==0x40:
gpio.output(D6, 1)
if ch&0x80==0x80:
gpio.output(D7, 1)
gpio.output(EN, 1)
time.sleep(0.005)
gpio.output(EN, 0)
# Low bits
gpio.output(D4, 0)
gpio.output(D5, 0)
gpio.output(D6, 0)
gpio.output(D7, 0)
if ch&0x01==0x01:
gpio.output(D4, 1)
if ch&0x02==0x02:
gpio.output(D5, 1)
if ch&0x04==0x04:
gpio.output(D6, 1)
if ch&0x08==0x08:
gpio.output(D7, 1)
gpio.output(EN, 1)
time.sleep(0.005)
gpio.output(EN, 0)
def lcdwrite(ch):
gpio.output(RS, 1)
gpio.output(D4, 0)
gpio.output(D5, 0)
gpio.output(D6, 0)
gpio.output(D7, 0)
if ch&0x10==0x10:
gpio.output(D4, 1)
if ch&0x20==0x20:
gpio.output(D5, 1)
if ch&0x40==0x40:
gpio.output(D6, 1)
if ch&0x80==0x80:
gpio.output(D7, 1)
gpio.output(EN, 1)
time.sleep(0.005)
gpio.output(EN, 0)
# Low bits
gpio.output(D4, 0)
gpio.output(D5, 0)
gpio.output(D6, 0)
gpio.output(D7, 0)
if ch&0x01==0x01:
gpio.output(D4, 1)
if ch&0x02==0x02:
gpio.output(D5, 1)
if ch&0x04==0x04:
gpio.output(D6, 1)
if ch&0x08==0x08:
gpio.output(D7, 1)
gpio.output(EN, 1)
time.sleep(0.005)
gpio.output(EN, 0)
def lcdclear():
lcdcmd(0x01)
def lcdprint(Str):
l=0;
l=len(Str)
for i in range(l):
lcdwrite(ord(Str[i]))
def setCursor(x,y):
if y == 0:
n=128+x
elif y == 1:
n=192+x
lcdcmd(n)
def readCount():
i=0
Count=0
# print Count
# time.sleep(0.001)
gpio.setup(DT, gpio.OUT)
gpio.output(DT,1)
gpio.output(SCK,0)
gpio.setup(DT, gpio.IN)
while gpio.input(DT) == 1:
i=0
for i in range(24):
gpio.output(SCK,1)
Count=Count<<1
gpio.output(SCK,0)
#time.sleep(0.001)
if gpio.input(DT) == 0:
Count=Count+1
#print Count
gpio.output(SCK,1)
Count=Count^0x800000
#time.sleep(0.001)
gpio.output(SCK,0)
return Count
begin()
lcdcmd(0x01)
lcdprint(" Automatic Gate ")
lcdcmd(0xc0)
lcdprint(" Using RPI ")
time.sleep(3)
lcdcmd(0x01)
lcdprint("Circuit Digest")
lcdcmd(0xc0)
lcdprint("Welcomes You")
time.sleep(3)
sample= readCount()
flag=0
lcdclear()
while 1:
count= readCount()
w=0
w=(count-sample)/106
print w,"g"
if w>100:
setCursor(0,0)
lcdprint("Gate Opened ")
if flag == 0:
gpio.output(m1, 1)
gpio.output(m2, 0)
time.sleep(1.3)
gpio.output(m1, 0)
gpio.output(m2, 0)
time.sleep(1.5)
flag=1;
lcdclear()
elif w<100:
setCursor(0,0)
lcdprint("Gate Closed ")
if flag==1:
gpio.output(m1, 0)
gpio.output(m2, 1)
time.sleep(1.3)
gpio.output(m1, 0)
gpio.output(m2, 0)
time.sleep(2)
flag=0
time.sleep(0.5)
In conclusion, a weight sensor HX711 and load cell can be easily interfaced with a Raspberry Pi 4 with careful attention to wiring and software configuration. In the right hands, the Raspberry Pi's processing capability can precisely measure mass and analyze the results.
Users must connect the load cell's wires to the HX711 Module and then link the HX711 Module to the Raspberry Pi 4's GPIO pins to interface the weight sensor HX711 and the load cell. After that, Python libraries like "pi-plates" and "HX711" can be used to calibrate and read the sensor values.
Once the sensor is installed, the collected data is used widely, including but not limited to weighing objects, measuring food portions, and automating manufacturing procedures. The Raspberry Pi's processing power and network adapters make it simple to incorporate weight sensing into a wide variety of projects and applications.
For makers, hobbyists, and professionals alike, the HX711 weight sensor and load cell interface with Raspberry Pi 4 provides a robust and versatile platform for measuring and analyzing weight data. The next article will show you how to use Raspberry Pi 4 to create a smart agriculture system based on the Internet of Things.
Hey peeps! Welcome to the Engineering Projects where you are learning the basics of Python in detail. We are working a lot with the arrays as these are important concepts in most of the high-level programming languages till now, the numeric data was used in the arrays but for our practice, we are moving towards the next step where the focus will be on the string data type. The practice is done on the Jupyter notebook and every step is going to be explained well without skipping any concepts but to keep things easy, we are not emphasising unnecessary details and concepts. So, before going deep into the topic, have a look at the list of the contents that will be discussed in this lecture:
What are the strings?
How do we use the string in arrays?
What is the list?
How do we extract the characters from a simple string through indexing?
How do you relate the string array with the list?
How can we get more than one character from a string message without using the array?
How do we add more than one message together by using the concatenation?
What is the best way to access the elements of the string array through indexing?
Can we add more elements of the string array into the already declared array?
How do we remove the elements from the string array?
What is the relation between the string and character in Python and how do you extract the single alphabets from the string using the list method?
All these concepts will be discussed in detail and will be understood by using the coding in Jupyter Notebook.
Here is a quick revision of the concept we have learned so far in this series but it is important to understand the basic definition so that we may understand the difference between all of some basic data types. The string is the sequenced order of the characters. It means that all the meaningful conversations between people and even this lecture are in the form of string. So, in this way, the array, containing all the elements in the form of the string is called the string array. We define it as:
"The string arrays are the specific type of arrays in which all the elements are in the form of string which means it contains the collection of characters in such a way that every element is a meaningful word."
We use the string in our daily life during the conversation and there is no need to explain more because we have used the string many times in our series of these lectures.
If we start from the basics then we have to mention that as the string is a collection of different characters, then extracting the characters from the strings it is quite simple and easy. Why we are associating this method with the arrays? It is because the compiler can read all the characters by indexing them one after the other and that is the reason why we can fetch the characters in Python by using the indexing method. So, have a look at the code for doing this simple task:
#Declaring and printing the string message
str="We are learning Python"
#printing the single character from the message
print("The string message = ", str)
print("The second character is " ,str[1])
print("The tenth character is ", str[11])
#Declaring and printing the string message
str="We are learning Python"
#printing the single character from the message
print("The string message = ", str)
#More than one character
print("The characters from second to ninth index are: " ,str[1:8])
#using only semicolons
print("The first ten index characters are : " ,str[:10])
#out of the range characters
print("The out of the range characters are : ", str[:45])
Here, the following points are to be understood:
More than one character can be extracted from the string using the index.
The starting and the ending number of the range you want to print are to be given in the index with a separation using the colon.
If the programmer wants to print the elements from the start to a certain number, there is no need to mention the zero, and we can start directly from the colon.
By the same token, if the colon comes second and then the number is before it, the compiler will print the character at the index starting from the number till the end of the series of the characters.
In case, the programmer gives the numbers that are out of range then the compiler, instead of throwing the error, prints the whole string with its intelligent working.
We all have been working with the addition of numbers in our tutorials, but today, the good thing about the string array in Python is, the addition of the arrays, even if they have strings in them, is as easy as the other types of “addition processes." The process of concatenation is used for this. We define it as:
"The concatenation is a specific process used for the string to join two or more strings together in a specific manner."
The At this level, there is no need to explain more. Have a look at the following code:
#decalring the arrays with string words
A=["hi", "we", "are", "learning", "Python"]
B=["It", "is", "easy", "with", "theengineering.com"]
#Using the concatenation for the addition
print(A+B)
Output:
In Python, the concept of a string array can be associated with the list because it becomes easy for the programmers to deal with the string as the list has the following feature:
These contain the specific order of the elements, and for the string, if we want to have a specific message, the order is important and it makes our task easy.
It allows frequent changes in the elements so that we may change the message according to our requirements.
Duplication of the element is possible in the list, and in the passing of the message, we observe the same words in single sentences.
Similar concepts are being used here that we have seen when we were learning the numerical problems, but this time, it will be interesting to know the difference between the results with the help of shortcodes.
Once you have declared your string, the extraction of single or multiple strings from the same array is fun. The programmer just has to specify the location, and the element is popped on the output. But there are different ways to do so, and some of them are shown in the code next.
#initializing the array containing the name of programming languages
languages=["C++", "C#", "MATLAB", "ASP.NET", "FLutter"]
#printing the arrays using the index in two ways.
print("\bAccessing the data through index: ",languages[3] )
print("\bAccessing the data through negative index: ",languages[-3] )
#getting the whole array of strings through for loop
print("\bPrinting the whole series using loop")
for lan in languages:
print(lan)
Once the array is made, the good thing is that it can be updated according to the will of the programmer. Let’s say we had an array containing the names of the students in the class; if a new student gets admission or the previous one changes the class, it can be updated easily. In other programming languages, the arrays do not allow the updating of the elements.
#initializing the array containing the name of programming languages
languages=["C++", "C#", "MATLAB", "ASP.NET", "Flutter"]
#appending the new element at the end
languages.append("java")
#getting the whole array of strings through for loop
print("\bPrinting the whole series using loop after appending")
for lan in languages:
print(lan)
#deleting the element from the array of string
languages.pop(2)
#getting the whole array of strings through for loop
print("\bPrinting the whole series using loop after deleting")
for lan in languages:
print(lan)
Hence, the update process is easy to use in arrays. The point that must be cleared here is, the pop function is sued to remove the element from the array and the programmer can not use a string in this place otherwise the compiler will show the error. Only the number of the element can be used in this function, and you must have noticed that it is not the position of the element that we have mentioned here but the index of that particular element.
In other programming languages, characters are separate data types that contain single alphabets and have their own identity and existence. In this way, there must be a specific way to initialize the characters and the strings. Usually, in languages such as C++ and C#, the ways to declare the string and characters are different. Strings are denoted by double quotation marks, and the characters are defined by using single quotation marks around the alphabet. The point that I want to make here is, in Python, there is no concept of single characters, but the declaration of the words or characters, when single or double quotation marks are used, means the string, no matter if it is a single alphabet or the whole message.
In case the programmer needs to convert the string into a single alphabet (the data type is still a string), he uses a simple and uncomplicated function to do so. The code and the output of this specific program with an example are given next:
#initialization and printing of the string message.
myMsg = " Python is easy. "
print("The message before conversion= ",myMsg )
#conversion of the string into alphabets.
myMsgList = list(myMsg)
print("The message after conversion= ",myMsgList )
#removing the white spaces from the result.
myMsgList2 = list(myMsg.strip())
print("The message without white spaces =", myMsgList2)
#printing the message without any single space
myMsgList3 = list(myMsg.replace(" ", ""))
print("The message without any single space =", myMsgList3)
Here, the following points must be known to understand all the operations performed.
The string message is initialized simply, and after that, the programmers can convert it into a list for useful functions.
To convert the whole string message into a single alphabet, the “list” function is used, and the characteristics of the string are converted into the list. Now, you do not have the string on the screen but the list.
In this case, the compiler reads even the blank spaces between the alphabet and shows them in the form of a single character with single quotation marks.
To remove the starting and end spaces, there is a method called "stripping" that eliminates the extra spaces from the message, and as a result, we get only the alphabets with the necessary spaces between them.
Another method called “replace” is used in Python which replaces all the spaces between the message and easily converts the whole message into a series of alphabets with no spaces between them.
There are other such methods that deal with the string in different ways. For example, the conversion of the string into single words is also possible, but for now, we are not discussing it. This is all for today, and we hope you learned a lot from this lecture. The beginning of this lecture included a very basic introduction to the string, and we saw how we can use strings in arrays. Moreover, using our concepts, we have learned many built-in functions, and with the usage of the string, it was easy to understand the concepts. We have seen the concatenation and other ways through which we can modify the strings according to our requirements. We will talk more about the string in our next lecture; until then, happy coding.
Hello students! Welcome to the next episode of NumPy, where we are working more on arrays in detail. NumPy is an important library for Python, and for concepts like integer arrays, it has many useful built-in functions that help programmers a lot. In the previous lecture, the installation and basic functions were discussed and this time, our focus is on the general operations and types of arrays that usually the programmers need during the coding. It is an interesting and basic lecture, and you will learn the following concepts in this lecture:
What are some important types of arrays?
Why are we using NumPy for arrays?
What are zero arrays?
What is the random array?
How can we use the ones array using NumPy?
Is it easy to perform the identity array in Numpy?
Practically perform the arithmetic operations in an array.
How do we find the maximum and minimum values in the array?
If we talk about arrays, it is a vast concept, and many points are important to discuss. It is one of the reasons why we are using the library of numPy and it becomes super easy to work on the arrays using it. There are different types of arrays that we have learned about in our mathematics classes, and some of them are so important that NumPy has special functions for them so that programmers who want to use them do not have to write the whole code manually, but instead, using some important instructions, the array is formed and used automatically according to the instructions.
Understanding the zeros array is not as difficult as its name implies; it is the array that has all the entries set to zero. In other words, the array does not contain any other value than zero. The size and shape of the array are not restricted by any rules; therefore, any size and shape of the array can be declared as a zero array.
By the same token, the code for some types of arrays is simple and easy, so here we want to show you how some programmers can add random numbers to their arrays by using this simple instruction. So have a look at the syntax, and then we will use it in the code:
myArray =zeros((numbers of rows, numbers of columns))
For adding more details to your array, you can use the following syntax:
myArray = np.zeros( shape , dtype , order )
We are using the zeros array for the first time, therefore, to keep things simple, we will use the first method in our program.
random.rand(numbers of rows, numbers of columns)
Both of these require less effort, but with the help of these built-in functions, the programmers feel the convenience of getting the best result instead of using multiple lines of code to get the required results:
import numpy as NumPy
#using the zeros method to print the zero array
print("\bZero array with two rows and three columns " )
zeroArray=NumPy.zeros((2,3))
print(zeroArray)
#using the random method to print the array
print("\bThe random array with two rows and three columns ")
randomArray=NumPy.random.rand(2,3)
print(randomArray)
Here, if you have not noticed the syntax, you must see that both of these have similar syntax, but the numbers of brackets are different. If the programmers do not follow the same syntax for each case (for the simple syntax and for the detailed syntax of zero error), then they will face errors.
Now, here is the task for you, check the other syntax mentioned above about the zeros array and try to find out how you can use the other details in your zeros array.
The next program to perform is also easy to understand if you know the previous one discussed above. This time, all the entries in the array are one. It means, no other entry other than 1 is the shape of the array can be rectangular, square, or any other according to the requirement of the programmer.
myArray =ones((numbers of rows, numbers of columns))
#using the ones method to print the ones array
print("\bZero array with two rows and three columns " )
onesArray=NumPy.ones((2,4))
print(onesArray)
# Declaring the array as a tuple
# declaring their data types and printing the results
onesArray = NumPy.ones((2, 3), dtype=[('x', 'int'), ('y', 'float')])
print("\bDetailed ones array= ")
print(onesArray)
print("\bData type of ones array= ")
print(onesArray.dtype)
Hence, in this way, we have seen two ways to print our ones array to compare the best method that programmers can use according to their requirements.
The identity array is another important type of matrix or array that is used in multiple instructions, and programmers dealing with numbers must know its formation and applications. We know that the diagonal entries in a matrix or array are the ones that have the same value for row and column. In simple words:
i=j
Where,
i=positions of the row
j=position of the column
So, for the identity array, these rules are followed:
All the diagonal elements are one.
All the elements other than the diagonal are zero.
No other number is used in the diagonal array.
The shape of the diagonal matrix is always square, which means the numbers of rows are equal to the number of columns.
Now it's time to move towards its code and output.
myArray=NumPy.identity(integer)
As you can see, only one number is required for this type of array because it is decided that the numbers of rows and columns are equal.
import numpy as NumPy
#declaring an identity array with four rows and four columns.
#printing the simple identity array
print("\bsimple identity matrix")
myArray=NumPy.identity(4)
print(myArray)
#Multiplying the whole array with three.
print("\bAfter the multiplication of the identity matrix with three")
myArray2=3*myArray
print(myArray2)
In this way, we have learned that the multiplication of an array is possible in the code, and it is a simple process just as we do it manually in our mathematical problems.
When dealing with the arrays, there are certain points that are pros of choosing this data type to manage our data. One of the most prominent advantages is the mathematical operations that can be performed on the arrays by following simple and uncomplicated syntax. Here is the list of the operations that you are going to observe in just a bit on the arrays:
This topic is interesting, and you are going to love it because it is simple to perform and easy to understand but is an important concept in Python, especially when using arrays. We all have been working with addition, subtraction, multiplication, and division since our childhood, and now is the time to use them in arrays. There is no need to explain more, so let’s move towards the code.
import numpy as NumPy
#Declaring two arrays for the arithmetic operations.
print("\bElements in arrays")
A=NumPy.array([[12,45,11,7],[23,8,11,90],[12,55,1,90]])
print("A= \n", A)
B=NumPy.array([[76,43,1,90],[43,99,14,11],[12,90,22,55]])
print("B= \n", B)
#Performing the arithmetic operations.
print("\bAddition of arrays \n", A+B)
print("\bSubtraction of arrays\n", A-B)
print("\bMultiplication of first array with the second\n", A*B)
print("\bMultiplication of second array with the first\n", B*A)
print("\bDivision of first array with the first\n", A/B)
print("\bDivision of second array with the first\n", B/A)
As you can see, we have a long list of outputs, and all the operations that we have discussed are self-explanatory. Here, we have seen that all the arithmetic operations can be done from array to array. Moreover, if you look at both types of multiplication and division, the answers are different, and it makes sense because these arrays do not follow the commutative law when dealing with arrays. Mathematically,
A*B!=B*A
Similarly,
A/B!=B/A
In addition to this, you must know that scaler arithmetic operations can be performed on the array that means, an integer or the float can be added, multiplied, divide and subtracted from the whole matrix, and the effect of that number will be observed on all the entries of that particular array.
The next operation in which we are interested in finding the maximum and minimum values in the array. These work great when dealing with image processing and related concepts. These are two different operations, and keep in mind, it seems easy to find the maximum and minimum values in the simple and small arrays, but when talking about the arrays with the order 1000*1000, it becomes almost impossible to find the required value. So without using more time, have a look at the code given next:
maximum_value=numPy.max(Name of the array)
minimu_value=numPy.min(Nmae of the array)
import numpy as NumPy
#Declaring two arrays for the arithmetic operations.
print("\bElements in arrays")
A=NumPy.array([[12,45,11,7],[23,8,11,90],[12,55,1,90]])
print("A= \n", A)
#Finding the maximum Value
maximum=NumPy.max(A)
print("Maximum Value in array = ", maximum)
#Finding the minimum Value
minimum=NumPy.min(A)
print("Minimum Value in array = " ,minimum)
Hence, as you can see, the maximum value occurs more than once in that array, but the compiler only gives us one value. The reason why I am mentioning it is that if NumPy is not used in this case and the programmer does not associate it with the array, the compiler throws the error that there must be another function that has to be used with your particular operation because it takes the array as a tuple. These small details are important to observe because many times, the programmers are stuck into such problems and do not get the reason behind the array.
Determinant=numPy.linalg.det(Name of array)
import numpy as NumPy
#Declaring two arrays for the arithmetic operations.
print("\bElements in arrays")
A=NumPy.array([[12,45,11,7],[23,8,11,90],[12,55,1,90],[11,33,66,1]])
print("A= \n", A)
#Getting the determinant of the array
determinant =NumPy.linalg.det(A)
print(determinant)
If you are confused with the keyword that we have just used here, let me tell you that linalg is the method in Python that is associated with the determinant of the square array. In other words, as we have used ”random” with the rand function above, there must be the use of linalg with the det function. Moreover, never use these functions with other types of arrays. The determinant can only be used with the square matrix.
Hence, it is enough for today. We have seen a lot of information about the arrays in this lecture, and all of these were performed on the NumPy library. At the start, we saw the types of arrays that the programmers used often in the coding. After that, we saw the mathematical operations such as the arithmetic and general operations in the NumPy. We tried our best to use similar arrays for different operations to make the comparison in our minds. All of these were uncomplicated, and throughout this lecture, we revised the basic concepts of the matrices and arrays that we learned years ago during our early education of computers and mathematics.
Hey, peps! Welcome to the new tutorial on the Jupyter notebook. As we are moving towards a higher level of Python, therefore, it is important to understand other ways of doing the same task. As we read in the previous lecture about 2D arrays, this time it is going to be done with the help of a famous library in Python. This time, you are going to learn different, engaging, and advanced-level concepts that not only help you deal with the 2D array but also the installation and working of the unique library of Python, which is NumPy. This lecture is going to be very useful and interesting, and therefore, we suggest you have a glance at all the goals of this lecture.
Getting the introduction to NumPy
Successfully installation of NumPy and knowing different methods for it
Using the arrays with the help of NumPy
Creation, indexing, flattening, and appending of the arrays using NumPy
Knowing the different ways in detail to use these methods.
All of these concepts will be clear to you, and we will move on to more details in the next lecture but for this lecture, it is important to learn the basics.
NumPy is a fantastic library for dealing with numeric data. You must know that a library in Python is a collection of modules that add functionality to a Python program. Libraries are typically distributed in the form of packages, which can be installed with package managers such as pip. If you remember, at the very first lecture of this course, we installed the packages by using pip. The same is the case with NumPy, and this will be clear in just a bit, but for now, you must know that they said that they could include modules that define functions, classes, and variables, as well as algorithms and other services.
NumPy, Pandas, matplotlib, and sci-kit-learn are some of the most commonly used Python libraries. They can be used for a variety of tasks, including data analysis and visualization, machine learning, and web development. Python programmers can take advantage of pre-existing code by using libraries, which can save time and effort when compared to writing everything from scratch.
"NumPy (Numerical Python) is a Python library that adds support for large, multi-dimensional arrays and matrices, as well as a large collection of high-level mathematical functions for operating on these arrays."
It is a fundamental Python package for scientific computing. The good thing here is, Python provides programmers with several ways to perform the same task so that every person may use the best way according to the requirements and expertise of the programmers. In the previous lecture, a simple method was used to perform the two-dimensional arrays, but you must know that NumPy is the second way to do so, which is the reason why we arranged this lecture.
Here comes the action. We are going to work with NumPy, and therefore, the installation process is necessary. The good news is, the programmers do not have to follow the prerequisites when you need to install the NumPy but only Python is enough. So if you are following our previous course, you are good to go with the Numpy. There are two ways to install NumPy:
Installation with the Conda (Advanced level)
Installation with the pip (Beginner’s level)
conda |
pip |
It is preferred by professional programmers. |
It is best for the students and learners. |
It is a cross-language therefore, it can install non-python tools and libraries such as compilers and CUDA. |
It only installs the particular Python on the system. It can not install other libraries rather than Python. |
The source through which the conda installs libraries is its own channel so the resources are owned by the conda itself for the installation. Examples of the channels are defaults and conda-forge. |
The installation is done from the Python Packaging Index (PyPI). Here it is important to understand that PyPI is the largest collection of packages and therefore, it has many features that create ease for Python programmers. |
Conda is considered an integrated solution that is used to manage different types of dependencies and environments. It does not need other tools to manage the packages. |
pip method has to get help from different types of tools to manage and arrange the dependencies and packages. |
Installation with the help of Conda also has different types of methods and for the convenience of all types of users, we are discussing all the basic instructions here.
The best practice for such installations is to use an environment. It means, instead of using the “install” method, the programmers will create the new environment.
conda create -n my-env
Once the environment is created, it's time to activate that particular environment.
conda activate my-env
Another option to perform the same option is to use conda-forge. Many professional programmers prefer this method because conda-forge provides a wide range of software packages, and in our case, NumPy is one of them. If you want to install from conda-forge then the following command is needed:
conda config --env --add channels conda-forge
The methods given above were a little bit tricky, and if the programmer prefers the simplest way, then they must only write the command given next:
conda install numpy
Now, for the installation process at the beginner level, you have to follow the steps listed next. You have to understand that it is recommended to be at this level because all the requirements of this course are designed according to easy and effective ways to code. Hence, the steps given next are enough for all of you:
In the window’s search panel, write the Anaconda prompt.
Here, write the following command:
pip install numpy
Wait for the installation and loading of the library on your personal computer.
Now, to check if your NumPy is working well, go to your Jupyter Notebook.
For this, fire up your Jupyter Notebook by searching for it in your window applications.
Go to the new Python project and wait for the new tab to be opened in your browser.
Note: It is essential to notice that every time the programmers want to use Numpy, they have to import it into the code, and that is the first step of every program where the programmer needs to get help from NumPy.
The typical easy-to-deal-with arrays are similar when we talk about the Jupyter notebook and MATLAB etc. Yet, with the advancement of techniques, better and updated methods have been introduced. The NumPy is a numeric library and to learn its usage, the best way is to deal with the arrays. We hope you know the basics of arrays and their fundamental information; therefore, we are directly starting the practice of arrays. In this way, the students will learn the details of 2D arrays and NumPy side by side.
Creating the array is as simple as what the students have seen in the previous lecture. All the steps are easy, and the comments explain the function of each line.
#importing the numpy
import numpy as numPy
#creating the new array from the imported NumPy library
myArray = numPy.array([[34,8,12,4],[90,5,12,78]])
#printing result
print("The 2D array \n ", myArray)
The output of this code is as expected:
If you want to make an array automatically with the minimal information provided by you, then it can be done with the help of NumPy (such as declaring the shape and size of the array). There are other ways to do so, but using NmuPy gives the programmers relief. It is because NumPy has built-in functions; they just have to associate their array with that particular function and get the desired output.
#importing the numpy
import numpy as numPy
#creating the new array from the imported NumPy library
#using the reshape and arrange functions
myArray = numPy.arange(9).reshape(3,3)
#printing the result
print("The 2D array \n ", myArray)
Here, the important points to be noticed are
The arrange function is used to provide information about the total number of elements in the array. But this must be declared by keeping the shape of the array in mind.
The reshape method has the following syntax:
reshape(numbers of rows, number of columns)
The total number of elements must match the shape so that the compiler may arrange the numbers easily; otherwise, the programmer observes the error.
All of the information is connected with the dot operator in the code.
The values in both these functions are enclosed in parentheses.
The arrangement of both functions is important because if the reshape method comes before the arrange method, there will be a long list of errors and the program will not run.
The indeed method is not new to us. We all know that the index always starts at zero. But in the case, we are discussing, one must know that when an array is declared, the index is not for only the elements but for the whole set of the row.
Moreover, flatting is a special method in NumPy in which the output of the resultant elements in an array is not shown in the form of brackets and single rows, but the programmer gets the real form of the array that we have used in our mathematics and other cases of the array. If these two are not clear to you now, do not worry because after looking at the code given next, all things will be clear.
#importing the numpy library
import numpy as numPy
#declaring my array
myArray=numPy.array([[12,56,33,90],[3,89,12,45],[34,89,12,90],[56,12,9,221]])
#using the flatten function
output=myArray.flatten()
print("The array is now = ", output)
#using the index method to get the third-row
a=myArray[2]
print("The third row= ", a)
The output of this program is given next:
Hence, in this way, we have learned two functions in one code. Here you must know that there are many simple and important concepts about arrays. If we start discussing them in separate codes, then it will become boring and lengthy to learn the small functions and methods.
Once the array is declared, the elements can then be modified. This concept is not applicable to other programming languages, such as C++. Yet, Python gives us this convenience, which is useful for programmers. The appending method is simple and easy, and this code will justify this:
#importing the numpy library
import numpy as numPy
#declaring my array
myArray=numPy.array([[12,56],[3,89],[34,89],[56,12]])
print("\bThe array before appending \n", myArray )
#declaring the second array to be appended
myArray2=numPy.array([[23,89],[12,90],[78,9],[78,11]])
#appending the second array with the first one and printing the result
print("\bThe result of two matrices \n ", numPy.append(myArray,myArray2,axis=1))
Hence, both of these arrays are merged by simply appending them to each other. Moreover, the “axis=1” instruction tells the compiler that the rows of both of these arrays are to be joined in the respective manner; otherwise, the whole array is fixed after the second one. You should check it on yourself.
Consequently, we have learned a lot today. From the introduction of NumPy to the installation of this library, all the steps were discussed here in detail. Moreover, this library was tested by using the array in different ways, such as creating, changing the dimensions, indexing, flattening, and appending the elements. All of these concepts were discussed thoroughly, and there are many more operations on the arrays. Hence, stay with us for more details in the next lecture.
Hello students! We hope you are enjoying learning Python, and therefore, we are moving forward with the advanced level of Python. For this, you have to keep in mind that you are moving towards complex codes, and therefore, you have to get ready for expert-level problems. Do not worry, we are not going to leave you alone with these complex codes; rather, we are discussing the amazing and interesting libraries in Python so that your work may be done with the pre-defined codes and applications so you get amazing results by following simple operations and statements. If it is confusing for you right now, do not worry. Have a look at the topics that you will learn about today, and after that, we will move towards the details:
What is meant by a library in programming languages?
List some of the important libraries that are related to Python.
Why learning the introduction of important Python libraries is essential for developers and engineers?
Give us a short introduction of libraries that are specific to some fields and playing important role in the popularity enhancement of Python as a programming language.
Why most of the libraries are specific for neural networks, machine learning and related fields?
We all know the proper meaning of the generic name of a library. It is a collection of books of a different kind in a single building. There are different kinds of books that are related to each other but are different in their content and types. The reason why we are discussing this here is, the libraries of Python, or simply any other programming language, can be defined as:
"In programming languages, a library is a collection of gigantic pre-compiled and pre-defined code that makes the programming more efficient, simple, and interesting."
Not only the codes, but the libraries also contain the documentation, message templates, configuration data, etc. In this way, we get the proper package that now only gives us unique outcomes, but these libraries are very specific to their related fields, and therefore, there is no need to have knowledge about all the applications of Python; one or more specific libraries for a specific field are enough.
The good thing about the Python libraries is that they are similar to other entities, such as methods; that is, they make us comfortable reusing the same code again and again with the help of simple commands. Python has been at the top of the programming language for years, and therefore, there are many communities that are working on it and have useful and fantastic features and workings in their company that give motivation to beginners.
The role of Python libraries is remarkable, given their popularity and the number of people working in the fields of data science, deep learning, machine learning, and related concepts. People are interested in the workings of these libraries, and therefore, every year, more and more findings in these fields are obtained using these libraries.
Let us tell you more about the libraries so that you may understand them better. Python libraries are written in the same syntax as Python semantics, tokens, and syntax. It is surprising to note that most of the Python libraries are written in C language. More than 200 core modules can be used in the Python standard libraries, and this makes Python a terrifically interesting and complex programming language because the programmer has the greed to use more and more features if he is crazy about it.
Without the standard libraries, any programming language is not that efficient, and therefore, we are emphasizing the importance of these libraries. You do not have to know all of these at once, but at this level, we will recommend that you know some very important standard libraries that all Python programmers must know. So here is the introduction of some very essential Python libraries with a very short introduction and the speciality of the related field.
No matter which tutorial you follow, the most remarkable Python library is TensorFlow. At this level, we hope that you know about it or have heard its name. The base of this library is found in Google because it was introduced by Google for numerical analysis and machine learning applications. The basic purpose of TensorFlow is to train machine learning and deep learning models and not only this but also helps to deploy these models on different platforms such as CPUs (Central Processing Units), GPU( Graphic Processing Units), or TPU( Tensor Processing Units), where the last one is special for the numerical analysis of the machine and deep learning methods. The good thing about this library is its flexible architecture and you will be amazed to see it works.
It is one of the most common libraries that is used for numerical analysis, and therefore, the name stands for Numerical Python. This one is also for machine learning applications and is perfect for large-sized matrices and a great amount of data in the multi-dimensional data processing. For easy computation, the built-in mathematical functions are ideal.
The importance of NumPy can be understood by the fact that even powerful libraries such as TensorFlow use NumPy internally to perform the computation with the tensors. Another feature that must be mentioned here is the array interface.
If your aim is to be a data scientist, then this library is a must-have skill for you. If we talk about machine learning, this library provides professionals with a high-level data structure along with analysis tools for data manipulation and cleaning. The basic operations on data such as indexing, re-indexing concatenation, segregation of data, etc can be done with the help of this data science library. This library functions similarly to NumPy, and the programmers can get a highly responsive data structure using the fantastic features that make it the best tool for solving real-life problems.
If you are interested in the computation of tensors in machine learning, then you cannot ignore Pytourch. It is the largest machine-learning library that works for tensor computation and, with strong GPU acceleration, the rich collection of APIs of PyTourch. In solving the complex issues in neural networks, Pytourch has amazing solutions. For the developers of GPU acceleration, PyTourch gives built-in support and therefore, they observe the remarkable speed, efficiency, and working in their field.
The full name of SciPy is Scientific Python, which is an open-source library for scientific computation at a high level. Keep in mind, this is an extension of NumPy, and it is used to deal with complex computational problems with simple commands. You can think of the sorting and indexing of the data as the specialities of SciPy. Most of the developers and engineers know the workings of Scipy, and it gives you a big setup as compared to using NumPy alone.
We have seen that SciPy is more famous for research purposes, and it also offers a C++ interface. Not only with Numpy, but you can have the pair of SciPy with other libraries as well, and it is the favourite library of engineers and developers.
The next library we are discussing is Keras, and Francois Chollet introduced this library as a powerful tool and flexible API by which deep learning and neural networks are dealt with. To reduce the cognitive load on the processors, Keras is designed simpler yet it gives the programmers the perfect working all the time.
When dealing with the deep neural network, GPUs are used for better performance, and Keras helps the developers effortlessly scale the models. If you are interested in building model prototypes quickly, then you should have Keras, because no matter if you are interested in the web browser, iOS, embedded devices, or any other platform, Keras shows impressive deployment capabilities.
If you are a game lover or want to develop games, then this library is for you. For some people, PyGame is the most popular library in Python because the developers know the importance of this magical library. You will find it at the top of SDL (Simple DirectMedia Layer), and the reason behind this is, it provides low-level access to computer hardware such as keyboards, mice, etc. and graphic units such as GPUs via OpenGL and Direct3D.
PyGame is amazing because it makes industry-standard games so that people can use them as a profession. In simple words, Pygame is a cross-platform that offers developers tons of interesting features through which they can develop games efficiently and with less effort. It makes it easy to have the optimized code, so it is easy to understand. Moreover, it supports a multi-core system that makes the code portable for the convenience of the game developers.
Coming back to the numerical data, those who have a large amount of data and want to plot them with minimum effort must install Metaplotlib. Hundreds of companies are using this library because it let the user visualize the data in several ways. Some of the very common uses of this library are histograms, tables, and different types of charts such as bar charts, pie charts, etc.
The good thing about this library is, it is not just restricted to static visualization, but the experts are working deeply with it to get creative and interactive animations with hard work. Another plus point that must be discussed here is that these give fully customizable results that seem great and can be used with other applications.
The name of this library stands for Python Based Reinforcement Learning, and it is a special library for neural networks and artificial intelligence. It is a perfect library for beginners because it is an open-source library, and its easy-to-use algorithm makes it perfect for those who want to get started with learning. Its flexible structure is quickly understood. We recommend this library to those researchers who want to learn the skills and workings of many different fields, including machine learning.
This library has a nice repetition in the student community because artificial intelligence and deep learning are leading fields in many pieces of research, yet not all people are experts in them. In many researches, there is no need to be an expert; the beginner level is more than enough. In such cases, the simplicity and ease of such libraries are a blessing.
The list of Python libraries does not end here, but some others worth discussing are:
Scikit-Learn
scrappy
LightGBM
Bottle
Tkinter
Eli5
Django
MoviePy
NLTK
Open CV
Pillow
Peewee
Beautiful Soup
PyQt
Pytest
All of these are important in specific fields, and you will notice that most of these are specifically optimized for neural networks, artificial intelligence, deep learning, machine learning, etc because these are emerging fields and Python is the most suitable language for these fields. There is so much to talk about in every single library, and you will learn it soon in the coming lectures.
Thus, we saw many useful topics today, and we can say that every library had great value in the information. We started this lecture with an introduction to libraries and kept the compatibility of Python in mind with that introduction. After that, we started introducing the important libraries that every Python programmer must know. It is not necessary that you learn all of these, and it is not wrong to say that a single person cannot be an expert in all these libraries, but the point that we want to make here is that Python is an extremely interesting and useful programming language, and if you want to learn it, you must know the scope of this magical programming language. We will write tutorials on these libraries and their projects in the next lectures, so stay with us for more detailed information about libraries.
Greeting learners! Welcome to the new tutorial on Python, where we are going to discuss the loops. In the previous lecture, our focus was on the primary introduction of the loops in Python. If you are from a programming background, you must know that there is a little bit of difference between the loops in Python and those in other programming languages. At the end of the previous lecture, we saw the details of the basic differences and examined why we consider Python better than other languages when considering loops. In the current lecture, our focus is only on the while loop, and you will get to know its importance soon when we discuss the detail of this loop. But before this, have a look at the list of the major concepts:
What are the loops?
Why do we use the while loop in Python?
What are some major points that must be known about the while loop in Python?
Can we use the loops while designing the games?
What is the concept of statements in Python?
How do break statements work in Python?
What do you know about the continue statement in Python?
What does the else statement do in Python when we use it with the while loop?
All of these are important interview questions and we will find the answer to each and every concept in detail with the example. We have been working with the Jupyter Notebook and therefore, we are again using it for the practical implementation of the concepts of the current lecture. So let’s move towards the first concept.
While loop is one of the most common loops in programming languages and if we talk about Python, loops have fundamental importance and while loop is the favorite of many programmers. No one can get excellence in programming in Python without knowing the detail of the loops in it. The reason why we are learning it so deeply is, there is a bit of difference between Python loops and other programming languages. We discussed it in the previous lecture. There are different reasons behind this statement, and some of them are explained next:
As all the loops do, the while loop repeats itself until a certain condition is satisfied. There is no restriction on the data type in the loop, which means, no matter if you have sequences, strings, integers, or other data types, you can use the while loop anywhere. This gives the programmer the independence to use it in a versatile way by using their creativity. Moreover, keep in mind the condition where the programmer wants to get input from the user after a certain condition is met in the code. In such cases, a while loop is perfect to use, and the restriction can be applied to the input as well.
The idea of the condition is so smooth in the while loop that it becomes interesting to use the sequences in the while loop. In some cases, when the length of the sequence is not known, programmers can use the sequence in the while loop to get the required result. In this way, the compiler keeps iterating the sequence until a certain condition is met.
Have you ever noticed the condition of a game where the sequence of certain objects keeps on moving in a specific sequence? This happens when the loops are used with special planning, and the while loop is one of those loops that provide the perfect results according to the needs of the program. In the simulations where a certain condition is to be fulfilled, the need for the while loop is always felt.
In addition, when the need to fulfil a certain condition is felt, a loop can be used, and the compiler uses the condition again and again until the requirements are met; once the mission is completed, the game is then over. This is the very basic idea that how programmers use while looping in gaming, there are many innovations every year where programmers use the loops in a different way to present interesting results. All the discussion can be proved with the help of the example in the jupyter notebook:
#initializing the while loop with the true condition
while True:
#providing the first condition
try:
#using the integers as the condition
number = int(input("Enter the age of your character: "))
#if the condition is satisfied, the program is terminated
break
#if the condition is not true, throw the error
except ValueError:
#printing the error message
print("The input is not correct, enter only the integers")
Once you have seen the working of the code, you might be thinking, "What happens at the backend?" This example is chosen here to tell you that not all conditions of the loops use a comparison between two things only. We can use the boolean conditions as well to get the required output. If you have seen the simple examples of the while loops, then you must be wondering about the output of this program. You can see that the compiler first gives an error when the input does not meet the requirements of the program.
If the user does not give the expected data type for the program, the compiler goes out of the loop and ignores the break statement. In the second part of the program, the compiler goes to the except value and prints the error message that tells the details of the expected input. In this way, the user understands the requirements in detail, and the program does not end, but the iteration is continued until a certain result is obtained.
In the while loop, there is the ability to use statements of various types, one of which you have just seen. Yet, for the convenience of the learners, we are discussing all the categories in detail. Each of the types has its own example in the Jupyter notebook. To open this, have a look at the steps given next:
In your Windows search bar, go and search for "Jupyter Notebook.”
Wait until it opens a new tab in your browser.
Once the tab is opened, go to the dialogue box and open a new Python project.
It will open a new tab with the cells where you can write your code.
In the while loop, the break statement is used many times. As the name suggests, the break statement breaks the iteration, and the compiler stops executing the program as soon as it passes through the break statement. No matter if the body of the code still has to be executed, if the break statement appears in the code, the compiler stops working. Therefore, programmers use the break statement when they have more than one case and just want to execute the one that suits the condition. There are certain benefits to this statement, and one of these is, it gives the programmer all the long codes at once. Here is an example of a break statement in a while loop:”
#Initializing the variable
a = 4
#Starting a while loop
while a <= 12:
#Printing the required output that we want on the screen
print(a, ":I am a Programmer of Python")
#Using the if loop to provide the condition to the compiler for break statement
if a == 9:
break
#iteration
a += 1
It may seem that the code has some unusual things in it such as the starting point is from 4 instead of 1. This is the way to give you the concept that the starting point is not always zero. It totally depends on the choice of the programmer according to the requirements of the program. Once the variable is declared, the while loop is started, where the maximum number of iterations is shown. Right after declaring the condition, the results are printed.
For the convenience of the reader, I have shown the number of the iteration so that one may understand the whole scenario. Here, to use the break statement, I have shown you the “if” loop. In this way, the compiler understands that whenever the iteration number is 9, it has to stop and jump to the next line instead of completing the iteration. Therefore, after the 9th iteration, the compiler is not showing us any results.
Another thing to notice is, the value of “a” is 4 at the start, but after every iteration, the compiler checks for the value when it is at the last line, and then it sees that the value of “a” is now one number greater, and therefore, the next iteration starts.
If you have understood the previous case, then this one is like a piece of cake because we can say that the working of the continuous statement is somehow opposite to the break statement.
#Initializing the variable
a = 0
#Starting a while loop
while a <= 12:
a += 1
#Using the if loop to provide the condition to the compiler for the continue statement
if a == 3:
continue
#Printing the required output that we want on the screen
print(a,"I am using the continue statement")
The other pieces of code are the same, but you can see there is a bit of difference in the position of some lines. If you have observed this, then you are on point. The iteration is done in the body of the while loop, and right after this, we are using the “if” condition. In the output, observe that the third number of iterations is missing, and this is because we told the compiler to jump whenever the iteration is at the third position. Once the iteration is ignored, the print operation gives us the output on the screen, where our value of the variable and the message on the screen are printed.
The third and last statement of today is the else statement, and this is quite similar to the cases given above. The else statement has the power to show the result once the condition is no longer true. It means that it can be the ending message that we want to print until the condition is satisfied. As a result, we get two blocks of the code at once that can be printed using the same code.
#Initializing the variable
a = 0
#Starting a while loop
while a <= 12:
#Printing the required output that we want on the screen
print(a,"I am using the continue statement")
#iteration
a +=1
#Using the else statement to tell the user that the condition is satisfied
else:
print("The condition is satisfied")
Here, you can see we are getting a continuous stream of the output where every number of the variable is being used. It is because there were no distractions for the compiler in the code within the while loop. Once we have used it to show that all the iterations are done, the compiler then jumps to the else statement, which tells us the final words of the code.
In the end, we can say that today we have learned a lot about the statements used with the while loop in Python, and with the help of examples, the concept is not completely clear. The focus was on the while loop, but using the example of the statements, we understood how we could get the perfect result by merging the concepts of loops and statements in Python. From the introduction to the ending, the discussion was clear about the loops, and we took care of the minor details as well to know best about the while loop. It was an informative lecture, and in the next lecture, we have to know more about loops in Python, so stay tuned with us and be happy with the practice.
Greetings Learners! Welcome to the new lecture on Python. Today we are moving towards an interesting and important concept. If you have come from a programming background, then you must know about the workings of loops. To make the repetition of the same sequence, we use loops. We are familiar with the sequences in detail as we have learned them in the previous lectures and have received the concept in the recent lecture. If you want to be a programmer, then you can not move forward without a solid base of loops; therefore, in this lecture, we will learn the concept of loops from scratch and then go on to a deep understanding of each loop in the next episodes. So have a look at the concepts that you will learn today.
What are the loops?
How do we understand the concept of loops from scratch?
What are some conditions of the loops that we have to understand before programming in loops?
What are the two basic types of loops in Python?
Discuss the syntax and types of loops.
What is the speciality of the while loop?
Why do we prefer the for loop when dealing with for loops?
What are the major differences that make Python better at looping than other types of programming languages?
Each of these is an important interview question, and will we explore the answers of every question mentioned above. In this lecture, the use of Jupyter notebook is not much but for the practicle implementations, this lecture is very important so let us start finding the answers of each question that we have just read now.
In programming languages, loops are the repetition of the same concept, again and again, to get the required output according to the requirements of the programmer. In other programming languages, there are many types of loops, and programmers use them in different ways. Usually, it has been observed that the programmer uses the same kind of loop most of the time that he finds useful or has a good grasp on the concept of a particular type of loop. Loops are defined as:
"Loops are a fundamental control structure in programming that allows you to execute a set of instructions repeatedly until a certain condition is met."
These are extremely useful to execute the conditions and calculations. The working of loops may be different, and the difference in the syntax is an important thing to be noticed, but keep in mind that the output of the loops is almost the same. No matter which type of loop the programmer uses, the output remains the same, just as at the backend, the working and the logic are the same.
When you are going to learn the loops, many people ignore the first step, which is to understand how the loops work at the backend of the code. We are not going into details about how the compiler executes the instruction, but just the steps that have to be followed by the compiler when the user runs the loop. Here are three basic steps:
Checking for the condition created by the programmer. The user always gives the condition at the start of the loop so that the compiler may understand whether the given loop is possible to execute or not. One must keep in mind that the compiler works with the general truths and facts of the real world. It means that if the programmer, say, tells the compiler that 2 is more significant than 10,000, the compiler will reject the condition.
Making the condition is the most important part of the loop for the programmer, and this is the only step where, if you have a strong base in the concept, the programming will become easy for you. This is the only step that will surely run in the loop no matter what condition the programmer applies. It is usually a single line of code, but it is crucial.
Once the condition is satisfied, the body of the code is executed. This is the main step where you will see if you are successful in the loop or not. Once the condition is met and the outcome is true, the compiler enters the body of the loop specified by the programmer and gives the output. Most of the time, the programmer wishes that the condition becomes true, so the remaining code gets the attention of the compiler.
The whole processing is done in the body, and the compiler can give more than one true condition according to the type of condition and other requirements.
It is true that programmers created unusual and amazing products, but there is a limitation that the fact is never ignored. The programmers use the facts in a better way by using their creativity, which results in perfect outputs.
It is obvious that many times, the condition is turned false, and then the compiler simply ignores the body and jumps out of the code. This will only happen if the condition is not satisfied, and this step is not connected with the one that we have just discussed. The detail of each of the steps can be understood by observing the flowchart of the loops given next.
In other programming languages, such as C++ and C#, there are many types of loops. However, in Python, there are primarily two types of loops, each of which has subtypes. In this lecture, you will understand the basic introduction to both of these, and after that, we will move towards the deep concepts and examples of these loops. So, at the most basic level, we can see that there are two types of loops in Python:
While loop
For loop
An introduction to both of them is given next.
The while loop starts with the keyword "while” and then the condition is written so that the compiler can check the condition and then execute the statements written after it accordingly. We introduce the while loop as:
“In programming, the while loop is one of the fundamental types of the loops in which the condition and the statement are the necessary parts of the syntax”
The condition is checked at the start of each iteration, and if it is still true, the loop executes, and this cycle continues until the condition is found to be true. The syntax of a while loop is given next:
while condition
statement(s)
As you can see, the condition is always given first, and the number of statements may vary according to the complexity of the program.
If the concept is taken to a deeper level, we will see that while a loop is a simple type of looping in Python, it has further subtypes, and the names of these are
Infinite loop
Else statement
Single statement while loop
The details and examples of each of them will be discussed in the next lecture.
The for loop is the basic type of looping, and usually, I find it more convenient to use it. Iterations are usually used with the sequence, where the elements of the sequence are repeated again and again. To control the number of iterations, the programmer sets a condition with the “for” keyword, where the compiler always checks the condition and decides whether it has to enter the body or not. Just like the while loop, it can also have more than one statement, and the control is totally in the hands of the programmer.
For iterator in sequence:
statement(s)
Here, you have to understand some concepts:
“For” is the keyword that initiates the loop and tells the compiler to work according to the information fed into the backend.
An iterator can be thought of just like the variable name and the programmer may call it anything according to his choice. Let us say, if it is a, then he will call it in the statement with the same name.
“In” keywords specify that the name of the iterator is now ended and the compiler is now entering into the sequence.
The sequence may be of any type no matter if it is a tuple, array, or list. The good thing about for loop is, it is associated with the sequences and according to the requirement, the programmers can access each and every member of the sequence without making much effort.
Statements may be one or more and it is important that every word of the sequence is correct so that the compiler will execute the instruction and then move towards the for keyword to check the condition again.
From the beginning, we have been saying that Python is simpler than other languages. Moreover, there are other characteristics that make it unique and better. As we are studying the loops so I have made a little comparison between the loops of Python with other programming languages.
Sr# |
Name of the Loop |
Python |
Other Programming Languages |
1 |
For loop |
In Python, the for loop is more versatile because it gives the independence to use any data type whether it is numeric of the string, list, or tuple |
The other programming languages deal with the for loop in just a number of way. It means only the integers are allowed to feed into the for loop of other programming languages. |
2 |
Range function in for loop |
The range function is used in collaboration with the for loop. In Python, it is more concise and dealing with the range function in Python is easier than in other languages, |
In other programming languages, the range function is less concise. The programmers can also use the same function in other languages as well, but dealing with this function is more difficult than in Python. |
3 |
While loop |
The while loop in Python is almost the same as the other languages, but the syntax is different. |
In other programming languages, the while loop works the same as the Python as at the backend, the conditions and workings are the same. |
4 |
Break loop |
Only syntax is different |
Only syntax is different |
5 |
Identation |
It is an important point about Python that makes it unique among others. The identifier is mandatory at some points in Python loops, but in some areas, the unnecessary indentation causes the error. |
The spaces and indentations in other programming languages do not result in any change in the output of the compiler. |
Hence, by using these points, we can conclude that, like every programming language, Python also has many features that make it unique. The loops are more specific and more interesting in Python than in other programming languages, but we have less variety in the loops in Python.
The range function and other functions that have been mentioned above will be discussed with you in detail in the next episode of this lecture. Till then, let us revise the concepts that we have discussed. The concept of loops is important in Python,n and there are only two major types of loops that we have also introduced. The subtypes of these loops also exist. The working of the loops is easy in Python, and we have seen that not all loops have the same syntax, but the differing syntax is important as it differentiates the languages just like other syntaxes. There are three basic steps that are followed by the loops and while constructing the loops, these steps must be cleared in your mind. This was all for today, and in the next episode, you will see the practical implementations of the loops in Python one after the other. Then, try to practice these concepts and keep learning.