Skip to ContentGo to accessibility pageKeyboard shortcuts menu
OpenStax Logo

Learning objectives

By the end of this section you should be able to

  • Explain the loop construct in Python.
  • Use a while loop to implement repeating tasks.

While loop

A while loop is a code construct that runs a set of statements, known as the loop body, while a given condition, known as the loop expression, is true. At each iteration, once the loop statement is executed, the loop expression is evaluated again.

  • If true, the loop body will execute at least one more time (also called looping or iterating one more time).
  • If false, the loop's execution will terminate and the next statement after the loop body will execute.

Checkpoint

While loop

Concepts in Practice

While loop example

Fibonacci is a series of numbers in which each number is the sum of the two preceding numbers. The Fibonacci sequence starts with two ones: 1, 1, 2, 3, . . . . Consider the following code that prints all Fibonacci numbers less than 20, and answer the following questions.

    # Initializing the first two Fibonacci numbers
    f = 1
    g = 1
    print (f, end = ' ')

    # Running the loop while the last Fibonacci number is less than 20
    while g < 20:
      print(g, end = ' ')
      # Calculating the next Fibonacci number and updating the last two sequence numbers
      temp = f
      f = g
      g = temp + g
    
1.
How many times does the loop execute?
  1. 5
  2. 6
  3. 7
2.
What is the variable g's value when the while loop condition evaluates to False?
  1. 13
  2. 20
  3. 21
3.
What are the printed values in the output?
  1. 1 1 2 3 5 8 13
  2. 1 2 3 5 8 13
  3. 1 1 2 3 5 8 13 21

Counting with a while loop

A while loop can be used to count up or down. A counter variable can be used in the loop expression to determine the number of iterations executed. Ex: A programmer may want to print all even numbers between 1 and 20. The task can be done by using a counter initialized with 1. In each iteration, the counter's value is increased by one, and a condition can check whether the counter's value is an even number or not. The change in the counter's value in each iteration is called the step size. The step size can be any positive or negative value. If the step size is a positive number, the counter counts in ascending order, and if the step size is a negative number, the counter counts in descending order.

Example 5.1

A program printing all odd numbers between 1 and 10

    # Initialization
    counter = 1

    # While loop condition
    while counter <= 10:
      if counter % 2 == 1:
        print(counter)
      # Counting up and increasing counter's value by 1 in each iteration
      counter += 1
    

Checkpoint

Counting with while loop

Concepts in Practice

while loop counting examples

Given the code, answer the following questions.

    n = 4
    while n > 0:
      print(n)
      n = n - 1
    
    print("value of n after the loop is", n)
    
4.
How many times does the loop execute?
  1. 3
  2. 4
  3. 5
5.
Which line is printed as the last line of output?
  1. value of n after the loop is -1.
  2. value of n after the loop is 0.
  3. value of n after the loop is 1.
6.
What happens if the code is changed as follows?
n = 4
while n > 0:
  print(n)
  # Modified line
  n = n + 1

print("value of n after the loop is", n)
  1. The code will not run.
  2. The code will run for one additional iteration.
  3. The code will never terminate.

Try It

Reading inputs in a while loop

Write a program that takes user inputs in a while loop until the user enters "begin". Test the code with the given input values to check that the loop does not terminate until the input is "begin". Once the input "begin" is received, print "The while loop condition has been met.".

Enter different input words to see when the while loop condition is met.

Try It

Sum of odd numbers

Write a program that reads two integer values, n1 and n2. Use a while loop to calculate the sum of odd numbers between n1 and n2 (inclusive of n1 and n2). Remember, a number is odd if number % 2 != 0.

Citation/Attribution

This book may not be used in the training of large language models or otherwise be ingested into large language models or generative AI offerings without OpenStax's permission.

Want to cite, share, or modify this book? This book uses the Creative Commons Attribution License and you must attribute OpenStax.

Attribution information
  • If you are redistributing all or part of this book in a print format, then you must include on every physical page the following attribution:
    Access for free at https://openstax.org/books/introduction-python-programming/pages/1-introduction
  • If you are redistributing all or part of this book in a digital format, then you must include on every digital page view the following attribution:
    Access for free at https://openstax.org/books/introduction-python-programming/pages/1-introduction
Citation information

© Mar 15, 2024 OpenStax. Textbook content produced by OpenStax is licensed under a Creative Commons Attribution License . The OpenStax name, OpenStax logo, OpenStax book covers, OpenStax CNX name, and OpenStax CNX logo are not subject to the Creative Commons license and may not be reproduced without the prior and express written consent of Rice University.

This book utilizes the OpenStax Python Code Runner. The code runner is developed by Wiley and is All Rights Reserved.