Python if-else Unit-2(2.1)
Python if-else Unit-2(2.1)
Decision making is the most important aspect of almost all the programming languages. As the name
implies, decision making allows us to run a particular block of code for a particular decision. Here, the
decisions are made on the validity of the particular conditions. Condition checking is the backbone of
decision making.
Statement Description
Indentation in Python
For the ease of programming and to achieve simplicity, python doesn't allow the use of parentheses
for the block level code. In Python, indentation is used to declare a block. If two statements are at the
same indentation level, then they are the part of the same block.
Generally, four spaces are given to indent the statements which are a typical amount of indentation in
python.
Indentation is the most used part of the python language since it declares the block of code. All the
statements of one block are intended at the same level indentation. We will see how the actual
indentation takes place in decision making and other stuff in python.
The if statement
The if statement is used to test a particular condition and if the condition is true, it executes a block of
code known as if-block. The condition of if statement can be any valid logical expression which can be
either evaluated to true or false.
The syntax of the if-statement is given below.
if expression:
statement
Example 1
Output:
a = int(input("Enter a? "));
b = int(input("Enter b? "));
c = int(input("Enter c? "));
if a>b and a>c:
print("a is largest");
if b>a and b>c:
print("b is largest");
if c>a and c>b:
print("c is largest");
Output:
Enter a? 100
Enter b? 120
Enter c? 130
c is largest
If the condition is true, then the if-block is executed. Otherwise, the else-block is executed.
if condition:
#block of statements
else:
#another block of statements (else-block)
Output:
Output:
The elif statement works like an if-else-if ladder statement in C. It must be succeeded by an if
statement.
if expression 1:
# block of statements
elif expression 2:
# block of statements
elif expression 3:
# block of statements
else:
# block of statements
Example 1
Output:
Example 2