Python Conditions

In this tutorial, you will learn about Python conditions. An if-else condition in Python is used to decide whether a certain condition is True or False.

It determines which block of code to execute depending on the evaluation of a condition.

Syntax:


if condition:
    # Code to execute if condition is True
else:
    # Code to execute if condition is False

Explanation:

If condition: If the condition is True, the block of code inside the if statement will be executed.

else condition: If the condition is False, the block of code inside the else statement will be executed.

Example:


age = 21

if age >= 21:
    print("You are an Adult.")
else:
    print("You are not an Adult.")

In this example:

If the age is 21 or more, the output will be “You are an Adult.”

Otherwise, the output will be “You are not an Adult.”

elif (else if) for Multiple Conditions:

You can also use elif to check multiple conditions:


x = 20

if x > 20:
    print("x is greater than 20")
elif x == 20:
    print("x is exactly 20")
else:
    print("x is less than 20")

Nested if statements:

You can also use nested if statements.


x = 20
y = 30

if x > 10:
    if y > 15:
        print("x is greater than 10 and y is greater than 15")

Short-hand if (Ternary Operator):

The ternary operator is used to apply a condition in a single line.


x = 10
print("x is greater than 5") if x > 5 else print("x is 5 or less")

Python Conditions – Interview Questions

Q 1: What are conditional statements in Python?
Ans: They are used to execute code based on conditions.
Q 2: Which keywords are used for conditions?
Ans: if, elif, and else.
Q 3: Can Python conditions work without else?
Ans: Yes, else is optional in conditional statements..
Q 4: What type of value must a condition return?
Ans: A condition must return a Boolean value.
Q 5: What is nested if in Python?
Ans: An if statement inside another if statement.

Python Condition – Objective Questions (MCQs)

Q1. Which keyword is used to start a conditional statement in Python?






Q2. What will be the output of the following code?

x = 10
if x > 5:
print("Yes")
else:
print("No")






Q3. Which of the following keywords is used for an alternative condition in Python?






Q4. What will be the output of the following code?

a = 5
b = 5
if a == b:
print("Equal")
else:
print("Not Equal") 






Q5. Which of the following statements about Python conditional statements is true?






Related Python Condition Topics