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

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

if True:
print("If Block")
print("Inside If")
PYTHON

Output

IndentationError: unexpected indent

Correct Code

if True:
print("If Block")
print("Inside If")
PYTHON

If - Else Syntax

When If - Else conditional statement is used, Else block of code executes if the condition is

False

Using If-Else

Code

a = int(input())
if a > 0:
print("Positive")
else:
print("Not Positive")
print("End")
PYTHON

Input

2

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

if False:
print("If Block")
print("After If")
else:
print("Else Block")
print("After Else")
PYTHON

Output

SyntaxError: invalid syntax
Warning
Note: No code is allowed in between if conditional block and else statement.

Post a Comment

Please Select Embedded Mode To Show The Comment System.*

Previous Post Next Post

Contact Form