Python Notes
Learn how to use the if statement in Python to make decisions in your code. Understand conditional logic, boolean expressions, and control flow with detailed examples and Hindi explanations.
Introduction (परिचय)
Python में if statement एक conditional statement है जो program को यह decide करने की power देता है कि कौन सा code block execute करना है।
Simple भाषा में: if statement वैसे ही काम करता है जैसे हम रोज़ life में decisions लेते हैं — "अगर बारिश होगी तो छाता लेकर जाएगा।"Syntax (वाक्य रचना)
if condition:
# code block (यह तब चलेगा जब condition True हो)
statement1
statement2Important Rules (महत्वपूर्ण नियम)
ifkeyword के बाद condition लिखते हैं- condition के बाद colon (
:) जरूरी है - Code block को indent करना जरूरी है (4 spaces या 1 tab)
- Python में indentation mandatory है
Flow Diagram (प्रवाह आरेख)
Basic Examples (बुनियादी उदाहरण)
Example 1: Simple Number Check
# अगर number positive है तो print करो
number = 10
if number > 0:
print("Number is positive")
print("यह एक positive number है")Output:
Example 2: Age Check (उम्र की जाँच)
age = 18
if age >= 18:
print("You are eligible to vote")
print("आप वोट देने के योग्य हैं")Output:
Example 3: When Condition is False
age = 15
if age >= 18:
print("You can vote") # यह नहीं चलेगा
print("Program ends here") # यह हमेशा चलेगाOutput:
Note: जब condition False होती है, if block skip हो जाता है और program आगे बढ़ता है।Comparison Operators (तुलना ऑपरेटर)
Python में conditions बनाने के लिए इन operators का उपयोग होता है:
| Operator | Meaning | Example | Result |
|---|---|---|---|
== | Equal to (बराबर) | 5 == 5 | True |
!= | Not equal (बराबर नहीं) | 5 != 3 | True |
> | Greater than (बड़ा) | 7 > 3 | True |
< | Less than (छोटा) | 2 < 8 | True |
>= | Greater or equal | 5 >= 5 | True |
<= | Less or equal | 3 <= 7 | True |
Examples with Operators
x = 25
if x == 25:
print("x is exactly 25") # यह चलेगा
if x != 10:
print("x is not 10") # यह चलेगा
if x > 20:
print("x is greater than 20") # यह चलेगा
if x < 50:
print("x is less than 50") # यह चलेगा
if x >= 25:
print("x is 25 or more") # यह चलेगा
if x <= 30:
print("x is 30 or less") # यह चलेगाOutput:
Logical Operators with If (लॉजिकल ऑपरेटर)
Multiple conditions को combine करने के लिए and, or, not use करते हैं।
and Operator — दोनों conditions True होनी चाहिए
age = 20
has_id = True
if age >= 18 and has_id:
print("Entry allowed")
print("प्रवेश की अनुमति है")Output:
or Operator — कोई एक condition True होनी चाहिए
is_student = False
is_senior = True
if is_student or is_senior:
print("Discount available")
print("छूट उपलब्ध है")Output:
not Operator — condition को उल्टा कर देता है
is_raining = False
if not is_raining:
print("Go for a walk!")
print("चलने जाओ!")Output:
If with Strings (Strings के साथ If)
name = "Python"
if name == "Python":
print("Hello, Python programmer!")
language = "hindi"
if language.lower() == "hindi":
print("नमस्ते! हिंदी में स्वागत है।")Output:
If with User Input (User Input के साथ)
# User से number लेना
number = int(input("Enter a number: "))
if number % 2 == 0:
print(f"{number} is an even number")
print(f"{number} एक सम संख्या है")Output (if user enters 8):
Nested If (If के अंदर If)
marks = 85
if marks >= 33:
print("Student has passed")
if marks >= 75:
print("Student got Distinction")
print("विद्यार्थी को डिस्टिंक्शन मिला")Output:
Multiple If Statements (एकाधिक If Statements)
score = 85
if score >= 90:
print("Grade: A+")
if score >= 80:
print("Grade: A") # यह चलेगा
if score >= 70:
print("Grade: B") # यह भी चलेगा
if score >= 60:
print("Grade: C") # यह भी चलेगाOutput:
| Grade | A |
| Grade | B |
| Grade | C |
Note: Multipleifstatements में हर condition independently check होती है। इसके लिएelifbetter option है।
Truthy and Falsy Values (सत्य और असत्य मान)
Python में कुछ values automatically True या False मानी जाती हैं:
Falsy Values (जो False मानी जाती हैं)
0(zero)""(empty string)[](empty list)NoneFalse
Truthy Values (जो True मानी जाती हैं)
- कोई भी non-zero number
- कोई भी non-empty string
- Non-empty list
True
# Truthy/Falsy examples
value = 0
if value:
print("This won't print") # 0 is falsy
name = "Rahul"
if name:
print(f"Hello, {name}!") # Non-empty string is truthy
items = []
if items:
print("List has items") # Empty list is falsy
count = 5
if count:
print(f"Count is {count}") # Non-zero is truthyOutput:
One-Line If Statement (एक लाइन में If)
x = 10
# Traditional way
if x > 5:
print("x is greater than 5")
# One-line way (ternary-like)
if x > 5: print("x is greater than 5")Note: One-line if readable नहीं होता, complex code में avoid करें।
Common Mistakes (सामान्य गलतियाँ)
❌ Mistake 1: Missing Colon
# WRONG — colon missing
if x > 5
print("hello")
# CORRECT
if x > 5:
print("hello")❌ Mistake 2: Wrong Indentation
# WRONG — no indentation
if x > 5:
print("hello") # IndentationError!
# CORRECT
if x > 5:
print("hello")❌ Mistake 3: Assignment instead of Comparison
x = 5
# WRONG — this assigns, doesn't compare
if x = 10: # SyntaxError!
print("ten")
# CORRECT — use ==
if x == 10:
print("ten")❌ Mistake 4: Case Sensitivity
name = "python"
# WRONG
if name == "Python": # False! case mismatch
print("Found")
# CORRECT
if name.lower() == "python":
print("Found")❌ Mistake 5: Boolean Comparison
is_active = True
# WRONG (redundant)
if is_active == True:
print("Active")
# CORRECT (Pythonic)
if is_active:
print("Active")Practice Exercises (अभ्यास प्रश्न)
Exercise 1 — Easy
Write a program that checks if a number is positive.
Exercise 2 — Easy
Check if a person's age qualifies for a senior citizen discount (age >= 60).
Exercise 3 — Medium
Take two numbers from user and print the larger one using only if statements.
Exercise 4 — Medium
Check if a given year is a leap year (divisible by 4, but centuries divisible by 400).
Exercise 5 — Hard
Write a program that:
- Takes a student's marks (0–100)
- If marks >= 90: print "Excellent"
- If marks >= 75: print "Very Good"
- If marks >= 60: print "Good"
- If marks >= 33: print "Pass"
Solutions (हल)
Solution 1
number = int(input("Enter a number: "))
if number > 0:
print(f"{number} is a positive number")Solution 2
age = int(input("Enter your age: "))
if age >= 60:
print("Senior citizen discount applicable")
print("वरिष्ठ नागरिक छूट लागू है")Solution 3
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
if a > b:
print(f"{a} is larger")
if b > a:
print(f"{b} is larger")
if a == b:
print("Both numbers are equal")Solution 4
year = int(input("Enter year: "))
if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
print(f"{year} is a Leap Year")
print(f"{year} एक लीप वर्ष है")Solution 5
marks = int(input("Enter marks (0-100): "))
if marks >= 90:
print("Excellent — शानदार!")
if marks >= 75 and marks < 90:
print("Very Good — बहुत अच्छा!")
if marks >= 60 and marks < 75:
print("Good — अच्छा!")
if marks >= 33 and marks < 60:
print("Pass — उत्तीर्ण!")
if marks < 33:
print("Fail — अनुत्तीर्ण!")Summary (सारांश)
| Concept | Description |
|---|---|
if statement | Condition check करता है |
: (colon) | if के बाद जरूरी है |
| Indentation | 4 spaces mandatory |
| Comparison operators | ==, !=, >, <, >=, <= |
| Logical operators | and, or, not |
| Truthy/Falsy | Non-zero = True, 0/empty = False |
Key Takeaway: if statement Python की नींव है। इसे अच्छे से समझना बाकी सब concepts के लिए जरूरी है।Next Topic (अगला विषय)
➡️ If-Else Statement — जब condition False हो तो क्या करें?
✅ Key Takeaways
- 🎯
ifstatement Python का सबसे basic decision-making tool है — यह condition check करके code execute करता है - 📝
ifkeyword के बाद condition लिखो, फिर colon (:) लगाओ — colon भूलना सबसे common mistake है - 📐 Indentation (4 spaces) Python में mandatory है — बिना indentation code error देगा
- 🔄 जब condition
Trueहोती है तो if block execute होता है,Falseहो तो skip हो जाता है - ⚖️ Comparison operators (
==,!=,>,<,>=,<=) conditions बनाने के काम आते हैं - 🔗
and,or,notlogical operators से multiple conditions combine कर सकते हैं - 💡 Python में Truthy/Falsy concept important है —
0,"",[],None= False; बाकी सब = True - ⚠️ Assignment (
=) और Comparison (==) में confuse मत होओ — condition में हमेशा==use करो - 🐍 Pythonic way:
if is_active:लिखो,if is_active == True:नहीं - 📚 Multiple independent
ifstatements सब separately check होते हैं — mutual exclusion के लिएelifuse करो
❓ FAQ
Q1: if और if-else में क्या difference है?
Answer: if statement सिर्फ तब काम करता है जब condition True हो। अगर condition False हो तो कुछ नहीं होता — program simply आगे बढ़ जाता है। if-else में False case handle करने के लिए else block होता है।
# Only if — False case handle नहीं होता
if age >= 18:
print("Adult")
# if-else — दोनों cases handle होते हैं
if age >= 18:
print("Adult")
else:
print("Minor")Q2: क्या if condition में parentheses () लगाना जरूरी है?
Answer: नहीं! Python में if condition के साथ parentheses optional हैं। लेकिन complex conditions में readability के लिए use कर सकते हो।
# Both are correct ✅
if x > 5:
print("yes")
if (x > 5):
print("yes")
# Complex condition — parentheses help readability
if (age >= 18 and has_id) or is_vip:
print("Entry allowed")Q3: if block में कितनी lines लिख सकते हैं?
Answer: कोई limit नहीं है! जितनी lines चाहो लिख सकते हो — बस सब lines same indentation level पर होनी चाहिए (4 spaces)।
if score >= 90:
print("Excellent!")
print("You topped the class!")
print("शानदार प्रदर्शन!")
bonus = 500
print(f"Bonus: {bonus}")Q4: क्या if के अंदर if लिख सकते हैं (Nested If)?
Answer: हाँ, बिल्कुल! इसे Nested If कहते हैं। हर inner if को extra 4 spaces indent करना होता है। लेकिन ज्यादा nesting से code complex हो जाता है, इसलिए 2-3 levels से ज्यादा avoid करें।
if marks >= 33:
print("Passed")
if marks >= 75:
print("Distinction")
if marks >= 90:
print("Topper!") # 3 levels deep — try to avoid thisQ5: == और is में क्या difference है?
Answer: == value comparison करता है (दोनों values same हैं?), जबकि is identity check करता है (दोनों same object हैं memory में?)। Beginners को == use करना चाहिए।
Q6: if 0: या if "": लिखने पर क्या होगा?
Answer: 0 और "" (empty string) Python में Falsy values हैं, इसलिए इनके if blocks कभी execute नहीं होंगे।
if 0:
print("This will NEVER print") # 0 is Falsy
if "":
print("This will NEVER print") # Empty string is Falsy
if "Hello":
print("This WILL print") # Non-empty string is TruthyThis WILL print
Q7: क्या if statement में function call कर सकते हैं?
Answer: हाँ! Condition में कोई भी expression या function call रख सकते हो जो True/False return करे।
Name is: Python List has more than 3 items
Q8: Python में if statement और Ternary Operator में क्या difference है?
Answer: Ternary operator एक single line expression है जो value return करता है, जबकि if statement एक block execute करता है।
age = 20
# Ternary operator — value assign करने के लिए
status = "Adult" if age >= 18 else "Minor"
print(status) # Adult
# Regular if — code block execute करने के लिए
if age >= 18:
print("You can vote")
print("You can drive")Adult You can vote You can drive
🎯 Interview Questions
1. What is an if statement in Python? Explain with an example.
Answer: if statement एक conditional statement है जो एक condition evaluate करता है। अगर condition True है तो if block का code execute होता है, otherwise skip हो जाता है।
temperature = 40
if temperature > 35:
print("It's very hot today!")
print("Stay hydrated!")It's very hot today! Stay hydrated!
Key Points:
ifkeyword से शुरू होता है- Condition के बाद colon (
:) mandatory है - Body indented होनी चाहिए (4 spaces)
- Condition True हो तभी body execute होती है
2. What happens when the condition in an if statement is False?
Answer: जब condition False होती है, Python simply if block को skip कर देता है और program अगली line (जो if block से बाहर है) से continue करता है।
x = 3
if x > 10:
print("This won't execute") # Skipped!
print("This also won't") # Skipped!
print("Program continues here") # Always executesProgram continues here
Program crash नहीं होता, error नहीं आती — बस if block skip हो जाता है।
3. What is the difference between = and == in Python?
Answer:
| Operator | Purpose | Example |
|---|---|---|
= | Assignment — value assign करना | x = 5 (x में 5 store करो) |
== | Comparison — equality check | x == 5 (क्या x बराबर है 5 के?) |
x = 10 # Assignment: x में 10 store हुआ
if x == 10: # Comparison: क्या x equal है 10 को?
print("x is 10") # ✅ Truex is 10
Interview Tip: if x = 10: लिखना Python में SyntaxError देगा। Condition में हमेशा == use करो।
4. What are Truthy and Falsy values in Python?
Answer: Python में हर value को boolean context में evaluate किया जा सकता है:
Falsy values (False मानी जाती हैं):
0,0.0— zero numbers""— empty string[],(),{}— empty collectionsNone— null valueFalse— boolean False
Truthy values (True मानी जाती हैं):
- Non-zero numbers (
1,-5,3.14) - Non-empty strings (
"hello"," ") - Non-empty collections (
[1,2],(1,),{"a":1}) True
Will print
5. Can we use multiple conditions in a single if statement? How?
Answer: हाँ! Python के logical operators — and, or, not — से multiple conditions combine कर सकते हैं।
age = 25
income = 50000
has_good_credit = True
# and — सभी conditions True होनी चाहिए
if age >= 21 and income >= 30000 and has_good_credit:
print("Loan approved!")
# or — कोई एक True हो तो काफी है
if age >= 60 or income < 20000:
print("Eligible for subsidy")
# not — condition उल्टी कर देता है
if not has_good_credit:
print("Loan rejected")Loan approved!
6. What is the significance of indentation in Python's if statement?
Answer: Python में indentation block structure define करती है। दूसरी languages (C, Java) curly braces {} use करती हैं, लेकिन Python indentation पर depend करता है।
# Correct ✅ — 4 spaces indentation
if True:
print("Inside if")
print("Still inside if")
print("Outside if")
# Wrong ❌ — IndentationError
if True:
print("Error!") # No indentation = Error!Key Points:
- Standard: 4 spaces per level
- Tab और spaces mix मत करो
- Same block की सब lines same indentation होनी चाहिए
- Indentation गलत हो तो
IndentationErrorआता है
7. What is the difference between multiple if statements and if-elif?
Answer:
Multiple if: हर condition independently check होती है — एक से ज्यादा blocks execute हो सकते हैं।
if-elif: पहली True condition मिलते ही बाकी skip हो जाती हैं — maximum एक block execute होता है।
score = 85
# Multiple if — सब check होंगे
if score >= 80:
print("A") # ✅ Prints
if score >= 70:
print("B") # ✅ Prints (independent check)
if score >= 60:
print("C") # ✅ Prints (independent check)
# if-elif — पहला match मिलने पर रुक जाएगा
if score >= 80:
print("A") # ✅ Prints — stops here
elif score >= 70:
print("B") # ❌ Skipped
elif score >= 60:
print("C") # ❌ Skipped8. How does Python evaluate compound conditions with and and or?
Answer: Python short-circuit evaluation use करता है:
and: पहलाFalseमिलते ही resultFalse— आगे check नहीं करताor: पहलाTrueमिलते ही resultTrue— आगे check नहीं करता
# Short-circuit with 'and'
x = 0
if x != 0 and 10/x > 2: # x != 0 is False, so 10/x never executes
print("Safe!") # No ZeroDivisionError!
# Short-circuit with 'or'
name = "Rahul"
if name or get_default_name(): # name is Truthy, function not called
print(f"Hello, {name}")Hello, Rahul
Interview Tip: Short-circuit evaluation performance optimize करता है और errors prevent करता है (जैसे division by zero)।
9. What is a Nested If statement? When should you use it?
Answer: Nested If मतलब एक if block के अंदर दूसरा if statement। इसका use तब करें जब एक condition True होने के बाद ही दूसरी condition check करनी हो।
has_ticket = True
age = 15
if has_ticket:
print("Ticket verified ✅")
if age >= 18:
print("Adult section — full price")
if age < 18:
print("Children section — half price")Ticket verified ✅ Children section — half price
When to use:
- जब conditions hierarchical हों (outer True हो तभी inner check करो)
- Login → then check role → then check permissions
When to avoid:
- 3+ levels deep nesting — code complex हो जाता है
- Use
andoperator or early return instead
10. Write a program to check if a number is positive, negative, or zero using only if statements.
Answer:
number = int(input("Enter a number: "))
if number > 0:
print(f"{number} is Positive ➕")
print(f"{number} एक धनात्मक संख्या है")
if number < 0:
print(f"{number} is Negative ➖")
print(f"{number} एक ऋणात्मक संख्या है")
if number == 0:
print("Number is Zero 0️⃣")
print("संख्या शून्य है")Enter a number: -7 -7 is Negative ➖ -7 एक ऋणात्मक संख्या है
Note: यह approach काम करता है, लेकिन if-elif-else ज्यादा efficient है क्योंकि unnecessary checks avoid होते हैं।
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for If 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, statement
Related Python Master Course Topics