While:
1. General Format
while test: # Loop test
statements # Loop body
else: # Optional else
statements # Run if didn't exit loop with break
2. break, continue, pass, and the Loop else
break
Jumps out of the closest enclosing loop (past the entire loop statement)
continue
Jumps to the top of the closest enclosing loop (to the loop’s header line)
pass
Does nothing at all: it’s an empty statement placeholder
Loop else block
Runs if and only if the loop is exited normally (i.e., without hitting a break)
When combined with the loop else clause, the break statement can often eliminate the need for the search status flags used in other languages
The loop else clause is also run if the body of the loop is never executed, as you don’t run a break in that event either; in a while loop, this happens if the test in the header is false to begin with.
x = y // 2 # For some y > 1
while x > 1:
if y % x == 0: # Remainder
print(y, 'has factor', x)
break # Skip else
x -= 1
else: # Normal exit
print(y, 'is prime')
instead, you can use flag
found = False
while x and not found:
if match(x[0]): # Value at front?
print('Ni')
found = True
else:
x = x[1:] # Slice off front and repeat
if not found:
print('not found')
is equivalent to
while x: # Exit when x empty
if match(x[0]):
print('Ni')
break # Exit, go around else
x = x[1:]
else:
print('Not found') # Only here if exhausted x
3. General Loop Format
while test:
statements
if test: break # Exit loop now, skip else if present
if test: continue # Go to top of loop now, to test1
else:
statements # Run if we didn't hit a 'break'
for
a generic iterator in Python : it can step through the items in any ordered sequence or other iterable object.
When Python runs a for loop, it assigns the items in the iterable object to the target one by one and executes the loop body for each. The loop body typically uses the assignment target to refer to the current item in the sequence as though it were a cursor stepping through the sequence.
for target in object: # Assign object items to target
statements
if test: break # Exit loop now, skip else
if test: continue # Go to top of loop now
else:
statements # If we didn't hit a 'break'
The for Loop is simpler to code and often quicker to run than while
The built-in range function (available since Python 0.X) produces a series of successively higher integers, which can be used as indexes in a for.
The built-in zip function (available since Python 2.0) returns a series of parallelitem tuples, which can be used to traverse multiple sequences in a for.
The built-in enumerate function (available since Python 2.3) generates both the values and indexes of items in an iterable, so we don’t need to count manually.
The built-in map function (available since Python 1.0) can have a similar effect to zip in Python 2.X, though this role is removed in 3.X.