Conditional Statements & Decision Making
Let's continue our Coding Interview Series! In this part, we'll learn how programs make decisions using conditional statements, along with practical examples frequently asked in coding interviews.
1. What is a conditional statement?
A conditional statement allows a program to execute different blocks of code based on whether a condition is true or false.
Example (Python):
age = 20
if age >= 18:
print("Eligible to vote")
else:
print("Not eligible")
2. What is an if statement?
An if statement executes a block of code only when a specified condition is true.
number = 10
if number > 0:
print("Positive number")
Output:
Positive number
3. What is the difference between if, elif, and else?
• if: Checks the first condition.
• elif: Checks additional conditions if previous conditions are false.
• else: Executes when none of the conditions are true.
Example:
marks = 75
if marks >= 90:
print("Grade A")
elif marks >= 60:
print("Grade B")
else:
print("Grade C")
Output:
Grade B
4. What is a nested if statement?
A nested if statement is an
if statement written inside another if statement.age = 25
has_id = True
if age >= 18:
if has_id:
print("Entry allowed")
Output:
Entry allowed
5. What is the difference between if-else and switch statements?
If-Else:
• Used to check conditions and ranges.
• Supports complex logical expressions.
• Available in most programming languages.
Switch:
• Used to select one execution path based on a matching value.
• Often cleaner when comparing one expression against multiple fixed cases.
• Available in languages like Java, C, and C++.
Python does not have a traditional switch statement, but it provides
match-case (Python 3.10+).6. How do you check whether a number is even or odd?
A number is even if it is divisible by 2; otherwise, it is odd.
num = 15
if num % 2 == 0:
print("Even")
else:
print("Odd")
Output:
Odd
7. How do you find the largest of two numbers?
Use an if-else statement to compare both numbers.
a = 25
b = 40
if a > b:
print("A is largest")
else:
print("B is largest")
Output:
B is largest
8. How do you find the largest of three numbers?
Use multiple conditions to compare three numbers.
a = 10
b = 25
c = 15
if a >= b and a >= c:
print(a)
elif b >= a and b >= c:
print(b)
else:
print(c)
Output:
25
9. What is a ternary operator?
A ternary operator is a shorthand way of writing a simple if-else condition in a single line.
result = "Adult" if age >= 18 else "Minor"
print(result)
Output:
Adult
10. How do you check whether a year is a leap year?
A year is a leap year if:
• It is divisible by 400, OR
• It is divisible by 4 but not divisible by 100.
year = 2024
if (year % 400 == 0) or (year % 4 == 0 and year % 100 != 0):
print("Leap Year")
else:
print("Not a Leap Year")
Output:
Leap Year
Double Tap ❤️ For More
