While Loops

  1. 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 when idx is a viable index into groceries.

    For <2>, the code should increment the value of idx.

  1. Write code to ask the user to type the letter y and keep asking the user to enter the letter y until they do.
    You have to ask the user to enter a letter again inside the while loop.
  1. 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 the while loop.

  1. 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.

  1. 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 the while loop: you want the while loop to continue as long as idx is legal – i.e., until is the index of the last element in groceries.
  1. Convert the following code to use a while loop:

    for item in groceries:
        print(item)
    
    You will have to use index-based looping, incrementing idx inside the while loop.