Iterations: ‘for’ and ‘while’loops



for loop



Python for Loop Syntax



for individual_item in iterator:
    statements…


individual item: just a variable name
iterator: something that can be iterated; like lists, tuples, dictionaries, range etc.

Examples



# loops and iteration

# 1. for loop
# for each item in some collection, do some stuff

# You list
programs_to_write = [
    "slightly better bash script",
    "web crawler",
    "port scanner",
    "web application",
    "cloud provisioning tool",
]

# Basic Form - IDENTATION is the key
for program_name in programs_to_write:
    print("I'm going to write a", program_name)  # capitalize?
    
print("\n...We're done!")
print("but it's not all clean fun -- the loop variable --", program_name, "-- still exists!")


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Range() Function



• The range() function accepts a start, stop, and optional step argument so you can get fancy with the sequences it can generate

# for loop with range() function
>>> for i in range(0,3):
        print(i)

0
1
2


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Iterating Through a Dictionary



• If you try to iterate through a dictionary, you might be surprised by the results

# Iterating through a Dictionary
>>> fruit_inventory = {"apples"5"pears"2"oranges"9}
>>> for fruit in fruit_inventory:
        print(fruit)

oranges
apples
pears


• Note that the iterator for a dictionary only iterates over the dictionary's keys

• To iterate over both the key and value, use the .items() dictionary method which returns a list of tuples

# Iterating through a dictionary using .items() method
>>> list(fruit_inventory.items())
[('oranges'9), ('apples'5), ('pears'2)]
>>> for fruit in fruit_inventory.items():
        print(fruit)

('oranges'9)
('apples'5)
('pears'2)


• To split up the Key and Value from the Tuple, use Unpacking

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Unpacking



• Assign a collection of items to a collection of variables

# Unpacking
>>> a, b, c = [123]
>>> a
1
>>> b
2
>>> c
3


# Unpacking Key and Value from Tuple
>>> for fruit, quantity in fruit_inventory.items():
        print("You have {} {}.".format(quantity, fruit))

You have 5 apples.
You have 2 pears.
You have 9 oranges.


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Nested ‘for’ loops


• Avoid nested ‘for’ loops with large collections because this will make the program runs slow

# Nested 'for' loops and range() function
grid = []

for x in range(0,3):
    for y in range(0,3):
        grid.append([x,y])
        print(x,y)


grid = []
for x in range(0,3):
    for y in range(0,3):
        grid.append([x,y])
        print(x,y)


for emotion in ["sometimes I hate""sometimes I love"]:
    for activity in ["flying""travel""eating""sleeping"]:
        print(emotion, activity)


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

While Loop



Python while Loop Syntax



# Syntax
while expression:
    statements…


expression can be any Python expression that evaluates to True or False value

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Examples



# while loop
>>> i = 0
>>> while i < 5:
        print(i)
        i += 1

0
1
2
3
4


# while loop - a traditional loop
print("Welcome to my game")

something_true = True
while (something_true):
    print("Going through the loop")
    
    # possibly make something_true = False
    something_true = False

print("we're done! something_true is now", something_true)


print("Welcome to my game")

choice = ""
while (choice != "quit"):
    choice = input("What would you like to do?\n")
    print("Going through the loop")
    print("Your choice was: ", choice)

print("we're done! choice is now", choice)

Index