Python Programming

Python if Statement, if elif else statement and how to use them in Raspberry PI based Security System

 Description:

Python if Statement, if elif else statement and how to use them in Raspberry PI based Security System– this is a very detail tutorial about how to use if statement elif statement and you will learn how to make a security system using  a simple if  statement in raspberry pi

Amazon Purchase Links:

Top Gaming Computers

Best Laptops

Best Graphic Cards

Portable Hard Drives

Best Keyboards

Best High Quality PC Mic

Computer Accessories

*Please Note: These are affiliate links. I may make a commission if you buy the components through these links. I would appreciate your support in this way!

What is If statement in python:

So the, if statement is used to check to see if something is the case if it is the case, do something otherwise continue along and you know don’t do anything under the if statement so one of the most common things that you’re going to use with your if statement is going to be some sort of assignment operator so these things are like greater than less than greater than or equal to less than or equal to or just straight-up equal.


How to use Python if statement:

x = 5

y =10

if x > y :

    print('x is greater than y')

let’s say x equals 5 and y equals 10 and so a basic if statement would go something like this  if X is greater than y  then print x is greater than y  when you run this code it doesn’t  show any message on screen as you can see in below figure

python if statement

As you can see in the program given above, the python if statement used is false, because the value assigned to the variable x which is 5 is not greater than the value stored in the variable y. So, when this if condition is executed it will not print anything on the screen. Any statement or a group of statements after the if condition are only executed if the condition is satisfied. So in the case of the above condition, as the condition is false so, it will not print anything. Now, lets have a look at a piece of code given below.

If, I change the if statement from x > y to x<y

x = 5

y =10

if x < y :

    print('x is less then y')




As you can see a value of 5 is stored in the variable x while a value of 10 is stored in the variable y. This time the if condition will be satisfied as the value stored in x is less than the value stored in y.

python if statement

In Python we can use multiple comparison operators in the same if statement, as you can see the program given below.

 x = 6

y = 10

z = 6


if x < y > z :

    print('x is less than y and y greater than z')

This time I stored a value of 6 in the variable x, a value of 10 in the variable y, and a value of 6 in the variable z.

If x < y > z :

This if statement will be satisfied as the value stored in x which is 6 is less than the value stored in y which is 10, while the value stored in y is greater than the value stored in z which is 6.  After executing the above program, I got the following result.

python if statement

As you can see in the screenshot image above, on the right side window you can see the message “x is less than y and y is greater than z”.  So, in order to print a statement or a group of statements, the specified if statement/condition should be satisfied.


What is if else statement:

The if else statement is used to check if the condition is true do this and if the condition is false than do something else.  Let me explain this with the help of some examples.

python if statement

less than assignment operator

x = 6

y = 10

if x < y:

    print('x is less than y')

else:

     print('x greater than y')

I started by assigning values to the variables x and y. I stored a value of 6 in the variable x and a value of 10 in the variable y. as you can see in the program above, I can print any of the two messages which depends on the if statement/condition. If the condition is satisfied this will print the message “x is less than y” and if the condition is not satisfied then it will print the other message “x greater than y”.

I run the above program and it printed “x is less than y” on the screen as you can see in the image below. This time it ignored the statement placed under the else.

python if statement

In the if else combination, the else statement/statements are only executed when the if condition is false. Let me practically explain this by change the values stored in variables x and y.

x = 61

y = 10

if x < y:

    print('x is less than y')

else:

     print('x greater than y')

As you can see in the program given above. This time I stored a value of 61 in the variable x and a value of 10 in the variable y. You can see the value stored in x is greater than the value stored in variable y. This time I changed the if statement to if x < y, which is of course false. So this time it will print the message “x greater than y”. Let’s confirm this by running this program.

python if statement

As you can see after executing the program, it printed x greater than y. Because, the condition was not satisfied and that’s why the statement after the else is printed. So, now I am sure you understand the whole purpose of the if else statement. When the condition is false then the statements following the else are executed.


