What are Conditional Statements?
Conditional statements are used to make decisions in a program based on certain conditions.
They allow a program to execute different blocks of code depending on whether a condition is True or False.
if Statement
The if statement is used to execute a block of code only when the given condition is True.
Example:
age = 20
if age >= 18:
print("Eligible to vote")
Output:
Eligible to vote
Explanation:
- The condition
age >= 18is checked. - Since the condition is True, the statement inside the if block is executed.
if-else Statement
The if-else statement is used when there are two possible outcomes.
- If the condition is True, the if block executes.
- If the condition is False, the else block executes.
Example:
number = 7
if number % 2 == 0:
print("Even Number")
else:
print("Odd Number")
Output:
Odd Number
Explanation:
The modulus operator (%) checks the remainder.
- If the remainder is 0, the number is even.
- Otherwise, the number is odd.
if-elif-else Statement
The if-elif-else statement is used to check multiple conditions.
-
ifchecks the first condition. -
elifchecks additional conditions if the previous conditions are False. -
elseexecutes when all conditions are False.
Example:
mark = 85
if mark >= 90:
print("Grade A")
elif mark >= 80:
print("Grade B")
elif mark >= 70:
print("Grade C")
else:
print("Fail")
Output:
Grade B
Nested if Statement
A nested if statement means writing an if statement inside another if statement.
It is used when a condition needs to be checked inside another condition.
Example:
age = 22
has_id = True
if age >= 18:
if has_id:
print("Eligible to enter")
else:
print("ID proof required")
else:
print("Not eligible")
Output:
Eligible to enter
Explanation:
- First, Python checks whether the age is 18 or above.
- If True, it checks whether the person has an ID.
- Since both conditions are True, the person is eligible to enter.
Ternary Operator
Python supports a one-line if-else expression, also called a conditional expression or ternary operator.
Syntax:
value_if_true if condition else value_if_false
Example:
age = 16
result = "Eligible" if age >= 18 else "Not Eligible"
print(result)
Output:
Not Eligible
Conclusion
Conditional statements are an important part of Python programming. They help programs make decisions and execute different blocks of code based on conditions.
By understanding if, if-else, if-elif-else, and nested if statements, developers can build logical and decision-making programs.
Top comments (0)