control-structure
control-structure
Structure
Conditional Statements (Decision Making)
If statements
Else statements
Elif statements
Nested if statements
If Statement
❖ Code Line 7: The if Statement checks for condition x<y which is False in this
case
❖ Code Line 8: The variable st is NOT set to "x is less than y."
❖ Code Line 9: The line print st - is trying to print the value of a variable that was
❖ The "else statement" is usually used when you have to judge one statement on the
basis of other.
❖ If one condition goes wrong, then there should be another condition that should
justify the statement or logic.
❖ Code Line 5: We define two variables x, y = 8, 4
❖ Code Line 7: The if Statement checks for condition x<y which is False in this case
❖ Code Line 9: The flow of program control goes to else condition
❖ Code Line 10: The variable st is set to "x is greater than y."
❖ Code Line 11: The line print st will output the value of variable st which is "x is greater
than y"
When "else condition" does not work
❖ There might be many instances when your "else condition" won't give you the desired result.
❖ It will print out the wrong result as there is a mistake in program logic.
❖ In most cases, this happens when you have to justify more than two statement or condition in a
program.
How to use "elif" statement
Syntax:
A If B else C
Example:
❖ Code Line 2: We define two variables x, y = 10, 8
❖ Code Line 3: Variable st is set to "x is less than y "if x<y or
else it is set to "x is greater than or equal to y".
❖ In this x>y variable st is set to "x is greater than or equal
to y."
❖ Code Line 4: Prints the value of st and gives the correct output
Nested If Statement
Here we have a if statement inside another if..else statement block. Nesting control
statements makes us to check multiple conditions.
num = -99
if num > 0
print(“positive number”)
else:
print(“negative number”)
if -99<=num:
print(“two digit negative number”)
Output:
negative number
two digit negative number