Python 3-Decision Making

Python conditional statement

Generally, if we want to automate any logic, we will be using three different ways to make the logic work on the code. They are,

  • Based on condition -> if/else statement
  • Based on iteration -> for statement
  • Iteration based on condition -> while statement

Python if/else block:

Used to write condition statements based on validation.

Syntax ->

If condition

                Statements

Else

                Statements

Here indentation plays a major role in writing the blocks of statements. So we need to maintain a proper indentation to segregate the blocks.

Below are the few conditions we use it in if/else block

  • We can directly use the Boolean values (True/False) in if/else block.
>>> if(True):
...     print("Hello")
... else:
...     print("Not True")
...
Hello
>>> if(False):
...     print("Hi")
...
>>>
  • And also we can use any Expressions which return Boolean values such as <, >, <=, >=, ==, !=
>>> x = 10
>>> if (x<=10):
...     print('True')
...
True
>>> if (n>10):
...     print('Greater')
...
>>> if (x==10):
...     print('Equal')
...
Equal
>>>
  • In numerical, except 0, all are True conditions.
>>> a=5
>>> if(a):
...     print("a is 5")
...
a is 5
>>> b=0
>>> if(b):
...     print("b is 0")
...
>>>
  • In other data types, must have atleast one index to be True condition.
>>> a,b,c = 1,4,7
>>> if (a>b) and (a>c):
...     print("a is larger")
... else:
...     print("a is smaller")
...
a is smaller
>>>