Python में if Statement
In this page:
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
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
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
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
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
logged_in = True
is_admin = True
if logged_in:
if is_admin: # only checked once logged_in is True
print("Welcome, admin")
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: