Python Programming - Conditional Statements

Exercise : Conditional Statements - General Questions
  • Conditional Statements - General Questions
1.
What is the purpose of the if statement?
To declare a variable
To define a function
To control the flow of a program based on a condition
To create a loop
Answer: Option
Explanation:
The if statement is used to make decisions in Python. It allows you to execute a block of code if a certain condition is true.

2.
Which keyword is used to introduce the else block in an if-else statement?
elif
else
then
or
Answer: Option
Explanation:
In an if-else statement, the else keyword is used to define the block of code that should be executed if the condition in the if statement is false.

3.
What will be the output of the following code?
x = 10
y = 5
if x > y:
    print("x is greater")
else:
    print("y is greater")
x is greater
y is greater
No output
Syntax Error
Answer: Option
Explanation:
The code compares the values of x and y using the > (greater than) operator. Since x is greater than y, the code inside the if block will be executed, printing "x is greater."

4.
Which of the following is the correct syntax for an if statement with multiple conditions?
if condition1:
    # code block
if condition2:
    # code block
if condition1:
    # code block
elif condition2:
    # code block
if condition1:
    # code block
else if condition2:
    # code block
if condition1:
    # code block
else condition2:
    # code block
Answer: Option
Explanation:

The correct syntax for an if statement with multiple conditions is to use elif (short for "else if") for subsequent conditions after the initial if statement.

Option A is also a valid syntax for handling multiple conditions, but it doesn't ensure mutual exclusivity between the conditions. In this case, both code blocks would execute if both condition1 and condition2 are true.


5.
What will happen if the following code is executed?
temperature = 25
if temperature > 30:
    print("It's hot!")
elif temperature > 20:
    print("It's warm.")
else:
    print("It's cool.")
It will print "It's hot!"
It will print "It's warm."
It will print "It's cool."
It will print nothing (no output)
Answer: Option
Explanation:
The code checks multiple conditions using if and elif. Since temperature is 25, it satisfies the second condition (temperature > 20), and the corresponding code block inside the elif will be executed, printing "It's warm."