Python में exit() function का use single या nested for Loop , while Loop को terminate करने के लिए किया जाता है।

Python exit() example

Copy Fullscreen Close Fullscreen
for no in range(1, 10) :
     print(no)
     if(no == 5) :
         exit()
Output
C:\Users\Rahulkumar\Desktop\python>python exit_for.py
1
2
3
4
5

Example अगर आप देखेंगे तो 5 के बाद print ही नहीं हुआ है because जैसे ही no की value 5 होगी loop terminate हो जायगा, और हम Loop से बाहर हो जाँयगे।

Difference between exit() and break

अगर आपने 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 ही होगा।

Python Terminate Multiple Loop Example
Copy Fullscreen Close Fullscreen
for no in range(1, 10) :
     for no_inner in range(1, 10) :
         print(no, no_inner)
	 if(no_inner == 5) :
	     exit(2)
Output
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

Copy Fullscreen Close Fullscreen
for no in range(1, 10) :
    print(no)
    if(no == 5) :
        exit()
else :
    print("it will never print")
Output
C:\Users\Rahulkumar\Desktop\python>python exit_test.py
1
2
3
4
5

Example से आप समझ सकते हैं , कि कैसे loop बीच में ही terminate होने की वजह से else part run ही नहीं हुआ।

Related Topics :

Rahul Kumar

Rahul Kumar

Hi ! I'm Rahul Kumar Rajput founder of learnhindituts.com. I'm a software developer having more than 4 years of experience. I love to talk about programming as well as writing technical tutorials and blogs that can help to others. I'm here to help you navigate the coding cosmos and turn your ideas into reality, keep coding, keep learning :)

Get connected with me. :) LinkedIn Twitter Instagram Facebook

b2eprogrammers