Abstract
Loops allow a program to perform a large number of calculations with only a few lines of code. Python includes two types of loops: while loops and for loops. Both while loops and for loops cause a program’s execution to return to an earlier point and make a decision about whether or not a group of statements should be executed again.
-
A while loop executes a group of statements as long as, or while, something is true. Like an if statement, a while loop has a condition which can include both relational operators and Boolean operators.
-
A for loop executes a group of statements once for each value in a collection. A collection of integers can be constructed using Python’s range function. For loops can also be used with collections of values like lists and dictionaries which are discussed in later chapters.
This chapter ends with 22 exercises that allow the reader to practice using both while loops and for loops. In some cases the exercises tell the reader which type of loop to use. Other exercises require the user to analyze the problem carefully and make a decision about which type of loop is most suitable for solving it.
Access this chapter
Tax calculation will be finalised at checkout
Purchases are for personal use only
Author information
Authors and Affiliations
Corresponding author
Rights and permissions
Copyright information
© 2019 Springer Nature Switzerland AG
About this chapter
Cite this chapter
Stephenson, B. (2019). Repetition. In: The Python Workbook. Texts in Computer Science. Springer, Cham. https://doi.org/10.1007/978-3-030-18873-3_3
Download citation
DOI: https://doi.org/10.1007/978-3-030-18873-3_3
Published:
Publisher Name: Springer, Cham
Print ISBN: 978-3-030-18872-6
Online ISBN: 978-3-030-18873-3
eBook Packages: Computer ScienceComputer Science (R0)