Python If Else Statement
🐍 Python If Statement
The if statement is used to control the flow of a program based on conditions.
1. Basic If Statement
✅ Output:
Note: Indentation is important in Python (usually 4 spaces).
2. If…Else Statement
When you want to execute one block if True, and another if False:
3. If…Elif…Else Statement
Use elif for multiple conditions:
4. Nested If Statements
You can put if statements inside other if statements:
5. Logical Operators in Conditions
You can combine conditions using:
| Operator | Meaning |
|---|---|
and | Both conditions must be True |
or | At least one must be True |
not | Reverse the result |
Example:
6. Python Ternary Operator (Single Line If)
7. Membership Check with If
8. Boolean Condition Directly
Since Python treats True/False directly:
9. Comparison Operators Used in If
| Operator | Meaning |
|---|---|
== | Equal to |
!= | Not equal |
> | Greater than |
< | Less than |
>= | Greater or equal |
<= | Less or equal |
Example:
10. Example Program: Age & Eligibility
🧠 Summary
if→ executes code if condition is Trueelse→ executes code if condition is Falseelif→ checks multiple conditionsLogical operators (
and,or,not) help combine conditionsTernary operator → shortcut for simple if-else
Practice Exercises
Write a program to check if a number is positive, negative, or zero.
Check if a student passes with marks >= 40, otherwise fail.
Check if a year is a leap year.
Check if a person is eligible to drive based on age >= 18.
Use ternary operator to print “Even” or “Odd” for a number.
