Note_Tech

All technological notes.


Project maintained by simonangel-fong Hosted on GitHub Pages — Theme by mattgraham

Python - Loops

Back


while Loop


print("\n--------while loop--------\n")
i = 0
while i < 6:
    i += 1
    print(i)

# 1
# 2
# 3
# 4
# 5


print("\n--------break--------\n")
i = 0
while i < 6:
    i += 1
    if i == 3:
        break
    print(i)

# 1
# 2


print("\n--------continue--------\n")
i = 0
while i < 6:
    i += 1
    if i == 3:
        continue
    print(i)

# 1
# 2
# 4
# 5
# 6


print("\n--------else--------\n")
i = 0
while i < 6:
  i += 1
  print(i)
else:
  print("i is no longer less than 6")

# 1
# 2
# 3
# 4
# 5
# 6
# i is no longer less than 6

for Loop

print("\n--------for loop--------\n")
# loop a list
fruits = ["apple", "banana", "cherry"]
for x in fruits:
    print(x)

# apple
# banana
# cherry

# loop a string
for x in "banana":
  print(x)


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


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


# range()
for x in range(6):
  print(x)
# 0
# 1
# 2
# 3
# 4
# 5


# start with 2, end with 5
for x in range(2, 6):
  print(x)
# 2
# 3
# 4
# 5


# start with 2, end with 29, increment the sequence with 3
for x in range(2, 30, 3):
  print(x)
# 2
# 5
# 8
# 11
# 14
# 17
# 20
# 23
# 26
# 29


# else
for x in range(6):
  print(x)
else:
  print("Finally finished!")

# 0
# 1
# 2
# 3
# 4
# 5
# Finally finished!


# break + else
for x in range(6):
  if x == 3: break
  print(x)
else:
  print("Finally finished!")
# 0
# 1
# 2


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

Nested Loops

# Nested Loops
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]

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

# red apple
# red banana
# red cherry
# big apple
# big banana
# big cherry
# tasty apple
# tasty banana
# tasty cherry

zip: Loop multiple lists simultaneously


xList = [1, 2, 3]
yList = [1, 2, 4]

for (x, y) in zip(xList, yList):
    if x != y:
        print("difference:", x, y)      # difference: 3 4



Conditional Loop: for + List Comprehension

xList = [1, 5, 10, 25]

target = 9

for item in [x for x in xList if x < target]:
    print(item)
# 1
# 5


TOP