while loop - countdown
Last updated
Last updated
Ask the user what food they would like to eat everyday. Using a while loop, print their favorite food 5 times.
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.
Recall that a stepper variable iterates, or loops, a specific number of times.
Programmers usex
ori
as a stepper variable.
Rewrite the Do Now to print the user’s favorite food 5 times by decrementing the variable rather than incrementing.
Steps:
Initialize the stepper variable x to 5.
Ask the user what they like to eat everyday.
Using a while loop, create a condition that will execute 5 times.
Print variable.
Decrement the stepper variable.
Using a while loop, print even numbers from 10 to 1.
What value can we initialize the stepper variable to?
Using a while loop, ask the user for a number 3 times. Where in the program should we ask the user for the number? Inside the loop, or outside the loop?
Create a temporary variable named squared that squares the number. Create another temporary variable named cubed that cubes the number.
Print the values of squared and cubed.
You eat a Pepperoni Pizza slice which is 400 calories and now want to burn off these calories for 10 minutes. You burn 11 calories per minute running. Create a chart to represent how many minutes you have left to exercise and how many calories you have left to burn off.
Steps:
Create a variable named calories and initialize it to 400.
Before the while loop, add the following lines to create your chart.
print("Mins\tCalories")
"\t" means tab.
In your own words, what is a while loop? What is a real life example when you count down?
Explain the role of the stepper variable when the while loop counts down.