Page 431 - CITS - Computer Software Application -TT
P. 431
COMPUTER SOFTWARE APPLICATION - CITS
if statement
The if statement is the most simple decision-making statement. It is used to decide whether a certain statement
or block of statements will be executed or not.
Syntax:
if condition:
# Statements to execute if
# condition is true
Here, the condition after evaluation will be either true or false. if the statement accepts boolean values-if the value
is true then it will execute the block of statements below it otherwise not.
As we know, python uses indentation to identify a block. So the block under an if statement will be identified as
shown in the below example:
if condition:
statement1
statement2
# Here if the condition is true, if block
# will consider only statement1 to be inside
# its block.
Example:
As the condition present in the if statement is false. So, the block below the if statement is executed.
# python program to illustrate If else statement
#!/usr/bin/python
i = 20
if (i < 15):
print(“i is smaller than 15”)
print(“i’m in if Block”)
else:
print(“i is greater than 15”)
print(“i’m in else Block”)
print(“i’m not in if and not in else Block”)
Output:
i is greater than 15
i’m in else Block
i’m not in if and not in else Block
if-else Statement
The if statement alone tells us that if a condition is true it will execute a block of statements and if the condition is
false it won’t. But if we want to do something else if the condition is false, we can use the else statement with the
if statement to execute a block of code when the if condition is false.
Syntax:
if (condition):
# Executes this block if
418
CITS : IT&ITES - Computer Software Application - Lesson 120 - 137