The for and while Loops
A loop repeats the same action many times. We study the for and while loops in Python, the range() function, leaving a loop early and avoiding endless loops.
All topics (4 of 11)
Chapter 1. Python Basics
Chapter 2. Lists and Strings
Chapter 3. Functions and Modules
Chapter 4. Working with Files
When the same action has to be done many times, a loop is used. Python has two kinds of loops: for is convenient when the number of repetitions is known in advance, and while when you need to repeat as long as a condition stays true. The loop body is written with an indent (4 spaces), just like in the conditional statement.
The for loop usually works with the range() function. If the first line is for i in range(5): and the second line, indented by 4 spaces, is print(i), then i takes the values 0, 1, 2, 3, 4 one after another, and these numbers appear on the screen. range(1, 6) gives the numbers from 1 to 5 (the last number is not included), and range(0, 10, 2) gives 0, 2, 4, 6, 8.
The while loop checks the condition each time and, if it is true, runs the body. For example, with n = 3, the loop while n > 0: with the commands print(n) and n = n - 1 inside prints 3, 2, 1 and stops when n becomes zero. If n is not changed inside the loop, the condition always stays true and the loop runs forever.
Calculating a sum is a classic example of a loop: starting with total = 0, the loop for i in range(1, 6): runs total = total + i inside it (indented by 4 spaces), and in the end total equals 15. To leave a loop early, use break, and to skip the current pass, use continue. If the number of repetitions is known, it is more convenient to choose for; if it is unknown, choose while.
Key takeaways
- A loop repeats a group of commands several times.
foris used when the number of repetitions is known, andwhileas long as a condition is true.range(5)gives the numbers 0, 1, 2, 3, 4 (5 is not included).- If nothing inside
whileaffects the condition, the loop becomes endless. breakstops the loop, andcontinuemoves on to the next pass.
Practice tasks
- Use
forandrange()to print the numbers from 1 to 10, then change the program so that it prints only the even numbers (2, 4, 6, 8, 10). - Use a
whileloop to count down from 10 to 1 and print “Liftoff!” at the end. - Write a program that asks the user to enter 5 numbers and calculates their sum (use a
forloop andint(input())).
Review questions
Test yourself: think first, then reveal the answer.
1Which numbers does range(1, 6) give?Show answerHide answer
The numbers 1, 2, 3, 4, 5 (6 is not included).2When is a for loop more convenient, and when a while loop?Show answerHide answer
A for loop when the number of repetitions is known in advance; a while loop when repeating depends on a condition.3Why can a while loop become endless?Show answerHide answer
If nothing inside the loop affects the condition, it always stays true.
0 of 11 topics completed
Sign in to mark