For Loops

Overview

These repeat until a loop over a set sequence. Or until the loop is broken by a break keyword.
For loop keywords
For - this should by followed by a sequence that the loop can iterate through. This can be an expression that generates a sequences. Python is very open is the options that can be used for the sequence.
continue - This can be included in the block,when the program reaches this it will start a new loop iteration
break - This will terminate the loop
else - This term can be included at the end of a loop. this will run once the loop sequence has ended. This will not run if the loop exits via a break.

Example 1 - Basic Loop

This example code takes a string, in this case "Chair" and for each character it prints this character.
part = "Chair"
for x in part:
     print x
Returns:
C
h
a
i
r

Example 2 - Fizz Buzz Program

This is an example to a common interview question call the Fizz Buzz problem. This is outlined as return the numbers 1 to 100, but with numbers that are mulpiples of 3 replaces with "Fizz", multiples of 5 replaces with "Buzz" and if multiples of both "FizzBuzz".
for number in range(1,101):
    if number % 5 == 0  and number % 3 == 0:
        print ("FizzBuzz")
    elif number % 3 == 0:
        print ("Fizz")
    elif number % 5 == 0:
        print ("Buzz")
    else:
        print (number)
This retunrs:
1
2
Fizz
4
Buzz
Fizz
...
...
94
Buzz
Fizz
97
98
Fizz
Buzz

Example 3 - Strings, Lists, Dictionaries

Let build upon example 2 and create a simple function that takes a variable. This variable can be a string, list or keys of a dictionary. 
def loop(x):
    for i in x:
        print (i)

item = "Table"
items = ["Chair", "Table", "Cupboard"]
prices = {"Chair":30, "Table":100, "Cupboard":120}

loop(item)
loop(items)
loop(prices.keys())
This Returns:
T
a
b
l
e
Chair
Table
Cupboard
Cupboard
Chair
Table
Note that keys() has not retained order in the dictionary.




Related Sections

Python - Learn the python from the basics up. This fast track example code course will get you creating powerful python programs in no time.
Tkinter - Learn the key features of the tkinter to allow you to create user interfaces for your python programs.


Related Pages

Pickle - The pickle library allows a program to save data in a binary file.
Python - List Comprehension - Create powerful list comprehension expressions.
Python - Generators - Learn about generator statements.
Python - Data types - The learn about the key datatypes in the python language.
Tkinter - Combo Box - This is a short example showing how to use combo boxes in a GUI.
Tkinter - Radio Buttons - A short example of how to create a GUI with radio buttons.
Tkinter - Canvas - Canvas allows for a range of shapes to be plotted, such as circles, squares, lines