After variables, data types, and operators, the next important concept is conditional statements.
Conditional statements allow a program to make decisions based on whether something is true or false.
For example:
If the temperature is high โ turn on the fan.
Otherwise โ keep it off.
This type of decision-making is used in almost every real-world application.
๐ง 1. What is a Condition?
A condition is an expression that produces a Boolean result: True or False
Example:
age = 20
age >= 18
The result is: True because 20 is greater than or equal to 18.
๐ 2. The "if" Statement
The if statement executes a block of code when a condition is true.
age = 20
if age >= 18:
print("Eligible")
Since the condition is true, the message is displayed.
๐ 3. The "if-else" Statement
Sometimes we need to handle both possibilities.
age = 16
if age >= 18:
print("Eligible")
else:
print("Not eligible")
Here, the condition is false, so the else block runs.
๐งฉ 4. The "if-elif-else" Statement
When there are multiple possible conditions, we can use elif.
marks = 75
if marks >= 90:
print("Excellent")
elif marks >= 60:
print("Good")
else:
print("Needs improvement")
Python checks the conditions from top to bottom. Once it finds a true condition, its corresponding block is executed.
๐ 5. Multiple Conditions
Logical operators can be used to combine conditions.
age = 25
has_ticket = True
if age >= 18 and has_ticket:
print("Entry allowed")
Both conditions must be true because and is being used.
โ 6. Using "not"
The not operator reverses a Boolean condition.
is_blocked = False
if not is_blocked:
print("Access allowed")
Since is_blocked is False, not is_blocked becomes True.
๐ 7. Conditional Statements in Different Languages
The concept is similar across programming languages, although the syntax changes.
Python
if age >= 18:
print("Adult")
JavaScript
if (age >= 18) {
console.log("Adult");
}Java
if (age >= 18) {
System.out.println("Adult");
}C++
if (age >= 18) {
cout << "Adult";
}The fundamental idea remains the same: evaluate a condition and decide what code should execute.
๐ฆ 8. Real-World Uses
Conditional statements are used everywhere:
โ Login authentication
โ ATM transactions
โ Online shopping
โ Age verification
โ Payment processing
โ Game logic
โ Form validation
โ Access control
โ Recommendation systems
For example, an online store might check whether Stock is available before allowing a customer to place an order.
โ ๏ธ 9. Common Beginner Mistake
Don't confuse assignment with comparison.
x = 10
means: Assign 10 to x.
While:
x == 10
means: Check whether x is equal to 10.
This difference is extremely important when writing conditions.
๐ง Conditional statements allow programs to move beyond simply executing instructions in sequence. They allow programs to make decisions.
Double Tap โค๏ธ For More