Saturday, July 2, 2022

Python - For loops

# Prints each item, one on each line
fruits = ["apple", "banana", "cherry"]
for x in fruits:
  print(x)
 
# Prints each letter in 'banana', one on each line
for x in "banana":
  print(x)

print ("---")

 
# Break exits the loop
# Displays apple, then banana, and then breaks out of the loop
# (So it never gets to cherry)
fruits = ["apple", "banana", "cherry"]
for x in fruits:
  print(x)
  if x == "banana":
    break

print ("---")

# This does the same thing but the break is before the print statement
# So we only see "apple"
# Recall that we are breaking out of the FOR loop, not just the IF condition

fruits = ["apple", "banana", "cherry"]
for x in fruits:
  if x == "banana":
    break
  print(x)


print ("===")

# continue says stop the current iteration of the loop
# and continue with the next one
# apple
# rotten!
# cherry

fruits = ["apple", "banana", "cherry"]
for x in fruits:
  if x == "banana":
    print("rotten!")
    continue
  print(x)

# Displays 0 through 5
for x in range(6):
  print(x)


print ("===")

# Displays 2 through 5
for x in range(2, 6):
  print(x)

print ("===")

# Weird
# Start at 2
# Keep going up to right before 30
# Increment by the third argument: 3
# So it displays 2, 5, 8, 11, 14, 17, 20, 23, 26, and 29
for x in range(2, 30, 3):
  print(x)
 
print("<><><><>")

# Displays 0 through 5 and then executes the else statement
# The else keyword says run this block of code when the loop statement is finished
for x in range(6):
  print(x)
else:
  print("Finally finished!")

print("<><><><>")

# Displays 0
for x in range(1):
  print(x)
 
print("<><><><>")

# Displays 0, 1
for x in range(2):
  print(x)

print("<><><><>")

# Displays 0, done
for x in range(1):
    print(x)
else:
    print("done")
    
print("<*><*><*><*>")

# Displays done
for x in range(0):
    print(x)
else:
    print("done")

# The break statement completely exits out of the for loop
# It will not execute the else block
# Displays 0, 1, 2
print ("----")
for x in range(6):
  if x == 3: break
  print(x)
else:
  print("Finally finished!")
 
# Fun with nested loops
# Displays red apple, red banana, red cherry, big x3, tasty x3
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]

for x in adj:
  for y in fruits:
    print(x, y)

# What you have to do if no content in a for loop    

for x in [0, 1, 2]:
  pass