while loop - count up
Introduction
Introductory Problem
Ask the user, "what is your favorite programming language". If they enter Python, print, "Python is my favorite too!" 5 times.
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.

Common Mistakes
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.
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.
Example 2
Using a while loop, print numbers from 1 to 5.
or
Example 3
Using a while loop, print odd numbers from 1 to 99.
or
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?

Example 5
Ask the user for a number 3 times using a while loop. Print the sum of the 3 numbers.
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?
Last updated
Was this helpful?