Control Flow and Loops

Conditional Statements & Loops

Conditional statements are used to control the flow of execution in a program based on certain conditions. They allow you to make decisions and execute different blocks of code depending on whether a condition is true or false. This topic covers the basic usage of if-else statements and nested if-else statements in Python.

Examples

Example 1: if-else Statement

x = 10

if x > 5:
    print("x is greater than 5")
else:
    print("x is not greater than 5")

Output:

x is greater than 5

Example 2: Nested if-else Statement

x = 10
y = 5

if x > y:
    print("x is greater than y")
elif x < y:
    print("x is less than y")
else:
    print("x is equal to y")

Output:

x is greater than y

Example 3: Nested if-else Statement with Multiple Conditions

x = 10
y = 5
z = 7

if x > y:
    if x > z:
        print("x is the largest")
    else:
        print("z is the largest")
elif y > z:
    print("y is the largest")
else:
    print("z is the largest")

Output:

x is the largest

Exercises

Exercise 1:

Question: What is the purpose of a conditional statement?

Answer: The purpose of a conditional statement is to make decisions and execute different blocks of code based on certain conditions.

Exercise 2:

Question: How do you write an if-else statement in Python?

Answer: An if-else statement in Python is written using the if keyword, followed by the condition to be checked, a colon, and an indented block of code for the "if" branch. The "else" branch is denoted by the else keyword, followed by a colon and another indented block of code.

Exercise 3:

Question: What is a nested if-else statement?

Answer: A nested if-else statement is an if-else statement that is nested inside another if or else block. It allows for multiple levels of conditions and decisions based on those conditions.

Exercise 4:

Question: How do you write a nested if-else statement in Python?

Answer: A nested if-else statement in Python is written by indenting an if-else statement inside another if or else block.

Exercise 5: Question: What is the output of the following code snippet?

x = 5

if x > 10:
    print("x is greater than 10")
else:
    if x > 7:
        print("x is greater than 7")
    else:
        print("x is not greater than 7")

Answer: The output of the code snippet will be "x is not greater than 7".

Last updated

Was this helpful?