Python Conditional Statements

The conditional statement in Python executes a specific block of code depending on the boolean values. If a boolean value is true then conditional statement executes a block of code, but if the boolean returns false, then it executes another block.

Python conditional statements are controlled by the IF, ELSE and ELIF statement.

  • if – when the boolean value returns True, the codes inside of if statement is executed.
  • else – when the boolean value returns False, the codes inside of else statement is executed.
  • elif – when multiple conditions are used, then the elif part statement is used.

Conditionals: Real-world implementation

Suppose you want to program a lift. Where the lift can have a maximum of 10 passengers or a maximum of 1000 kg.  As the lift has a specific amount of space and obviously limited. Your problem is, you have to implement the program in the lift circuits that will give you a warning when the weight of all passengers is more than 1000 kg, and also the lift will not move until the weight is under 1000 kg.

See the example below how can we do it using Python programming


#Python conditionals statement example

weight = 1005 # current passenger weight
isMoveable = 0 # lift moveable status, by deafult not moveable
on = 1 # lift moveable
off = 1 # lift not moveable

if weight > 1000:
    print("Lift is over loaded!")
    isMoveable = off # lift won't move to any floor
elif weight == 1000:
    print("Lift is full")
    isMoveable = on # lift will move to the indicated floor
    print("Current weight: %d" % weight)
    isMoveable = on  # lift will move to the indicated floor


Lift is over loaded

In the next subsequent tutorials, we will learn how to apply each type of conditional statement in Python with examples.

Posted in