# Python Programming/Loops

This lesson introduces loops.

## Objectives and Skills

Objectives and skills for this lesson include:
* Control Flow
** The while statement
** The for loop
** The break and continue statement

## Readings

* Wikipedia: Control flow
* Python for Everyone: Iteration
* Python Basics: Iteration, Iterables, Iterators, and Looping

## Multimedia

* YouTube: Python for Informatics: Chapter 5 - Iterations
* YouTube: Python For
* YouTube: Python Range and While
* YouTube: Python Break
* YouTube: Python Continue
* YouTube: Python Nested Loops
* YouTube: Python Iteration Playlist
* Python Tutorial for Beginners 7: Loops and Iterations - For/While Loops

## Examples
### While Statement

The while loop executes as long as the condition remains true. In Python, any non-zero integer value is true and zero is false. The condition may also be a string or list value, in which case anything with a non-zero length is true and empty sequences are false. The body of the loop must be indented, and each line within a block must be indented by the same amount.

### For Statement

The for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence.

### Range Function

The range function returns an immutable sequence of numbers and is commonly used for looping a specific number of times in for loops. The syntax for the range function is range([start,] stop[, step]), with start defaulting to 0 and step defaulting to 1.

### Break Statement

The break statement breaks out of the smallest enclosing for or while loop.

### Continue Statement

The continue statement continues with the next iteration of the loop.

### Nested Loops

Loops may be nested with one loop inside another.
Output:

## Activities
### Tutorials

* Complete one or more of the following tutorials:
** LearnPython
*** Loops
** TutorialsPoint
*** Loops
** Codecademy
*** Loops
** SoloLearn
*** Control Structures
** Wikiversity
*** Python/While Statement
*** Python/For Statement
** Wikibooks
*** Wikibooks: A Beginner's Python Tutorial/Loops, Conditionals

### Practice

* Review MathsIsFun: Definition of Average. Create a Python program that asks the user to enter grade scores. Start by asking the user how many scores they would like to enter. Then use a loop to request each score and add it to a total. Finally, calculate and display the average for the entered scores. Include try and except to handle input errors. Revise the program to compare the code required when the loop control structure is based on both while and for statements.
* Create a Python program that uses a loop to generate a list of multiplication expressions for a given value. Ask the user to enter the value and the number of expressions to be displayed. Include try and except to handle input errors. For example, a list of three expressions for the value 1 would be: 1 * 1 = 1 1 * 2 = 2 1 * 3 = 3
* Review MathsIsFun: 10x Printable Multiplication Table. Create a Python program that uses nested loops to generate a multiplication table. Rather than simply creating a 10 by 10 table, ask the user to enter the starting and ending values. Include row and column labels, and include try and except to handle input errors. For example, the output might look like: 1 2 3 1 1 2 3 2 2 4 6 3 3 6 9
* Review MathsIsFun: 10x Printable Multiplication Table. Create a Python program that uses nested loops to generate a multiplication table. Rather than simply creating a 10 by 10 table, ask the user to enter the starting and ending values. Use a condition with (<variable> % 2) to test for odd or even values. Generate the multiplication table only for even values. For odd values, use the continue statement to continue the next iteration of the loop. Include row and column labels, and include try and except to handle input errors. For example, the output might look like: 2 4 6 2 4 8 12 4 8 16 24 6 12 24 36
* Review MathsIsFun: 10x Printable Multiplication Table. Create a Python program that uses nested loops to generate a multiplication table. Rather than simply creating a 10 by 10 table, ask the user to enter the starting and ending values. Use a break statement to terminate the loop if the number of rows or columns exceeds 10. Include row and column labels, and include try and except to handle input errors.

### Games

* Play CodeCombat.

## Lesson Summary
### Control Flow Concepts

* Control flow refers to the order in which the individual statements, instructions or function calls of an imperative or a declarative program are executed or evaluated.
* Control flow statement types include unconditional branch, conditional branch, conditional loop, subroutines, and unconditional halt.
* Python does not support an unconditional branch. All control flow must be structured using conditions, loops. functions, or exit (unconditional halt).
* Python uses colons and indentation to designate code blocks and control structures.
* A loop is a sequence of statements which is specified once but which may be carried out several times in succession.

### Python Loops

