← Back to Python Course | Chapter 3: Control Flow | Lesson 1 of 10

Python में if Statement

if statement एक नियम की तरह है जो कहता है 'यह तभी करो जब कुछ सच हो', जैसे ठंड होने पर ही कोट पहनना। अगर condition false है, तो Python उस हिस्से को skip कर देता है।
Syntax
python
if condition:
    # code runs when condition is True
    statement

बेसिक If Statement

if statement अपना indented block तभी चलाता है जब उसकी condition True का मूल्यांकन करती है; अगर condition False है, तो Python पूरे block को बिना execute किए सीधे skip कर देता है और आगे जो भी अगला statement है उस पर चला जाता है।

उदाहरण: Basic If Statement

python
age = 20
if age >= 18:  # condition must be True for the block to run
    print("You can vote")

Indentation का महत्व

Python यह पहचानता है कि कौन-सी lines if block में शामिल हैं सिर्फ़ indentation के आधार पर -- पारंपरिक रूप से 4 spaces -- braces के बजाय। जो line if से कम indent की गई है उसे block से बाहर समझा जाता है, भले ही कोई closing keyword न हो।

उदाहरण: The Importance of Indentation

python
age = 20
if age >= 18:
    print("Inside the if block")  # indented, so it's part of the if block
print("Outside the if block")  # not indented, runs regardless of the condition

Conditions में Relational Operators

== (equal to) और != (not equal to) जैसे comparison operators ज़्यादातर conditions की बुनियाद होते हैं, हर एक True या False value produce करता है जिस पर if statement फिर काम करता है।

उदाहरण: Relational Operators in Conditions

python
status = "active"
if status == "active":  # == compares for equality
    print("Account is active")

Truthiness जाँचना

Python non-empty containers और non-zero numbers को truthy मानता है और खाली वाले ("", [], 0) को falsy, इसलिए आप if len(my_list) > 0: जैसे लंबे तरीके के बजाय सीधे if my_list: लिखकर जाँच सकते हैं कि list में कुछ है या नहीं।

उदाहरण: Checking Truthiness

python
my_list = [1, 2]
if my_list:  # non-empty list is truthy
    print("List has items")

Nested If Blocks

एक if को दूसरे के अंदर रखने से आप पहली condition पास होने के बाद ही दूसरी condition जाँच सकते हैं -- उदाहरण के लिए, admin है या नहीं यह जाँचने से पहले user logged in है यह जाँचना -- इस तरह logic को कदम-दर-कदम narrow किया जाता है।

उदाहरण: Nested If Blocks

python
logged_in = True
is_admin = True
if logged_in:
    if is_admin:  # only checked once logged_in is True
        print("Welcome, admin")
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.