SoFunction
Updated on 2024-11-19

Analyzing while loops and for loops in python

while loop

The while loop continues as long as the loop condition is True (x > y in the following examples):

u, v, x, y = 0, 0, 100, 30   ⇽--- ❶ 
while x > y:          ❷  
u = u + y  
x = x - y  
if x < y + 2:    
v = v + x    
x = 0  
else:    
v = v + y + 2    
x = x - y - 2 
print(u, v)

A shorthand notation is used above, where u and v are assigned the value 0, x is set to 100, and the value of y becomes 30❶. The next block is a loop ❷, which may contain a break (to exit the loop) and a continue statement (to abort the current iteration of the loop). The output will be 60 40.

for loop

The for loop can iterate over all iterable types, such as lists and tuples, making it both simple and powerful. Unlike many other languages, Python's for loop iterates over each data item in a sequence, such as a list or tuple, making it more like a foreach loop. The following loop will find the first integer divisible by seven:

item_list = [3, "string1", 23, 14.0, "string2", 49, 64, 70] 
for x in item_list:   ⇽--- ❶
  if not isinstance(x, int):    
continue   ⇽--- ❷  
if not x % 7:    
print("found an integer divisible by seven: %d" % x)    
break   ⇽--- ❸

x is assigned to each value ❶ in the list in turn. If x is not an integer, the rest of this iteration is skipped with the continue statement. The program continues to flow and x is set to the next item in the list ❷. When the first eligible integer is found, the loop is ended by the break statement ❸. Output The result will be:

found an integer divisible by seven: 49

Above is all you need to know about while and for loops, thanks for learning and supporting me.