Equal Assignment operator in python:

The equal equal assignment operator is one of the most commonly operators in python programming. The assignment operator in python or C++ programming is used to check if a value stored in one variable is equal to the value stored in the other variable. Let me explain this with the help of an example. The following program shows how to use the assignment operator in Python.

x = 8

y = 10

if x == y:

    print('x equal to y' ) 

else:

     print('x not y')

As you can see the two values stored in variables x and y are not equal. Let’s run this program.

python if statement

To compare the values stored in variables x and y I used the equal assignment operator. As you can see clearly the values are different. So the python if statement is false that’s why it printed x not y or x not equal to y, it’s totally up to you which message you want to print. Anything you write will be printed. Writing a wrong text will not generate an error but these are considered as the logical errors. Now let’s make some changes to the code.

x = 10

y = 10

if x == y:

    print('x equal to y' )

else:

     print('x not y')

This time I stored the same value 10 in both the variables x and y. this time it will print the message “x equal to y”.

python if statement

As you can see this time the if statement is satisfied as the value stored in x is equal to the value stored in y.


What is if elif statement in python:

To show multi-way decision, based on several conditions, we use if elif. I have been using the if elif statements in advanced level raspberry pi projects available in the Raspberry Pi based projects category. Let’s start with the if elif flow chart.

python if statement

Let’s write a small program to demonstrate how the if elif statement works in the python programming.

a = 10

b = 20

if a > b:

    print('a is greater than b')

elif a==b:

    print('a and b are equal')

elif a < b:

    print('a is less than b')

For the demonstration purposes I stored a value of 10 in variable a and a value of 20 in the variable b. The control flow checks from top to bottom. First of all, it checks

if a > b

in this case this condition is false, so the control will jump to the next condition and checks

elif a==b:

This condition is also false, as the values stored in the variables a and b are not the same. So, again the control jumps to the next condition and checks

elif a < b:

Now this time the condition is satisfied as the value stored in variable a is less than the value stored in b. So this will print ‘a is less than b’ as you can see in the picture below.

python if statement

Now let’s change the values stored in variables a and b.

a = 30

b = 20




if a > b:

    print('a is greater than b')

elif a==b:

    print('a and b are equal')

elif a < b:

    print('a is less than b')

In the above example, the control flow again checks from top to bottom.  first of all, it checks that if a is greater than  b ? so, in this case the condition is true and it ignore the rest of the program and it prints the message “a is greater than b”.

python if statement



python If elif and else:

Now, let take this to another level by using the else statement with the if elif. The if elif and else combination is my favorite one. You can compare a value stored in one variable with multiple values, let say you are getting different values in the range of 0 to 1023 from a sensor. You can use as many if elif conditions. You can compare a pre-defined value with the sensor values and then you can print different messages. Let me explain this with the help of a very simple program how to use the if elif and else all together.

a = 10

b = 20

if a > b:

    print('a is greater than b')

elif a==b:

    print('a and b are equal')

else:

    print('sorry all the condition gone false')

In the above example control flow checks from top to bottom, first of all, it checks that if a is greater than b ? So, in this case the condition is false it to jumps to the next condition and it checks whether a is equal to b again the condition false. So as both the conditions are false that’s why it prints “sorry all the conditions gone false”

python if statement

Enough with the basics. Now it’s time to use the if statement in some practical project using Raspberry Pi.


Use of if statement in Raspberry Pi based project using Python Programming:

Project Name: Raspberry Pi based Security System using Python Programming.

Let’s make a security system based on the Raspberry Pi using IR Sensor, PIR Sensor, and Laser Sensor. When any of the above sensors is activated an LED will turn ON. For this project, you should have a basic knowledge of how to connect different Sensors with Raspberry Pi. If you have never used the Raspberry Pi then read my other articles on the Raspberry Pi in which I have covered the extreme basics including the interfacing and basic python programming. The reason I am sharing the following code, is only to show how the python if statements are used in the real Raspberry Pi based projects.

