To execute a block of code over and over again, you can use while
statement. while
statement executes the code in loop as long as the given condition is true.
counter = 1
while counter < 10:
print(counter)
counter += 1
# while loop executes as long as counter is less than 10
Break, Continue Statements
break
statement exits the loop immediately. continue
statement only skips the current loop and continues with the next loop. To get detailed information you can read Python Break, Continue, Pass Statements.
counter = 0
while counter <= 10:
counter += 1
if counter % 2 == 1:
continue
print(counter)
# prints 2, 4, 6, 8, 10
# continue statement skips the loop
# for odd numbers
counter = 0
while counter <= 10:
counter += 1
if counter == 5:
break
print(counter)
# prints 1, 2, 3, 4
# and exits the loop when counter == 5
Else Statement in While Loops
else
block is executed at the end of while loop unless break statement is run during while
loop.
while i < 5:
if colors[i] == "Green":
print("Green is in the list.")
break
i += 1
else:
print("Green is not found in the list.")