Python Programming/Loops
This lesson introduces loops.
Objectives and Skills
editObjectives and skills for this lesson include:[1]
- Control Flow
- The while statement
- The for loop
- The break and continue statement
Readings
editMultimedia
editExamples
editWhile Statement
editThe 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
editThe 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
editThe 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
editThe 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
editThe 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
editLoops 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
editTutorials
edit- Complete one or more of the following tutorials:
- LearnPython
- TutorialsPoint
- Codecademy
- SoloLearn
- Wikiversity
- Wikibooks
Practice
edit- 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
edit- Play CodeCombat.
Lesson Summary
editControl Flow Concepts
edit- 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- 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- 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-
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
edit- Flashcards: Quizlet: Python Loops
- Quiz: Quizlet: Python Loops
See Also
edit- 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
References
edit- ↑ Vskills: Certified Python Developer
- ↑ Python.org: An informal introduction
- ↑ Python.org: More Flow Control Tools
- ↑ Python.org: Built-in Types
- ↑ Python.org: More Flow Control Tools
- ↑ Python.org: More Flow Control Tools
- ↑ TutorialsPoint: Python nested loops
- ↑ Wikipedia: Control flow
- ↑ Wikipedia: Control flow
- ↑ Wikipedia: Control flow
- ↑ Wikipedia: Control flow
- ↑ Wikipedia: Control flow
- ↑ Wikipedia: Control flow
- ↑ Wikipedia: Control flow
- ↑ Wikipedia: Control flow
- ↑ Wikipedia: Control flow
- ↑ Wikipedia: Control flow
- ↑ Python.org: sys.exit()
- ↑ Python.org: An informal introduction
- ↑ Python.org: An informal introduction
- ↑ Python.org: An informal introduction
- ↑ Python.org: More Flow Control Tools
- ↑ Python.org: More Flow Control Tools
- ↑ Python.org: Built-in Types
- ↑ Python.org: Built-in Types
- ↑ Python.org: More Flow Control Tools
- ↑ Python.org: More Flow Control Tools
- ↑ PythonLearn: Iteration
- ↑ PythonLearn: Iteration
- ↑ PythonLearn: Iteration
- ↑ PythonLearn: Iteration
- ↑ PythonLearn: Iteration
- ↑ PythonLearn: Iteration
- ↑ PythonLearn: Iteration