Raspberry Pi based Security System Circuit Diagram:

python if statement

As you can see the circuit diagram of the Raspberry Pi based Security system is very simple. The IR Sensor output wire is connected with the Raspberry Pi pin number 23. While the VCC and GND pins of the IR Sensor are connected with the Raspberry Pi +5 volts and ground pins.

The PIR Sensor output wire is connected with the Raspberry Pi pin number 22, while the VCC and GND pins of the PIR Sensor are connected with the +5 volts and GND pins of the Raspberry PI.

Finally, the LDR “Light dependent resistor” circuit shown on the left side. An LDR is connected in series with a 10uf capacitor. A wire from the middle of the LDR and capacitor is connected with the Raspberry Pi pin number 18. You can also use a 10K ohm resistor in series with the LDR instead of using the capacitor. This will form the voltage divider circuit. A laser is placed in front of the LDR so when anyone crosses the laser the voltage on the Raspberry Pi is changed. This change in voltage is enough for making the decision.

Three LEDs are connected with the Raspberry Pins 26, 5, and 21. Instead of using the LEDs you can also use the relays, this way you can control 220Vac light bulbs or buzzers. For the relays connections read my other articles. So, now let’s have a look at the following program.


Raspberry Pi Based Security System Python Programming:

import RPi.GPIO as gpio
import time
gpio.setmode(gpio.BCM)
gpio.setwarnings(False)

ir_sensor=23
pir_sensor=22
laser_sensor=18

pir_indicator=26
ir_indicator=5
laser_indicator=21

pir_state=0
ir_state=0
laser_state=0

gpio.setup(ir_sensor,gpio.IN)
gpio.setup(pir_sensor,gpio.IN)
gpio.setup(laser_sensor,gpio.IN)

gpio.setup(ir_indicator,gpio.OUT)
gpio.setup(ir_indicator,False)

gpio.setup(pir_indicator,gpio.OUT)
gpio.setup(pir_indicator,False)

gpio.setup(laser_indicator,gpio.OUT)
gpio.setup(laser_indicator,False)


def pir():
    global pir_state
    if(gpio.input(pir_sensor)==0) and (pir_state==0):
        print('Pir in Normal State..')
        gpio.output(pir_indicator,False)
        pir_state=1
        time.sleep(2)
    time.sleep(1)
    
    if(gpio.input(pir_sensor)==1) and (pir_state==1):
        gpio.output(pir_indicator,True)
        print('Motion Detected..')
        time.sleep(5)
        gpio.output(pir_indicator,False)
        pir_state=0
        
def ir():
    global ir_state
    if(gpio.input(ir_sensor)==0) and (ir_state==0):
        print('IR Normal State..')
        gpio.output(ir_indicator,False)
        ir_state=1
        time.sleep(2)
    time.sleep(1)
    
    if(gpio.input(ir_sensor)==1) and (ir_state==1):
        gpio.output(ir_indicator,True)
        print('Object Detected..')
        time.sleep(5)
        ir_state=0
     
def laser():
    
    global laser_state
    
            
    if (gpio.input(laser_sensor)==0) and (laser_state==0):
        print("laser normal state")
        gpio.output(laser_indicator,False)
        laser_state=1
        time.sleep(2)
        
    time.sleep(1)
    if (gpio.input(laser_sensor)==1) and (laser_state==1):                       
        gpio.output(laser_indicator,True)
        print("laser detect..")
        time.sleep(5)
        laser_state=0        
while(True):
    
    pir()
    ir()
    laser()
    time.sleep(0)



programming explanation:

import RPi.GPIO as gpio

import time

gpio.setmode(gpio.BCM)

gpio.setwarnings(False)

first of all I imported the required library for controlling the raspberry pi gpio pins

ir_sensor=23   gpio pin 23

pir_sensor=22   gpio pin 22

