Python 2: Repetition- While Loops
By the end of this lesson you should be able to:
1. Set up a loop to repeat a block of code a set number of times.
2. Use a loop to repeat a block of code until the user enters a certain value.
Without the ability to repeat code, computers are just fancy calculators. Repetition, variables and conditions are the building blocks of all computer programs. There are essentially 2 ways repetition is achieved:
1. Loops – Which send a program back to a previous line until some condition is met.
2. Recursion- The act of a function calling itself. (More on this later)
Both have their time and place. For now we are going to focus on a specific type of loop called the “while” loop.
The while loop says “Repeat this block of code while this is true”
It is worth noting that the only code that gets repeated is the code that is tabbed under the loop.
Save each program in you unit 1 folder as a text document called A3Px where x is the program number. Then copy and paste it into the python interpreter. Use the # symbol in include your name and the program code at the top of your script.
Ex: #Tony Demello A3P1
Program 1 – Counting by 3s
Write a program displays all multiples of 3 from 0 to 100.
Program 2 – Muti-Name
Prompt the user to enter their name and the number of times they would like to see it printed on the screen. Print the user’s name that many times.
Program 3- Multiplier 2.0
Prompt the user to enter 2 numbers and report the product. Then give them the option to do it again (y) or to quit (n).
Program 4- Average 2.0
Modify your average program from assignment 2 so that uses a loop to allow the user to enter as many scores as they like. Then report the average.
Show Mr.Kurz all4 programs when you are finished.
Next up: The Number Guessing Game!