If tutorials available on this website are helpful for you, please whitelist this website in your ad blocker😭 or Donate to help us ❤️ pay for the web hosting to keep the website running.
Python में exit() function का use single या nested for Loop , while Loop को terminate करने के लिए किया जाता है।
for no in range(1, 10) :
print(no)
if(no == 5) :
exit()
C:\Users\Rahulkumar\Desktop\python>python exit_for.py 1 2 3 4 5
Example अगर आप देखेंगे तो 5 के बाद print ही नहीं हुआ है because जैसे ही no की value 5 होगी loop terminate हो जायगा, और हम Loop से बाहर हो जाँयगे।
अगर आपने Python में break statement पढ़ा तो आपको याद होगा कि break भी loop को terminate करता था और exit() function भी terminate कर रहा है , तो दोनों में difference क्या हुआ -
Actually , exit() function एक positive integer value accept करता है। pass किये गए number के according हम कितने ही loop को terminate कर सकते हैं। for example exit(2) loop को एक साथ terminate करेगा और exit(5) पांच loops को।
हालाँकि by default exit() function में exit() 1 set होता है , इसलिए ऊपर दिए गए example में single loop को terminate कर दिया है।
exit() function में अगर आप 1 या 1 से कम (means 0 या negative) value pass करते हैं तो वो by default 1 ही होगा।
for no in range(1, 10) :
for no_inner in range(1, 10) :
print(no, no_inner)
if(no_inner == 5) :
exit(2)
C:\Users\Rahulkumar\Desktop\python>python exit_multi.py 1 1 1 2 1 3 1 4 1 5
ऊपर दिए गए example में आप clearly देख सकते हैं कि जैसे ही inner loop में variable की value 5 हुई बैसे दोनों loop terminate हो गए हैं।
Note : for loop में कभी भी break / exit() के साथ else use न करें , because else तभी run होता है जब for loop completely execute हो जाता है , जबकि break / exit() loop में बीच में से ही terminate कर देता हैं।
For Example
for no in range(1, 10) :
print(no)
if(no == 5) :
exit()
else :
print("it will never print")
C:\Users\Rahulkumar\Desktop\python>python exit_test.py 1 2 3 4 5
Example से आप समझ सकते हैं , कि कैसे loop बीच में ही terminate होने की वजह से else part run ही नहीं हुआ।
Hi ! My name is Rahul Kumar Rajput. I'm a back end web developer and founder of learnhindituts.com. I live in Uttar Pradesh (UP), India and I love to talk about programming as well as writing technical tutorials and tips that can help to others.
Get connected with me. :) LinkedIn Twitter Instagram Facebook