laser_sensor=18   gpio pin 18

Then I defined pins for the Sensors, as you can see the IR Sensor is connected with 23, PIR Sensor is connected with 22, and Laser Sensor is connected with pin number 18.

pir_indicator=26

ir_indicator=5

laser_indicator=21

Then I defined pins for the LEDs, which are used as the indicators.

pir_state=0

ir_state=0

laser_state=0

the pir_state, ir_state, and laser_state variables are used as the flags to stop the unnecessary repetition of code.

gpio.setup(ir_sensor,gpio.IN)

gpio.setup(pir_sensor,gpio.IN)

gpio.setup(laser_sensor,gpio.IN)

then I set the sensors  property as input




gpio.setup(ir_indicator,gpio.OUT)

gpio.setup(ir_indicator,False)

gpio.setup(pir_indicator,gpio.OUT)

gpio.setup(pir_indicator,False)

gpio.setup(laser_indicator,gpio.OUT)

gpio.setup(laser_indicator,False)

def pir():

global pir_state

if(gpio.input(pir_sensor)==0) and (pir_state==0):

print(‘Pir in Normal State..’)

gpio.output(pir_indicator,False)

pir_state=1

time.sleep(2)

time.sleep(1)

if(gpio.input(pir_sensor)==1) and (pir_state==1):

gpio.output(pir_indicator,True)

print(‘Motion Detected..’)

time.sleep(5)

gpio.output(pir_indicator,False)

pir_state=0

pir() function is a user-defined function, it has no return type and does not take any arguments as the input. As you can see clearly, inside this function we have only two if statement, these if conditions are used to check if the pir sensor has detected any motion or not.

if(gpio.input(pir_sensor)==0) and (pir_state==0):

This condition means if there is nobody in front of the PIR sensor, or the PIR sensor has not detected any motion and pir_state is also 0 then print on the screen “Pir in Normal State..”, turn off the LED and change the pir_state to 1 and wait for 2 seconds.



You might be thinking why am I using the pir_state?

I am using the pir_state as the flag. If we don’t use this then the following instructions will be executed again and again.

print(‘Pir in Normal State..’)

gpio.output(pir_indicator,False)

pir_state=1

time.sleep(2)

Executing these instructions again and again wastes only the processing time, and also keep the raspberry pi busy. We can solve this by using the flags. This way the above instructions will be executed only one time, and as the flag status is changed so the condition becomes false. Similarly for the other condition.

if(gpio.input(pir_sensor)==1) and (pir_state==1):

gpio.output(pir_indicator,True) // turn on the pir_indicator

print(‘Motion Detected..’) // prints this message

time.sleep(5) // wait for 5 seconds

gpio.output(pir_indicator,False) // Turns off the pir_indicator

pir_state=0 // status is changed

as you can see the pir_state is again changed to 0. So, by using flags we can stop the unnecessary repetition of codes, and the instructions placed inside the if conditions can be executed only one time.

def ir():

global ir_state

if(gpio.input(ir_sensor)==0) and (ir_state==0):

print(‘IR Normal State..’)

gpio.output(ir_indicator,False)

ir_state=1

time.sleep(2)

time.sleep(1)

if(gpio.input(ir_sensor)==1) and (ir_state==1):

gpio.output(ir_indicator,True)

print(‘Object Detected..’)

time.sleep(5)

ir_state=0



ir() function is also a user defined function, it has no return type and does not take any arguments as the input. As you can see clearly, inside this function we have only two if statement conditions, these if statement conditions are used to check if the ir sensor has detected any object  or not.

if(gpio.input(ir_sensor)==0) and (ir_state==0):

This condition means if there is nobody in front of the IR sensor, or the IR sensor has not detected any object and ir_state is also 0 then print on the screen “ir in Normal State..”, turn off the LED and change the ir_state to 1 and wait for 2 seconds.

you might be thinking why am I using the ir_state?

