Loops in Python
while loop
Use while loop, when you don't know in advance how many times you will repeat the block of code.
Make sure the condition/expression will be false eventually, otherwise loop will be in infinite loop.
Indentation is very important in Python language.
while loop syntax in Python:-
"while" expression ":" block-of-code
["else" ":" block-of-code]
while i < 6:
print (i)
i = i + 1
while x < 3 :
print (x)
x = x + 1
else:
print ('the else')
for loop
Use for loop, in Python, when you know number of times the loop should iterate.
for loop syntax in Python:-
"for" target_list "in" expression_list ":" block-of-code
["else" ":" block-of-code]
for i in range(8):
print (i)
for x in [1,7,13,2] : print (x)
for i in range(0, len(data), 2):
print (data[i])
print (ch)
for n,a in enumerate("Hello World"):
print ('alphabet', a, 'index number', n)
a = ['cat', 'window', 'defend']
for x in a:
print (x, len(x))
for key, value in comp_arr.items():
print ('%s: %s' % (key, value))
data = [ ("C20H20O3", 308.371), ("C22H20O2", 316.393),
("C24H40N4O2", 416.6), ("C14H25N5O3", 311.38), ("C15H20O2", 232.3181) ]
for (formula, mw) in data:
print ("The molecular weight of %s is %s" % (formula, mw))
for line in open('log.txt', 'r'): # loops through each line in file
print(line)
for key in dictionary.keys(): # loops through each key in Python dictionary
print(key)
for key, value in dictionary.iteritems(): print ('A %s has %d' % (key, value))
for key, value in comp_arr.items():
print ('%s: %s' % (key, value))
continue - go to next iteration
pass - nothing
for looop examples with break and continue
>>> for value in [3, 1, 4, 1, 5, 9, 2]:
print ("Checking", value)
if value > 8:
print ("Exiting for loop")
break
elif value < 3:
print ("Ignoring")
continue
print ("The square is", value**2)
for x in range(5):
print (x)
break
else :
print ('I am in else block')
async with EXPR as VAR:
BLOCK
async for TARGET in ITER:
BLOCK
else:
BLOCK2
Related Python Articles: Functions in Python Comprehensions in Python
Thanks for this explanation.
ReplyDeletePython Online Training