7/27/24, 9:00 PM Revolutionizing the Job Market | NxtWave
[Link] 1/6
7/27/24, 9:00 PM Revolutionizing the Job Market | NxtWave
Conditional Statements
Block of Code
A sequence of instructions are called block of code.
Python executes code in a sequence.
Condition
An expression that results in either
True or False
Examples
i. 2 < 3
ii. a == b
iii. True
Conditional Statement
Conditional Statement allows you to execute a block of code only when a
specific condition is
True
[Link] 2/6
7/27/24, 9:00 PM Revolutionizing the Job Market | NxtWave
Conditional Block
Block of code which executes only if a condition is
True is called Conditional Block.
Indentation
Space(s) in front of the conditional block is called indentation.
Indentation(spacing) is used to identify Conditional Block.
Standard practice is to use four spaces for indentation.
Possible Mistakes
Each statement inside a conditional block should have the same indentation
(spacing).
Wrong Code
[Link] 3/6
7/27/24, 9:00 PM Revolutionizing the Job Market | NxtWave
PYTHON
1 if True:
2 print("If Block")
3 print("Inside If")
Output
IndentationError: unexpected indent
Correct Code
PYTHON
1 if True:
2 print("If Block")
3 print("Inside If")
If - Else Syntax
When If - Else conditional statement is used, Else block of code executes if
the condition is
False
Using If-Else
Code
PYTHON
1 a = int(input())
[Link] 4/6
7/27/24, 9:00 PM Revolutionizing the Job Market | NxtWave
2 if a > 0:
3 print("Positive")
4 else:
5 print("Not Positive")
6 print("End")
Input
Output
Positive
End
Possible Mistakes in If-Else
Else can only be used along with if condition. It is written below if
conditional block
Code
PYTHON
1 if False:
2 print("If Block")
3 print("After If")
4 else:
5 print("Else Block")
6 print("After Else")
Output
[Link] 5/6
7/27/24, 9:00 PM Revolutionizing the Job Market | NxtWave
SyntaxError: invalid syntax
Warning
Note: No code is allowed in between if conditional block and else
statement.
[Link] 6/6