I am using the ir_state as the flag. If we don’t use this then the following instructions will be executed again and again.

print(‘ir in Normal State..’)

gpio.output(ir_indicator,False)

ir_state=1

time.sleep(2)

Executing these instructions again and again wastes only the processing time, and also keeps the raspberry pi busy. We can solve this by using the flags. This way the above instructions will be executed only one time, and as the flag status is changed so the condition becomes false. Similarly for the other condition.

if(gpio.input(ir_sensor)==1) and (ir_state==1):

gpio.output(ir_indicator,True) // turn on the ir _indicator

print(object Detected..’) // prints this message

time.sleep(5) // wait for 5 seconds

gpio.output(ir_indicator,False) // Turns off the ir _indicator

ir _state=0 // status is changed

as you can see the ir_state is again changed to 0. So, by using flags we can stop the unnecessary repetition of codes, and the instructions placed inside the if statement conditions can be executed only one time.



def laser():

global laser_state

if (gpio.input(laser_sensor)==0) and (laser_state==0):

print(“laser normal state”)

gpio.output(laser_indicator,False)

laser_state=1

time.sleep(2)

time.sleep(1)

if (gpio.input(laser_sensor)==1) and (laser_state==1):

gpio.output(laser_indicator,True)

print(“laser detect..”)

time.sleep(5)

laser_state=0

laser () function is also a user defined function, it has no return type and does not take any arguments as the input. As you can see clearly, inside this function we have only two if statement conditions, these python if statement conditions are used to check if the LDR sensor has detected any object  or not.

if(gpio.input(laser _sensor)==0) and (laser _state==0):

This condition means if there is nobody in front of the LDR “laser sensor, or the LDR sensor has not detected any object and laser_state is also 0 then print on the screen “laser Normal State..”, turn off the LED and change the laser _state to 1 and wait for 2 seconds.

you might be thinking why am I using the laser_state?

I am using the laser _state as the flag. If we don’t use this then the following instructions will be executed again and again.




print(laser Normal State..’)

gpio.output(laser_indicator,False)

laser_state=1

time.sleep(2)

Executing these instructions again and again wastes only the processing time, and also keeps the raspberry pi busy. We can solve this by using the flags. This way the above instructions will be executed only one time, and as the flag status is changed so the condition becomes false. Similarly for the other condition.

if(gpio.input(laser_sensor)==1) and (laser_state==1):

gpio.output(laser_indicator,True) // turn on the laser _indicator

print(object Detected..’) // prints this message

time.sleep(5) // wait for 5 seconds

gpio.output(laser_indicator,False) // Turns off the laser _indicator

laser_state=0 // status is changed

As you can see the laser_state is again changed to 0. So, by using flags we can stop the unnecessary repetition of codes, and the instructions placed inside the python if statement conditions can be executed only one time.

while(True):

pir()

ir()

laser()

time.sleep(0)

Finally, I called all the user defined functions in the while (True) function.


Related Raspberry Pi Based Projects:

Raspberry Pi home/Office Automation using RFID

https://www.electroniclinic.com/raspberry-pi-home-automation-using-rc522-rfid-smart-home/

Raspberry Pi RFID RC522 NFC Reader, Tags Scanner python code

https://www.electroniclinic.com/raspberry-pi-rfid-rc522-nfc-reader-tags-scanner-python-code/

Raspberry Pi Industrial Automation HMI/GUI designing using PYQT5

https://www.electroniclinic.com/raspberry-pi-industrial-automation-hmi-gui-designing-using-pyqt5/

Engr Fahad

My name is Shahzada Fahad and I am an Electrical Engineer. I have been doing Job in UAE as a site engineer in an Electrical Construction Company. Currently, I am running my own YouTube channel "Electronic Clinic", and managing this Website. My Hobbies are * Watching Movies * Music * Martial Arts * Photography * Travelling * Make Sketches and so on...

Leave a Reply

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

Back to top button