While Loops¶
-
Assume a list
groceries
has been defined. Replace<1>
and<2>
in the code below so that the code prints out each item in the list.For
<1>
, you must provide a condition that will be true whenidx
is a viable index intogroceries
.For
<2>
, the code should increment the value ofidx
.
-
Write code to ask the user to type the letter
y
and keep asking the user to enter the lettery
until they do.You have to ask the user to enter a letter again inside thewhile
loop.
-
Write code to ask the user for an integer or to enter the number 0 to quit.
When the user enters an integer, print out the number squared. E.g.,
Enter an integer, or 0 to quit: 12 12 squared is 144 Enter an integer, or 0 to quit: 0 Thanks for playing.
Note
In this environment, you won’t see output from your print statement until the program ends.
Figure out what your condition for the while loop will be. I.e., when do you want to asking the user for another number.
You will have to repeat your
input()
call inside thewhile
loop.
-
Write a short program that asks the user to enter a positive number, and then repeatedly doubles that number until the result is more than 1 million. The program then prints out how many times the number was doubled. E.g., :: Enter a positive number: 2 Your number was doubled 19 times before the result was greater than 1000000
What is the condition that will stop the while loop?
You need to create a variable, say,
numTimesDoubled
, that you will increment each time in the while loop.
-
Convert the following index-based for loop to use a while loop:
for idx in range(len(groceries)): print(groceries[idx])
Figure out the condition for thewhile
loop: you want thewhile
loop to continue as long asidx
is legal – i.e., until is the index of the last element ingroceries
.
-
Convert the following code to use a while loop:
for item in groceries: print(item)
You will have to use index-based looping, incrementingidx
inside the while loop.