while else python
# While Loops
# Basic syntax:
while condition_to_check:
something you want to do as long as condition_to_check is true
something else you want to do as long as condition_to_check is true
# Note, make sure that the condition_to_check will return false at some
# point, otherwise you'll be stuck in an infinite loop
# Note, for more complicated conditions_to_check, you may need to use
# parentheses to clarify the argument. E.g.:
# while (i < 10 and (j >= 5 or k == "some_text")):
# Note, the stuff you do during each iteration is indicated by indenting
# it (tab or 4 spaces) - you don't need to surround it in braces { }
# Note, use break to exit the loop entirely if some condition is true and
# use continue to skip to the next iteration if some condition is true
# Example usage:
i = 0
while i < 3: # Continues as long as i less than 3 = TRUE
print(i)
i += 1 # += is shorthand for: i = i + 1
--> 0 # Python is 0-indexed, so zero is printed first
--> 1
--> 2
# Example usage 2:
i = 0
while i < 3:
print(i)
i += 1
else:
print("Something to do once, immediately after the loop terminates")
--> 0
--> 1
--> 2
--> Something to do once, immediately after the loop terminates
# Example usage 3:
i = 0
while i < 6:
if i == 2:
i += 1
continue # If i = 2, continue skips to the next iteration of the loop
if i == 4:
break # If i = 4, break exits the loop entirely
print(i)
i += 1
--> 0
--> 1
--> 3
target = 100
current = 0
while current != target:
current += 1
print(current)
#The while loop repeats the indented code while its condition is true
#(current IS NOT equal to target).
else:
print("Target Reached!")
#When the while loop condition is no longer true (current IS equal to target),
#the indented code under else: is ran.