Python Loops

for-loops

  • used for iterating: going through an iterable one by one

'for-each' loop example

name = 'Ted'
for character in name:
    print(character)

will print

T
e
d
  • can also be used for loops, tuples, and dictionaries (will print the keys)
  • can use to change a mutable iterable
  • can use to move data between lists
  • 'for-each' example:
    tv = ['Got', 'Narcos', 'Vice']
    coms = ['Arrested Development', 'Friends', 'Always Sunny']
    all_shows = []
    
    for show in tv:
      show = show.upper()
      all_shows.append(show)  
    
    for show in coms:
      show = show.upper()
      all_shows.append(show)
    now all_shows is now ['GOT','NARCOS', 'VICE', 'ARRESTED DEVELOPMENT', 'FRIENDS', 'ALWAYS SUNNY']

###'for' loop example

for i in range(1,11):
print(i)

prints:

1
2
3
4
5
6
7
8
9
10
  • if starting at index 0, you only have to give it the ending index
  • second param is not inclusive

while-loops

  • executes code as long as an expression evaluates to True
  • example:
    • x = 10
      while x > 0:
          print('{}'.format(x))
          x -= 1
      print('Happy New Year!'
      prints
      10
      9
      8
      7
      6
      5
      4
      3
      2
      1
      Happy New Year!
  • a loop with an expression that is always 'True' is an infinite loop

break and continue

  • break makes a loop end immediately
    • often used in if statements so the loop will continuously from until a particular condition occurs
  • continue ends current iteration of loop and moves to the next iteration
    • example:
      for i in range(1,6):
          if i == 3:
              continue
          print(i)
      prints
      1
      2
      4
      5

Nested Loops

  • loops that are inside other loops
  • called inner and outer loops
  • want to limit the number of loops that are nested, it can easily get very complicated
  • example:
    for i in range(1, 3):
      print(i)
      for letter in ['a', 'b', 'c']
          print(letter)
    prints
    1
    a
    b
    c
    2
    a
    b
    c
  • example:
    list1 = [1, 2, 3, 4]
    list2 = [5, 6, 7, 8]
    added = []
    for i in list1:
        for j in list2:
            added.append(i + j)
    print(added)
    prints
    [6, 7, 8, 9, 7, 8, 9, 10, 8, 9, 10, 11, 9, 10, 11, 12]
  • example:
    while input('y or n?') != 'n':
      for i in range(1,6):
          print(i)
    prints
    y or n?y
    1
    2
    3
    4
    5
    y or n?y
    1
    2
    3
    4
    5
    y or n?n

Copyright © 2022