The assert Statement :-
assert Python का एक Statement (कथन) है। इसका उपयोग किसी condition को check (जाँच) करने के लिए किया जाता है।
अगर condition True होती है, तो program सामान्य रूप से आगे चलता है।
अगर condition False होती है, तो Python AssertionError देता है।
English
The assert statement is used to check whether a condition is true or false.
- If the condition is True, the program continues normally.
- If the condition is False, Python raises an AssertionError.
Syntax:-
assert condition
या
assert condition, "Error Message"
Example:-
age = 20
assert age >= 18
print("You are eligible")
Output:-
You are eligible
Because:-
यहाँ condition है:
age >= 18
age की value 20 है।
इसलिए:
20 >= 18 → True
Condition True होने के कारण assert कोई error नहीं देता और program आगे चलता है।
English
The condition age >= 18 is True because the value of age is 20. Therefore, the program continues normally.
Example of False Condition:-
age = 15
assert age >= 18
print("You are eligible")
Output:-
AssertionError
Because:-
यहाँ:
15 >= 18 → False
Condition False है, इसलिए Python AssertionError देता है।
print("You are eligible") execute नहीं होगा।
English
Here, 15 >= 18 is False. Therefore, Python raises an AssertionError and the print() statement is not executed.
assert with Error Message :-
हम assert के साथ अपना error message भी दे सकते हैं।
Syntax:-
assert condition, "Error Message"
Example:-
age = 15
assert age >= 18, "Age must be 18 or above"
print("You are eligible")
Output:-
AssertionError: Age must be 18 or above
Explanation:-
जब condition False होती है, तो दिए गए error message के साथ AssertionError दिखाई देता है।
English
When the condition is False, Python displays AssertionError along with the specified error message.
Another Example:-
marks = 75
assert marks >= 33
print("Student Passed")
Output:-
Student Passed
क्योंकि:
75 >= 33 → True
इसलिए program आगे execute होगा।
False Example:-
marks = 25
assert marks >= 33, "Student has failed"
print("Student Passed")
Output:-
AssertionError: Student has failed
क्योंकि:
25 >= 33 → False
इसलिए AssertionError आएगा।
Use of assert Statement :-
assert का उपयोग मुख्य रूप से:
1. Condition Check करने के लिए
हिंदी: Check करता है कि x zero से बड़ा है या नहीं।
2. Debugging के लिए
English:
assert is commonly used during development to find problems in a program.
हिंदी:
Program बनाते समय errors या गलत conditions को पहचानने के लिए assert का उपयोग किया जाता है।
3. Program Assumptions Check करने के लिए
age = 20
assert age >= 18
यह check करता है कि program की expected condition सही है या नहीं।