Jump to content

Python Programming/Loops

From Wikiversity

This lesson introduces loops.

Objectives and Skills

[edit | edit source]

Objectives and skills for this lesson include:[1]

  • Control Flow
    • The while statement
    • The for loop
    • The break and continue statement

Readings

[edit | edit source]
  1. Wikipedia: Control flow
  2. Python for Everyone: Iteration
  3. Python Basics: Iteration, Iterables, Iterators, and Looping

Multimedia

[edit | edit source]
  1. YouTube: Python for Informatics: Chapter 5 - Iterations
  2. YouTube: Python For
  3. YouTube: Python Range and While
  4. YouTube: Python Break
  5. YouTube: Python Continue
  6. YouTube: Python Nested Loops
  7. YouTube: Python Iteration Playlist
  8. Python Tutorial for Beginners 7: Loops and Iterations - For/While Loops

Examples

[edit | edit source]

While Statement

[edit | edit source]

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.[2]

i = 0
while i < 3:
    print(i)    # 0, 1, 2
    i += 1

For Statement

[edit | edit source]

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

for i in range(3):
    print(i)    # 0, 1, 2

Range Function

[edit | edit source]

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.[4]

for i in range(0, 10, 2):
    print(i)    # 0, 2, 4, 6, 8

Break Statement

[edit | edit source]

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

i = 0
while True:
    print(i)    # 0, 1, 2
    i += 1
    if i >= 3:
        break

Continue Statement

[edit | edit source]

The continue statement continues with the next iteration of the loop.[6]

for i in range(10):
    if i % 2:
        continue
    print(i)    # 0, 2, 4, 6, 8

Nested Loops

[edit | edit source]

Loops may be nested with one loop inside another.[7]

for i in range(1, 4):
    for j in range(1, 4):
        print(str(i) + str(j), end = '\t')
    print()
print()

i = 1
while i < 4:
    j = 1
    while j < 4:
        print(str(i) + str(j), end = '\t')
        j += 1
    print()
    i += 1

Output:

11      12      13
21      22      23
31      32      33

11      12      13
21      22      23
31      32      33

Activities

[edit | edit source]

Tutorials

[edit | edit source]
  1. Complete one or more of the following tutorials:

Practice

[edit | edit source]
  1. 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.
  2. 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
  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
  4. 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
  5. 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

[edit | edit source]
  1. Play CodeCombat.

Lesson Summary

[edit | edit source]

Control Flow Concepts

[edit | edit source]
  • 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.[8]
  • Control flow statement types include unconditional branch, conditional branch, conditional loop, subroutines, and unconditional halt.[9]
  • Python does not support an unconditional branch. All control flow must be structured using conditions, loops. functions, or exit (unconditional halt).[10]
  • Python uses colons and indentation to designate code blocks and control structures.[11]
  • A loop is a sequence of statements which is specified once but which may be carried out several times in succession.[12]

Python Loops

[edit | edit source]
  • Python loop structures include while and for.[13]
  • While is a condition-controlled loop, repeating until some condition changes.[14]
  • Python for loops are collection-controlled loops repeating for all elements of a sequence, which is more like foreach in other programming languages.[15]
  • Loops may be continued prematurely using the continue statement.[16]
  • Loops may be terminated prematurely using the break statement.[17]
  • Programs may be terminated prematurely using the exit() function.[18]
  • 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.[19]
  • The body of the loop must be indented, and each line within a block must be indented by the same amount.[20]
  • The syntax for the while loop is:[21]
while condition:
    statements
  • The for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence.[22]
  • The syntax for the for loop is:[23]
for variable in sequence:
    statements
  • The range function returns an immutable sequence of numbers and is commonly used for looping a specific number of times in for loops.[24]
  • The syntax for the range function is range([start,] stop[, step]), with start defaulting to 0 and step defaulting to 1.[25]
  • The break statement breaks out of the smallest enclosing for or while loop.[26]
  • The continue statement continues with the next iteration of the loop.[27]

Key Terms

[edit | edit source]
accumulator
A variable used in a loop to add up or accumulate a result.[28]
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.[29]
decrement
An update that decreases the value of a variable.[30]
initialize
An assignment that gives an initial value to a variable that will be updated.[31]
increment
An update that increases the value of a variable (often by one).[32]
infinite loop
A loop in which the terminating condition is never satisfied or for which there is no terminating condition.[33]
iteration
Repeated execution of a set of statements using either a function that calls itself or a loop.[34]

Review Questions

[edit | edit source]
Enable JavaScript to hide answers.
Click on a question to see the answer.
  1. 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.
  2. Control flow statement types include _____, _____, _____, _____, and _____.
    Control flow statement types include unconditional branch, conditional branch, conditional loop, subroutines, and unconditional halt.
  3. 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).
  4. Python uses _____ to designate code blocks and control structures.
    Python uses colons and indentation to designate code blocks and control structures.
  5. A loop is _____.
    A loop is a sequence of statements which is specified once but which may be carried out several times in succession.
  6. Python loop structures include _____ and _____.
    Python loop structures include while and for.
  7. While is _____.
    While is a condition-controlled loop, repeating until some condition changes.
  8. 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.
  9. Loops may be continued prematurely using the _____ statement.
    Loops may be continued prematurely using the continue statement.
  10. Loops may be terminated prematurely using the _____ statement.
    Loops may be terminated prematurely using the break statement.
  11. Programs may be terminated prematurely using the _____ function.
    Programs may be terminated prematurely using the exit() function.
  12. 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]
  13. 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.
  14. The syntax for the while loop is:
    The syntax for the while loop is:

    while condition:
        statements

  15. 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.
  16. The syntax for the for loop is:
    The syntax for the for loop is:

    for variable in sequence:
        statements

  17. 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.
  18. 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.
  19. The break statement _____.
    The break statement breaks out of the smallest enclosing for or while loop.
  20. The continue statement _____.
    The continue statement continues with the next iteration of the loop.

Assessments

[edit | edit source]

See Also

[edit | edit source]

References

[edit | edit source]