CCD Module13-PL101 01
CCD Module13-PL101 01
of examples.
References:
• Python Programming for Beginners
INFORMATION SHEET PL 101-13.1.1
Computer programs are great to use for automating and repeating tasks so that we don’t have
to. One way to repeat similar tasks is through using loops. We’ll be covering Python’s while loop in this
tutorial.
A while loop implements the repeated execution of code based on a given Boolean condition.
The code that is in a while block will execute as long as the while statement evaluates to True.
You can think of the while loop as a repeating conditional statement. After an if statement, the
program continues to execute code, but in a while loop, the program jumps back to the start of the
while statement until the condition is False.
As opposed to for loops that execute a certain number of times, while loops are conditionally
based, so you don’t need to know how many times to repeat the code going in.
Python while loop is used to run a specific code until a certain condition is met. The something
that is being done will continue to be executed until the condition that is being assessed is no longer
true.
The syntax of while loop is:
while condition:
# body of while loop
Here,
Output
1
2
3
4
5
i=1
True 1 is printed. i is increased to 2.
n=5
i=2
True 2 is printed. i is increased to 3.
n=5
i=3
True 3 is printed. i is increased to 4.
n=5
i=4
True 4 is printed. i is increased to 5.
n=5
i=5
True 5 is printed. i is increased to 6.
n=5
i=6
False The loop is terminated.
n=5
current_level = 0
final_level = 5
game_completed = True
print('Level Ends')
Output
In the above example, we have used the while loop to check the current level and display it on
the console.
If the condition of a loop is always True, the loop runs for infinite times (until the memory is
In the above example, the condition is always True. Hence, the loop body will run for infinite times.
The else part is executed after the condition in the while loop evaluates to False. For example,
counter = 0
Output
Inside loop
Inside loop
Inside loop
Inside else
Here, we have used the counter variable to print the 'Inside Loop' string three times.
On the fourth iteration, the condition in while becomes False. Hence, the else part is executed.
Note: The else block will not execute if the while loop is stopped by a break statement.
The for loop is usually used when the number of iterations is known. For example,
# this loop is iterated 4 times (0 to 3)
for i in range(4):
print(i)
And while loop is usually used when the number of iterations are unknown. For example,
while condition:
# body of loop
Let’s create a small program that executes a while loop. In this program, we’ll ask for the user to
input a password. While going through this loop, there are two possible outcomes:
We’ll create a file called password.py in our text editor of choice, and begin by initializing the
variable password as an empty string:
password.py
password = ''
The empty string will be used to take in input from the user within the while loop.
Now, we’ll construct the while statement along with its condition:
password.py
password = ''
Here, the while is followed by the variable password. We are looking to see if the
variable password is set to the string password (based on the user input later), but you can choose
whichever string you’d like.
This means that if the user inputs the string password, then the loop will stop and the program
will continue to execute any code outside of the loop. However, if the string that the user inputs is not
equal to the string password, the loop will continue.
Next, we’ll add the block of code that does something within the while loop:
password.py
password = ''
while password != 'password':
print('What is the password?')
password = input()
Inside of the while loop, the program runs a print statement that prompts for the password.
Then the variable password is set to the user’s input with the input() function.
The program will check to see if the variable password is assigned to the string password, and if
it is, the while loop will end. Let’s give the program another line of code for when that happens:
password.py
password = '' “
The last print() statement is outside of the while loop, so when the user enters password as the
password, they will see the final print statement outside of the loop.
However, if the user never enters the word password, they will never get to the
last print() statement and will be stuck in an infinite loop.
An infinite loop occurs when a program keeps executing within one loop, never leaving it. To
exit out of infinite loops on the command line, press CTRL + C.
You’ll be prompted for a password, and then may test it with various possible inputs. Here is
sample output from the program:
Output
What is the password?
hello
What is the password?
sammy
What is the password?
PASSWORD
What is the password?
password
Yes, the password is password. You may enter.
Keep in mind that strings are case sensitive unless you also use a string function to convert the
string to all lower-case (for example: The functions str.upper() and str.lower() will return a string with all
the letters of an original string converted to upper- or lower-case letters.) before checking.
Now that we understand the general premise of a while loop, let’s create a command-line
guessing game that uses a while loop effectively. To best understand how this program works, you
should also knowledge about using conditional statements and converting data types.
First, we’ll create a file called guess.py in our text editor of choice. We want the computer to
come up with random numbers for the user to guess, so we’ll import the random module with
an import statement.
guess.py
import random
Next, we’ll assign a random integer to the variable number, and keep it in the range of 1 through
25 (inclusive), in the hope that it does not make the game too difficult.
guess.py
import random
At this point, we can get into our while loop, first initializing a variable and then creating the loop.
guess.py
import random
number_of_guesses = 0
guess = input()
guess = int(guess)
number_of_guesses = number_of_guesses + 1
if guess == number:
break
We’ve initialized the variable number_of_guesses at 0, so that we increase it with each iteration
of our loop so that we don’t have an infinite loop. Then we added the while statement so that
the number_of_guesses is limited to 5 total. After the fifth guess, the user will return to the command
line, and for now, if the user enters something other than an integer, they’ll receive an error.
Within the loop, we added a print() statement to prompt the user to enter a number, which we
took in with the input() function and set to the guess variable. Then, we converted guess from a string to
an integer.
Before the loop is over, we also want to increase the number_of_guesses variable by 1 so that
we can iterate through the loop 5 times.
Finally, we write a conditional if statement to see if the guess that the user made is equivalent
to the number that the computer generated, and if so we use a break statement to come out of the
loop.
Though it works, right now the user never knows if their guess is correct and they can guess the
full 5 times without ever knowing if they got it right. Sample output of the current program looks like the
following:
Output
Guess a number between 1 and 25:
11
Guess a number between 1 and 25:
19
Guess a number between 1 and 25:
22
Guess a number between 1 and 25:
3
Guess a number between 1 and 25:
8
Let’s add some conditional statements outside of the loop so that the user is given feedback as
to whether they correctly guess the number or not. These will go at the end of our current file.
guess.py
import random
number = random.randint(1, 25)
number_of_guesses = 0
number_of_guesses = number_of_guesses + 1
if guess == number:
break
if guess == number:
print('You guessed the number in ' + str(number_of_guesses) + ' tries!')
else:
print('You did not guess the number. The number was ' + str(number))
At this point, the program will tell the user if they got the number right or wrong, which may not
happen until the end of the loop when the user is out of guesses.
To give the user a little help along the way, let’s add a few more conditional statements into
the while loop. These can tell the user whether their number was too low or too high, so that they can
be more likely to guess the correct number. We’ll add these before our if guess == number line.
guess.py
import random
number_of_guesses = 0
if guess == number:
break
if guess == number:
print('You guessed the number in ' + str(number_of_guesses) + ' tries!')
else:
print('You did not guess the number. The number was ' + str(number))
When we run the program again with python guess.py, we see that the user gets more guided
assistance in their guessing. So, if the randomly-generated number is 12 and the user guesses 18, they
will be told that their guess is too high, and they can adjust their next guess accordingly.
There is more that can be done to improve the code, including error handling for when the user
does not input an integer, but in this example we see a while loop at work in a short command-line
program.
STUDENT NAME: __________________________________ SECTION: __________________
PRECAUTIONS:
Do not just copy all your output from the internet.
Use citation and credit to the owner if necessary.
ASSESSMENT METHOD: WRITTEN WORK CRITERIA CHECKLIST
STUDENT NAME: _____________________________ SECTION: __________________
CRITERIA SCORING
Did I . . .
1 2 3 4 5
1. Focus - The single controlling point made with an awareness of a
task about a specific topic.
2. Content - The presentation of ideas developed through facts,
examples, anecdotes, details, opinions, statistics, reasons, and/or
opinions
3. Organization – The order developed and sustained within and
across paragraphs using transitional devices and including the
introduction and conclusion.
4. Style – The choice, use, and arrangement of words and sentence
structures that create tone and voice.
5. .
6. .
7. .
8. .
9. .
10. .
TEACHER’S REMARKS: QUIZ RECITATION
PROJECT
GRADE:
5 - Excellently Performed
4 - Very Satisfactorily Performed
3 - Satisfactorily Performed
2 - Fairly Performed
1 - Poorly Performed
_______________________________
TEACHER
Date: ______________________