Loops Flashcards
While Loop
This is a loop that will keep repeating itself until the while condition becomes false.
n = 1
while n < 100:
n += 1
For Loop
For loops give you more control than while loops. You can loop through a range, a list, a dictionary, or a tuple.
all_fruits = [“apple”, “banana”, “orange”]
for fruit in all_fruits:
print(fruit)
_ in a For Loop
If the value your for Loop is iterating through, ex: the number in the range, or the item in the list is not needed, you can replace it with an underscore.
for _ in range(100):
#Do something 100 times.
break
This keyword allows you to break free if the loop. You can use it in a for or while Loop.
for s in scores:
if s > 100/:
print(“Invalid”)
break
print(s)
continue
This keyword allows you to skip this iteration of the loop and go to the next. The loop will still continue, but it will start from the top.
n = 0
while n < 100:
n += 1
if n % 2 == 0:
continue
print(n)
#Prints all the odd numbers