User Tools

Site Tools


clubs:python_club:python_club_loops
Home | clubs :: cloud club :: python_club :: 3D-Printing | projects :: Proxmox | Kubernetes | scripting | utilities | games

About the Club

Python Club Topics - Loops

Loops

  1. whiile loops
    1. Execute a set of statements for as long as a condition evaluates to true
  2. for loops
    1. Used for iterating over a sequence ( eg. list, tuple, dictionary, set, or a string )

while loop examples

  1. This condition always evaluates to True, so will continue forever
    i = 0
    while True:
      i += 1
      print("keep going... " + str(i))
  2. This condition will change to False when i updates to the value of 6
    i = 1
    while i <= 6:
      print(i)
      i += 1
  3. Adding a break key word, we can stop the loop
    i = 1
    while i <= 6:
      print(i)
      i += 1
      if i == 5:
        break
  4. Adding a continue key word, we can do something and continue the loop
    i = 1
    while i <= 6:
      print(i)
      i += 1
      if i == 5:
        print("i equals 5")
        continue
  5. Adding an else key word, we can do something else
    i = 1
    while i <= 6:
      print(i)
      i += 1
    else:
        print("i is no longer less than 6")

for loop examples

  1. Iterates over the list and prints the items, one line at a time
    fruits = ["apple", "banana", "orange"]
    for x in fruits:
      print(x)
  2. Iterates over the letters in a string and prints them, one line at a time
    for x in "banana":
      print(x)
  3. Can use the break key word
    fruits = ["apple", "banana", "orange"]
    for x in fruits:
      print(x)
      if x == "banana":
        break
  4. Can use the continue key word
    fruits = ["apple", "banana", "orange"]
    for x in fruits:
      print(x)
      if x == "banana":
        print("I love bananas!")
        continue
  5. Can use the else key word only if the loop exits normally ( without a break )
    fruits = ["apple", "banana", "orange"]
    for x in fruits:
      print(x)
      if x == "apple":
        break
    else:  
      print("I'm done!")
clubs/python_club/python_club_loops.txt · Last modified: by 127.0.0.1