* Python loop structures include while and for.
* While is a condition-controlled loop, repeating until some condition changes.
* Python for loops are collection-controlled loops repeating for all elements of a sequence, which is more like foreach in other programming languages.
* Loops may be continued prematurely using the continue statement.
* Loops may be terminated prematurely using the break statement.
* Programs may be terminated prematurely using the exit function.
* The while loop executes as long as the condition remains true. In Python, any non-zero integer value is true and zero is false. The condition may also be a string or list value, in which case anything with a non-zero length is true and empty sequences are false.
* The body of the loop must be indented, and each line within a block must be indented by the same amount.
* The syntax for the while loop is:
* The for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence.
* The syntax for the for loop is:
* The range function returns an immutable sequence of numbers and is commonly used for looping a specific number of times in for loops.
* The syntax for the range function is range([start,] stop[, step]), with start defaulting to 0 and step defaulting to 1.
* The break statement breaks out of the smallest enclosing for or while loop.
* The continue statement continues with the next iteration of the loop.

## Key Terms
### accumulator

    A variable used in a loop to add up or accumulate a result.

### counter

    A variable used in a loop to count the number of times something happened. We initialize a counter to zero and then increment the counter each time we want to “count” something.

### decrement

    An update that decreases the value of a variable.

### initialize

    An assignment that gives an initial value to a variable that will be updated.

### increment

    An update that increases the value of a variable (often by one).

### infinite loop

    A loop in which the terminating condition is never satisfied or for which there is no terminating condition.

### iteration

    Repeated execution of a set of statements using either a function that calls itself or a loop.

## Review Questions

* Control flow refers to _____. Control flow refers to the order in which the individual statements, instructions or function calls of an imperative or a declarative program are executed or evaluated.
* Control flow statement types include _____, _____, _____, _____, and _____. Control flow statement types include unconditional branch, conditional branch, conditional loop, subroutines, and unconditional halt.
* Python does not support _____. All control flow must be structured using _____. Python does not support an unconditional branch. All control flow must be structured using conditions, loops. functions, or exit (unconditional halt).
* Python uses _____ to designate code blocks and control structures. Python uses colons and indentation to designate code blocks and control structures.
* A loop is _____. A loop is a sequence of statements which is specified once but which may be carried out several times in succession.
* Python loop structures include _____ and _____. Python loop structures include while and for.
* While is _____. While is a condition-controlled loop, repeating until some condition changes.
* Python for loops are _____, which is more like _____ in other programming languages. Python for loops are collection-controlled loops repeating for all elements of a sequence, which is more like foreach in other programming languages.
* Loops may be continued prematurely using the _____ statement. Loops may be continued prematurely using the continue statement.
* Loops may be terminated prematurely using the _____ statement. Loops may be terminated prematurely using the break statement.
* Programs may be terminated prematurely using the _____ function. Programs may be terminated prematurely using the exit function.
* The while loop executes as long as _____. In Python, _____ is true and _____ is false. The condition may also be _____, in which case _____ is true and _____ are false. The while loop executes as long as the condition remains true. In Python, any non-zero integer value is true and zero is false. The condition may also be a string or list value, in which case anything with a non-zero length is true and empty sequences are false.[18]
* The body of the loop must be _____. The body of the loop must be indented, and each line within a block must be indented by the same amount.
* The syntax for the while loop is: The syntax for the while loop is: while condition:  statements
* The for statement _____. The for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence.
* The syntax for the for loop is: The syntax for the for loop is: for variable in sequence:  statements
* The range function _____. The range function returns an immutable sequence of numbers and is commonly used for looping a specific number of times in for loops.
* The syntax for the range function is _____. The syntax for the range function is range([start,] stop[, step]), with start defaulting to 0 and step defaulting to 1.
* The break statement _____. The break statement breaks out of the smallest enclosing for or while loop.
* The continue statement _____. The continue statement continues with the next iteration of the loop.

## Assessments

* Flashcards: Quizlet: Python Loops
* Quiz: Quizlet: Python Loops

## See Also

* Python.org: More Control Flow Tools
* Python.org: Compound statements
* SoloLearn: Python
* Open Book Project: Python 3 - Iteration
* PythonBasics: for loops and exercises
* TutorialsPoint: Python Do While Example
* Digital Ocean: How To Use Break, Continue, and Pass Statements when Working with Loops in Python 3