CH 3 Operators Statements in Python 3
CH 3 Operators Statements in Python 3
CH 3 Operators Statements in Python 3
HYDERABAD REGION
E-CONTENT
COMPUTER SCIENCE CLASS XI
CONDITIONAL STATEMENTS
IF-ELIF-ELSE
THAMARAI N, PGT CS
JNV PALAKKAD
Learning Objectives
PROCESS DECISION
SUBPROCESS START/END
DOCUMENT DATA
EXAMPLE FOR FLOWCHART
IF STATEMENT.
This is the simplest decision-
making statement in Python. It is
used to decide if a particular
PYTHON
block of codeIFneeds
STATEMENTS
to be
executed or not. Whenever the
given condition is True, then the
block of code inside it gets
executed, else it does not
SYNTAX FOR IF
if condition:
body of if
Example of if statement:
If you have only one statement to execute, then you can put it on the same line
as the if statement. Let's try doing this for the above example.
num1, num2 = 5, 6
if(num1 < num2): print("num1 is less than num2")
if else statement
The statements written within the else block get executed whenever the if condition
is False. You can imagine the flow of execution this way,
The syntax for if else statement:
Else statement is preceded by the keyword 'else' and it also ends with a colon :.
Unlike the if, the else statement will not have any conditional statements.
if condition:
body of if
else:
body of else
EXAMPLE
Explanation:In the above-given code, the if condition is False and hence the
control shifts to the else block. Hence the statement written within the else block
gets printed.
Shortcut of if else
If you have only one statement each for if and else, then they can be
put in the same line. This can be done as shown below
num1, num2 = 6, 5
print("num1 is less than num2") if (num1 < num2) else
print("num2 is less than num1")
num1, num2 = 5, 5
if(num1 > num2):
print("num1 is greater than num2")
elif(num1 == num2):
print("num1 is equal to num2")
else:
print("num1 is less than num2")
Output:num1 is equal to num2
Nested if statements
SYNTAX:
if condition1:
statements
if condition2:
statements
else:
statements
else:
statements
THE FLOW CHART: NESTED IF
Examples of nested if statements: