Python Notes
Master the if-else statement in Python to handle both True and False conditions. Learn two-way decision making with real-world examples, Hindi explanations, and practice problems.
Introduction (परिचय)
if-else statement Python में two-way decision making के लिए use होता है।
सरल भाषा में: -if— अगर condition सच है तो यह करो -else— नहीं तो (otherwise) यह करो
Real-Life Example:
Flow Diagram (प्रवाह आरेख)
Basic Examples (बुनियादी उदाहरण)
Example 1: Positive or Negative
number = -5
if number >= 0:
print("Number is Positive or Zero")
print("संख्या सकारात्मक या शून्य है")
else:
print("Number is Negative")
print("संख्या नकारात्मक है")Output:
Example 2: Even or Odd (सम या विषम)
num = 7
if num % 2 == 0:
print(f"{num} is Even (सम)")
else:
print(f"{num} is Odd (विषम)")Output:
Example 3: Pass or Fail (उत्तीर्ण या अनुत्तीर्ण)
marks = 45
if marks >= 33:
print("Result: PASS ✓")
print("परिणाम: उत्तीर्ण ✓")
else:
print("Result: FAIL ✗")
print("परिणाम: अनुत्तीर्ण ✗")Output:
Example 4: Voting Eligibility (मतदान योग्यता)
age = int(input("Enter your age: "))
if age >= 18:
print("You are eligible to vote ✓")
print("आप मतदान के योग्य हैं ✓")
else:
print("You are NOT eligible to vote ✗")
years_left = 18 - age
print(f"आपको {years_left} साल और इंतजार करना होगा")Output (if age = 16):
Practical Programs (व्यावहारिक कार्यक्रम)
Program 1: Temperature Check (तापमान जाँच)
temp = float(input("Enter temperature in Celsius: "))
if temp > 37.5:
print("You have FEVER!")
print("आपको बुखार है! डॉक्टर के पास जाएं।")
else:
print("Temperature is Normal ✓")
print("तापमान सामान्य है ✓")Output (temp = 38.2):
Program 2: Number Guessing (अनुमान लगाना)
secret = 42
guess = int(input("Guess the number (1-100): "))
if guess == secret:
print("🎉 Correct! You guessed it right!")
print("शाबाश! आपने सही अनुमान लगाया!")
else:
print(f"Wrong! The correct number was {secret}")
print(f"गलत! सही संख्या {secret} थी")Output (guess = 25):
Program 3: Discount Calculator (छूट कैलकुलेटर)
purchase = float(input("Enter purchase amount (₹): "))
if purchase >= 1000:
discount = purchase * 0.10
final = purchase - discount
print(f"10% Discount Applied: ₹{discount:.2f}")
print(f"Final Amount: ₹{final:.2f}")
else:
print(f"No discount. Pay full: ₹{purchase:.2f}")
print(f"₹1000 से अधिक खरीदें और 10% छूट पाएं!")Output (purchase = 1500):
Output (purchase = 800):
Program 4: Divisibility Check (विभाज्यता जाँच)
n = int(input("Enter a number: "))
d = int(input("Enter divisor: "))
if d != 0 and n % d == 0:
print(f"{n} is divisible by {d}")
print(f"{n} को {d} से विभाजित किया जा सकता है")
else:
if d == 0:
print("Error: Division by zero!")
print("त्रुटि: शून्य से विभाजन नहीं होता!")
else:
print(f"{n} is NOT divisible by {d}")
print(f"{n} को {d} से विभाजित नहीं किया जा सकता")Program 5: Login System (लॉगिन सिस्टम)
correct_username = "admin"
correct_password = "python123"
username = input("Username: ")
password = input("Password: ")
if username == correct_username and password == correct_password:
print("✓ Login Successful!")
print("✓ लॉगिन सफल! आपका स्वागत है।")
else:
print("✗ Login Failed!")
print("✗ लॉगिन विफल! गलत username या password।")Ternary Operator — Short If-Else (संक्षिप्त if-else)
Python में एक line में if-else लिखने का तरीका:
Syntax
value = expression_if_true if condition else expression_if_falseExamples
# Traditional
age = 20
if age >= 18:
status = "Adult"
else:
status = "Minor"
# Ternary (one line)
status = "Adult" if age >= 18 else "Minor"
print(status) # Adult# Even/Odd using ternary
n = 15
result = "Even" if n % 2 == 0 else "Odd"
print(f"{n} is {result}") # 15 is Odd# Maximum of two numbers
a, b = 45, 72
maximum = a if a > b else b
print(f"Maximum = {maximum}") # Maximum = 72If-Else with Multiple Conditions (एकाधिक शर्तों के साथ)
# Checking temperature range
temp = 28
if temp >= 35:
print("It's very hot! Stay hydrated.")
print("बहुत गर्मी है! पानी पीते रहें।")
else:
print("Temperature is comfortable.")
print("तापमान आरामदायक है।")# Using logical operators
income = 50000
has_loan = True
if income >= 30000 and not has_loan:
print("Loan approved ✓")
else:
print("Loan not approved ✗")
print("ऋण स्वीकृत नहीं है")Comparing Strings (Strings की तुलना)
# String comparison
password = input("Enter password: ")
if password == "secure123":
print("Access granted!")
else:
print("Access denied!")
# Case-insensitive comparison
city = input("Enter city name: ")
if city.lower() == "delhi":
print("Welcome to the capital!")
print("राजधानी में आपका स्वागत है!")
else:
print(f"You are in {city}")Nested If-Else (if-else के अंदर if-else)
num = int(input("Enter a number: "))
if num > 0:
if num % 2 == 0:
print(f"{num} is Positive and Even")
else:
print(f"{num} is Positive and Odd")
else:
if num == 0:
print("Number is Zero")
else:
print(f"{num} is Negative")Flow:
num > 0?
/ \
Yes No
/ \
num%2==0? num==0?
/ \ / \
Yes No Yes No
| | | |
Even Odd Zero NegativeReal-World Application: ATM Machine Simulation
balance = 5000
print("=== ATM Machine ===")
print("=== एटीएम मशीन ===")
amount = int(input("Enter withdrawal amount: "))
if amount <= 0:
print("Invalid amount! Please enter positive value.")
elif amount > balance:
print(f"Insufficient funds!")
print(f"अपर्याप्त राशि! आपके खाते में ₹{balance} हैं।")
else:
balance -= amount
print(f"₹{amount} dispensed successfully!")
print(f"Remaining balance: ₹{balance}")
print(f"शेष राशि: ₹{balance}")Common Mistakes (सामान्य गलतियाँ)
❌ Mistake 1: else without if
# WRONG
else:
print("hello") # SyntaxError!
# CORRECT
x = 5
if x > 0:
print("positive")
else:
print("not positive")❌ Mistake 2: Condition after else
# WRONG — else never has a condition
if x > 5:
print("big")
else x <= 5: # SyntaxError!
print("small")
# CORRECT
if x > 5:
print("big")
else:
print("small or equal")❌ Mistake 3: Missing else block content
# WRONG — empty else without pass
if x > 0:
print("positive")
else:
# IndentationError!
# CORRECT — use pass if nothing to do
if x > 0:
print("positive")
else:
pass # do nothing❌ Mistake 4: Wrong logic
n = 0
# WRONG — 0 will print "positive"
if n >= 0:
print("positive")
else:
print("negative")
# CORRECT
if n > 0:
print("positive")
else:
print("zero or negative")Practice Exercises (अभ्यास प्रश्न)
Exercise 1 — Marks Grade
Input marks, print "Pass" if marks >= 33, else "Fail".
Exercise 2 — Max of Two Numbers
Take 2 numbers from user, print the larger one.
Exercise 3 — Triangle Check
Take 3 sides. Check if they can form a triangle. *(Hint: Sum of any two sides > third side)*
Exercise 4 — Profit or Loss
Take cost price and selling price, print profit or loss amount.
Exercise 5 — Leap Year
Check if a given year is a leap year or not.
Exercise 6 — Password Strength
Check if password length >= 8, has uppercase and digit.
Solutions (हल)
Solution 1
marks = int(input("Enter marks: "))
if marks >= 33:
print("PASS ✓")
else:
print("FAIL ✗")Solution 2
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
if a > b:
print(f"Larger number: {a}")
else:
print(f"Larger number: {b}")Solution 3
a = float(input("Side 1: "))
b = float(input("Side 2: "))
c = float(input("Side 3: "))
if a + b > c and b + c > a and a + c > b:
print("Valid Triangle ✓")
print("यह एक वैध त्रिभुज है ✓")
else:
print("Not a Triangle ✗")
print("यह त्रिभुज नहीं बन सकता ✗")Solution 4
cp = float(input("Cost Price: ₹"))
sp = float(input("Selling Price: ₹"))
if sp > cp:
profit = sp - cp
print(f"Profit: ₹{profit:.2f}")
print(f"लाभ: ₹{profit:.2f}")
else:
loss = cp - sp
print(f"Loss: ₹{loss:.2f}")
print(f"हानि: ₹{loss:.2f}")Solution 5
year = int(input("Enter year: "))
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print(f"{year} is a Leap Year 📅")
else:
print(f"{year} is NOT a Leap Year")Summary (सारांश)
| Feature | Description |
|---|---|
if block | True होने पर execute होता है |
else block | False होने पर execute होता है |
| Ternary | val = a if cond else b |
| Nested | if-else के अंदर if-else |
else after if | हमेशा pair में आते हैं |
Next Topic (अगला विषय)
➡️ Elif Statement — Multiple conditions handle करने के लिए
✅ Key Takeaways (मुख्य बातें)
- 📌
if-elsestatement two-way decision making provide करता है — condition True हो या False, दोनों cases handle होते हैं - 📌
elseblock तब execute होता है जबifकी condition False हो — यह "otherwise" का काम करता है - 📌
elseकभी अकेला नहीं आ सकता — हमेशाifके साथ pair में use होता है - 📌
elseके बाद कोई condition नहीं लिखी जाती — बस colon (:) लगता है - 📌 Indentation बहुत जरूरी है —
ifऔरelseदोनों blocks properly indent होने चाहिए (4 spaces) - 📌 Ternary operator (
value = a if condition else b) से एक line में if-else लिख सकते हैं — short और readable - 📌 Nested if-else में एक if-else के अंदर दूसरा if-else लिख सकते हैं — complex decisions के लिए useful
- 📌
if-elseमें logical operators (and,or,not) use करके multiple conditions combine कर सकते हैं - 📌 String comparison में case-sensitivity ध्यान रखें —
.lower()या.upper()use करें safe comparison के लिए - 📌
elseblock empty नहीं छोड़ सकते — अगर कुछ नहीं करना तोpasskeyword use करें
❓ FAQ (अक्सर पूछे जाने वाले प्रश्न)
Q1: if-else और सिर्फ if में क्या अंतर है?
Answer: सिर्फ if statement में अगर condition False हो तो कुछ नहीं होता — program आगे बढ़ जाता है। लेकिन if-else में False case भी handle होता है — else block execute होता है।
# सिर्फ if — False पर कुछ नहीं होता
x = 3
if x > 5:
print("Big")
# कोई output नहीं अगर x <= 5
# if-else — दोनों cases handle
if x > 5:
print("Big")
else:
print("Small or equal")Small or equal
Q2: क्या else के बाद condition लिख सकते हैं?
Answer: ❌ नहीं! else के बाद condition नहीं लिखी जाती। अगर आपको और conditions check करनी हैं तो elif use करें। else हमेशा "बाकी सब cases" को handle करता है।
# WRONG ❌
# else x < 5: → SyntaxError!
# CORRECT ✅
if x > 5:
print("big")
else:
print("not big") # सभी remaining casesQ3: Ternary operator कब use करना चाहिए?
Answer: जब simple one-line decision हो — जैसे variable assignment। Complex logic या multiple statements के लिए regular if-else ही बेहतर है readability के लिए।
# ✅ Good use of ternary
status = "Pass" if marks >= 33 else "Fail"
# ❌ Avoid — too complex for ternary
# result = "A" if m > 90 else "B" if m > 75 else "C" if m > 60 else "F"Q4: Nested if-else कितने levels तक use कर सकते हैं?
Answer: Technically कोई limit नहीं है, लेकिन 2-3 levels से ज्यादा nesting code को unreadable बना देती है। ज्यादा levels होने पर elif या functions use करें।
Q5: if-else में = और == का अंतर क्या है?
Answer: = assignment operator है (value assign करता है), जबकि == comparison operator है (दो values compare करता है)। if condition में हमेशा == use करें!
x = 10 # assignment — x में 10 store हो रहा है
if x == 10: # comparison — x 10 के बराबर है?
print("Yes!")Yes!
Q6: क्या else block optional है?
Answer: हाँ! else block optional है। अगर आपको सिर्फ True case handle करना है तो सिर्फ if काफी है। else तभी लिखें जब False case में भी कुछ करना हो।
Q7: if-else में pass keyword क्यों use करते हैं?
Answer: Python में empty block allowed नहीं है। अगर आप अभी else block में कुछ नहीं लिखना चाहते (placeholder), तो pass use करें — यह "do nothing" का काम करता है।
if condition:
do_something()
else:
pass # बाद में logic add करेंगेQ8: if True: और if False: क्या करते हैं?
Answer: if True: हमेशा True होता है — if block हमेशा execute होगा। if False: हमेशा False होता है — else block execute होगा। Testing/debugging में useful है।
if True:
print("Always runs!")
else:
print("Never runs!")Always runs!
🎯 Interview Questions (इंटरव्यू प्रश्न)
Q1: What is the difference between if and if-else statement?
Answer: if statement सिर्फ True condition handle करता है — अगर condition False हो तो कुछ नहीं होता। if-else statement दोनों cases (True और False) handle करता है। if-else को two-way branching भी कहते हैं क्योंकि program दो paths में से एक जरूर follow करता है।
Q2: Can we have multiple else blocks for a single if?
Answer: ❌ नहीं! एक if के साथ सिर्फ एक ही else block हो सकता है। अगर multiple conditions check करनी हैं तो elif (else if) use करें। else हमेशा last में आता है as a catch-all/default case।
Q3: Explain the ternary operator in Python with an example.
Answer: Python का ternary operator एक single-line conditional expression है। Syntax: value = expr_if_true if condition else expr_if_false। यह regular if-else का shorthand है और primarily simple assignments या return statements में use होता है।
age = 20
category = "Adult" if age >= 18 else "Minor"
print(category) # Output: AdultAdult
Q4: What happens if we write else without if?
Answer: Python SyntaxError throw करेगा। else standalone exist नहीं कर सकता — यह हमेशा if, for, while, या try statement के साथ associated होना चाहिए।
Q5: What is short-circuit evaluation in if-else conditions?
Answer: Python में and/or operators short-circuit evaluation follow करते हैं। and में पहली condition False होने पर दूसरी check नहीं होती। or में पहली True होने पर दूसरी skip हो जाती है। इससे performance improve होती है और errors avoid होती हैं।
x = 0
# Short-circuit — दूसरी condition check नहीं होगी
if x != 0 and 10/x > 2:
print("Yes")
else:
print("Safe from ZeroDivisionError!")Safe from ZeroDivisionError!
Q6: What is the difference between nested if-else and elif?
Answer: Nested if-else में एक if-else के अंदर दूसरा if-else होता है (hierarchical decisions)। elif एक ही level पर multiple conditions check करता है (sequential decisions)। Nested if-else readability कम करता है; जहाँ possible हो elif prefer करें।
Q7: Can we use if-else inside a function's return statement?
Answer: हाँ! Ternary operator use करके return statement में directly if-else लिख सकते हैं। यह code concise बनाता है।
def check_sign(n):
return "Positive" if n > 0 else "Zero or Negative"
print(check_sign(5))
print(check_sign(-3))Positive Zero or Negative
Q8: What is truthy and falsy in Python's if-else context?
Answer: Python में कुछ values automatically False मानी जाती हैं (falsy): 0, 0.0, "" (empty string), [] (empty list), None, False। बाकी सब truthy होती हैं। if-else में direct value check कर सकते हैं बिना explicit comparison के।
Name is empty! List has items
Q9: How does Python handle indentation errors in if-else?
Answer: Python IndentationError raise करता है अगर if/else blocks properly indent न हों। Python में indentation syntax का part है (C/Java जैसे {} braces नहीं हैं)। Standard practice 4 spaces use करना है। Mixed tabs और spaces से भी errors आती हैं।
Q10: What is the time complexity of if-else statement?
Answer: if-else statement की time complexity O(1) (constant time) होती है — यह simple condition check है। लेकिन अगर condition में कोई function call या loop हो तो उसकी complexity अलग होगी। Statement itself constant time में evaluate होता है।
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for If-Else Statement in Python.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Python Master Course topic.
Search Terms
python-master-course, python master course, python, master, course, control, flow, else
Related Python Master Course Topics