वैसे तो सभी loops का काम same ही है But different loops का काम करने का तरीका change हो जाता है जैसे कि अब तक हमने while loop के बारे में जाना while loop में block of statement को execute करने का तरीका अलग है कहें तो while loop में एक जगह हम condition लगाते हैं और दूसरी जगह value change वाली condition लगाते हैं। but for loop में ऐसा नहीं है for loop में loop की सारी conditions एक ही line में लग जाती हैं। for loop का ज्यादातर use sequence के elements को iterate करने के लिये किया जाता है। जैसे string, list, tuple, etc. for loop में range() function का use किया जाता है।
Syntax: for variable_name in sequence Body of for loop
Example: for i in range(1,5): print(i) Output: 1 2 3 4
for Iterating list sequence
Example: a = [1, 2, 3, 4, 5, 6] for n in a : print(n) Output: 1 2 3 4 5 6
for Iterating tuple sequence
Example: tuple = (1, 2, 3, 4, 5, 6) for a in tuple: print(a) Output: 1 2 3 4 5 6
for Iterating dictionary sequence
Example: dict = {1:2, 3:4, 5:6, 7:8, 9:10, 11:12, 13:14, 15:16 } for a in dict: print(a, dict[a]) Output: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
for Iterating string sequence
Example: str = "Hello" for a in str: print(a) Output: H e l l o
else with for Loop
for Loop के साथ else का use ये है जब condition true होती है तब for loop का statement execute होता है और condition false होती है तब control pass होके else पर जाकर else वाले statement को execute करता है।
Example: name = ['Navin', 'Khushi', 'Krishna'] for i in name : print(i) else: print("Outside of for Loop") Output: Navin Khushi Krishna Outside of for Loop
for loop को पढ़ने के बाद अन्य प्रकार के looping statements नीचे दिये हुये हैं।
इन्हें भी देखें।
- if statement
- if-else statement
- if-elif statement
- nested if statement
- range() function
- keywords
- Identifiers (names)
- Literals
- Operators
- punctuatorts
Python Programs के लिये यहाँ click करें।