Python If-Else Statements
Python If-Else Statements
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
If Statement The if statement is used to test a specific condition. If the condition is true, a
block of code (if-block) will be executed.
If - else The if-else statement is similar to if statement except the fact that, it also provides
Statement the block of the code for the false case of the condition to be checked. If the
condition provided in the if statement is false, then the else statement will be
executed.
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.
Skip Ad
1. if expression:
2. statement
Example 1
Output:
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.
The syntax of the if-else statement is given below.
1. if condition:
2. #block of statements
3. else:
4. #another block of statements (else-block)
Output:
The elif statement works like an if-else-if ladder statement in C. It must be succeeded
by an if statement.
1. if expression 1:
2. # block of statements
3.
4. elif expression 2:
5. # block of statements
6.
7. elif expression 3:
8. # block of statements
9.
10. else:
11. # block of statements
Example 1
Output:
Example 2