Loops

While Loop

While Loop General Syntax

while condition:
    statement(s)

While Loop Example

i = 0
while i < 5:
    print("Hello")
    i += 1
Hello
Hello
Hello
Hello
Hello

For Loop

General Syntax

for item in sequence:
    statement(s)

Example

sequence = ["The", "Quick", "Brown", "Fox"]
for item in sequence:
    print(item)
The
Quick
Brown
Fox

Break statement

payment_per_year = 10000
interest_rate = 0.05
current_year = 0
balance = 0
while (current_year <= 100):
    balance += payment_per_year
    interest = balance * interest_rate / 100
    balance += interest
    if (balance >= goal):
        break
    current_year += 1
while (sum < goal):
    input_number_as_string = input("Enter a number: ")
    input_number_as_integer = int(input_number_as_string)
    if (input_number_as_integer < 0):
        pass
    sum += n # not executed if n < 0

Nested Loops

for i in range(3):
    print(i)
    for j in range(5):
        print(j)