Monday, April 7, 2025

7.12 Conditional statement (if, elif, else) | Grade 9 New Curriculum Computer Science 2082

 


7.12 Conditional statement (if, elif, else)

A conditional statement is like a decision-making tool that allows the program to make decisions based on whether a condition is true or false.

 

Types of conditional statements

 

If Statement: Executes a block of code if the condition is true.

Syntax:

if condition:

    # Code to execute if condition is true

Example:

if x > 10:

    print("x is greater than 10")

 

If-Else Statement: If the condition is true, one block of code is executed; otherwise, another block is executed.

Syntax:

if condition:

    # Code to execute if condition is true

else:

    # Code to execute if condition is false

Example:

if x > 10:

    print("x is greater than 10")

else:

    print("x is 10 or less")

 

If-Elif-Else Statement: Checks multiple conditions. If one condition is true, the corresponding block of code will execute. If none are true, the else block will execute.

 

Syntax:

if condition1:

    # Code to execute if condition1 is true

elif condition2:

    # Code to execute if condition2 is true

else:

    # Code to execute if none of the conditions are true

 

Example:

if x > 10:

    print("x is greater than 10")

elif x == 10:

    print("x is equal to 10")

else:

    print("x is less than 10")

 

Nested If Statements: We can place one if statement inside another to check multiple conditions at different levels.

 

Syntax:

if condition1:

    #code to be executed if condition1 is True

        if condition2:

            #code to be executed if condition 2 is True

        else:

           #code to be executed when condition2 is False

else:

    #code to be executed when condition1 and condition2 are False

 

Example:

if x > 10:

    if x < 20:

        print("x is between 10 and 20")

    else:

        print("x is greater than or equal to 20")

else:

    print("x is 10 or less")

 

 

 

No comments:

Post a Comment