Python Lesson 9 : Decision making in python (if Statements)

  1. Logical Conditions
  2. Writing ”if” statements
  3. Writing If variable is equal to
  4. Writing If variable is not equal to
  5. Writing If variable is greater than
  6. Writing If variable is less than
  7. Writing variable is less than or equal to
  8. Writing variable is greater than or equal to
  9. Writing variable is not equal to
  10. Handling Multiple conditions using if/elif statements
  11. Adding a default condition to you if statements

Executing code based on a condition being true of false is common in programming. Python has a few techniques for handling conditions in your program. 

1) Logical Conditions

Lets first learn the logical conditions in Python:

Conditon Syntax
Equals  a == b
Not Equals  a != b
Less than  a < b
Less then or equal to  a <= b
Greater than  a > b
Greater than or equal to  a >= b
Using the “not” keyword means the condition is. false not a == b (a is not equal to b)  not a > b (a is not greater than b)  Etc…

2) Writing ”if” statements

”If” statements test if a condition is true or false. If the condition is met then the code is executed.

3) Writing If variable is equal to

a = 4
# equal to
if a == 4:
	print(a)
Notebook Output

4) Writing If variable is not equal to

b = 5
# not equal to
if b != 4:
    print(b)
Notebook Output

5) Writing If variable is greater than

c = 7
# greater than
if c > 5:
    print(c)
Notebook Output

6) Writing If variable is less than

Notebook Output

7) Writing variable is less than or equal to

Notebook Output

8) Writing variable is greater than or equal to

f = 6
# is greater than or equal to
if f >= 5:
    print(f)
Notebook Output

9) Writing variable is not equal to

Notebook Output

10) Handling Multiple conditions using if/elif statements

color = "blue"
#handle multiple conditions with if/elif
if color == "red":
    print("color is red")
elif color == "green":
    print("color is green")
elif color == "blue":
    print("color is blue")
Notebook Output

11) Adding a default condition to you if statements

color = "yellow"
#handle multiple conditions with if/elif/else
if color == "red":
    print("color is red")
elif color == "green":
    print("color is green")
elif color == "blue":
    print("color is blue")
else:
    print("color is not red, blue or green")
Notebook Output

Recommended Books