Python Classroom
  • Introduction
  • About Python Classroom
  • Python Cloud Options
    • CS50 IDE
      • CS50 IDE Overview
      • CS50 IDE and Python
      • CS50 IDE Debugging
      • CS50 IDE Shortcuts
      • Linux Bash Shell
      • Vim Mode
        • Vim Tutorial
    • CS50 Sandbox
    • PythonAnywhere
    • Repl.it
  • Python Curriculum Map
    • Pedagogy
      • Python Professional Development
      • Teaching Tips
      • Assessment Tips
      • Rubrics
      • Activities
        • Picture Activity
        • Map Activity
        • Crossing the Bridge
        • NIM
        • Mastermind
        • Cards
          • Card Deck Algorithms
          • Sorting Cards
        • River Crossing
          • Jealous Boyfriends
          • Cannibals and Priests
          • Family
          • Police and the Thief
          • Humans and Monkeys
          • Moving Money
        • Crossing the River
        • Traveling Salesperson
        • Logic Problems
        • CIA Crack the Code
        • IQ Test
        • Puzzles
    • AP Computer Science Principles Framework
  • Python Philosphy
    • How to Practice Python
  • microbit
  • Turtle Graphics
    • Turtle Examples
    • Turtle Activities
    • Turtle Maze Problems
    • Turtle Graphics with loops
    • Turtle Snake
    • Turtle Graphics with Conditionals
  • Output
    • Output Examples
    • Output Mistakes
  • Variables
    • Variable Data Type Examples
    • Variable Role Examples
    • Variables Mistakes
    • Variables Problems
  • Math
    • Math Examples
    • Math Mistakes
    • Math Problems
    • Math Self Check
  • Input
    • Input Examples
    • Input Mistakes
    • Input Problems
  • Decisions
    • if
      • if Examples
      • if Mistakes
      • if Problems
    • if else
      • if else Examples
      • if else Problems
      • if / if else Problems
    • if elif else
      • if elif else Examples
      • if elif else Problems
    • nested if
      • nested if Examples
      • nested if Problems
    • Logical Operators
      • Logical Operators Examples
    • Adventure Game Project
  • Loops
    • while loop - count up
      • Examples
      • Problems
    • while loop - countdown
      • Examples
      • Problems
    • while loop - sentinel value
      • Problems
    • while loop - sentinel menu
      • Problems
    • for loop - range (one argument)
      • Examples
      • Problems
    • for loop - range (two arguments)
      • Problems
    • for loop - range (three arguments)
      • Problems
  • Lists
    • Lists - Numbers
      • Problems
    • Lists - Strings
      • Problems
      • Shopping Project
  • Dictionaries
  • String Methods
  • Functions
    • Variable Scope
    • Functions - no parameters
    • Functions - one parameter
    • Functions - return
    • Functions - lists
  • Files
  • Classes
    • Inheritance
  • Python Projects
    • Adventure Game
    • Restaurant Project
    • Trivia Game
    • Family Tree Project
  • Raspberry Pi
    • Raspberry Pi Models
    • Raspberry Pi Setup
  • Roblox
  • Glossary
Powered by GitBook
On this page
  • Introduction
  • Introductory Problem
  • while loop
  • Variable Roles
  • Common Mistakes
  • while loop Examples
  • Example 1
  • Example 2
  • Example 3
  • Example 4
  • Example 5
  • Conclusion

Was this helpful?

  1. Loops

while loop - count up

PreviousLoopsNextExamples

Last updated 5 years ago

Was this helpful?

Introduction

Introductory Problem

Ask the user, "what is your favorite programming language". If they enter Python, print, "Python is my favorite too!" 5 times.

fav = input("What is your favorite programming language? ")
if fav == "Python":
    print("Python is my favorite too!")
    print("Python is my favorite too!")
    print("Python is my favorite too!")
    print("Python is my favorite too!")
    print("Python is my favorite too!")

while loop

A while loop executes an indented block of code, or instructions, repeatedly while a condition is true. Previously, you learned about if statements that executed an indented block of code while a condition was true. You can think of a while loop like an if condition but the indented block of code executes more than once. Hence, a loop.

Variable Roles

Recall that a stepper variable iterates, or loops, a specific number of times.

Programmers usexorias a stepper variable.

Common Mistakes

Infinite Loops

An infinite loop is a loop that runs forever. It can only be stopped by killing the program. If there are output statements in the loop, these lines will flash by on the screen. To kill the program, press Ctrl+C in the Terminal. Or click on CS50 IDE -> Restart your Workspace.

Never Starts

Because the first action of a while loop is to evaluate the Boolean expression, if that expression is False, the indented block of code will never be executed.

Off by one

Another common error you may encounter is being off by one. Change the initial stepper value or the condition to correct this.

while loop Examples

Example 1

Again, ask the user, "what is your favorite programming language". This time, print "Python is my favorite too!" 5 times using a while loop.

Python programmers typically start counting at 0. This will become more clear when we introduce lists.

Steps:

  • Initialize the stepper variable x to 0.

  • Combine while with a condition that will execute 5 times.

  • Print "Python is my favorite language!"

  • Increment the stepper variable.

x = 0
while x < 5:
    print("Python is my favorite language!")
    x = x + 1

Example 2

Using a while loop, print numbers from 1 to 5.

What value can you initialize the stepper variable to?

x = 1
while x <= 5:
    print(x)
    x = x + 1

or

x = 1
while x < 6:
    print(x)
    x = x + 1

The placement of x = x + 1 in the while loop matters.

If you print x after x = x + 1, the value will be different than if you printed it before.

Example 3

Using a while loop, print odd numbers from 1 to 99.

What value can you initialize the stepper variable to? What can you increment the variable by?

x = 1
while x < 100:
    print(x)
    x = x + 2

or

x = 1
while x <= 99:
    print(x)
    x = x + 2

Example 4

Print the sum of the first 10 numbers. For example: 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10

Create a variable called sum and initialize it to 0.

  • What value can you initialize the stepper variable to?

  • How can you use x to calculate the sum?

x = 1
sum = 0
while x <= 10:
    sum = sum + x
    x = x + 1
print("Sum:", sum)

Example 5

Ask the user for a number 3 times using a while loop. Print the sum of the 3 numbers.

x = 0
sum = 0
while x < 3:
    num = int(input("Number: "))
    sum = sum + num
    x = x + 1
print("Sum:", sum)

Conclusion

  • In your own words, what is a while loop?

  • Give a simple example of something you do over and over again everyday.

  • Explain the role of the stepper variable when the while loop counts up.

  • How is using a while loop more efficient than the solution to the introductory problem?