[go: up one dir, main page]

0% found this document useful (0 votes)
27 views15 pages

CCD Module13-PL101 01

programming language

Uploaded by

darwinteberio0
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views15 pages

CCD Module13-PL101 01

programming language

Uploaded by

darwinteberio0
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

In this lesson, we will learn about the while loop in Python programming with the help

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,

1. A while loop evaluates the condition


2. If the condition evaluates to True , the code inside the while loop is executed.
3. condition is evaluated again.
4. This process continues until the condition is False .
5. When condition evaluates to False , the loop stops.
Flowchart for Python While Loop
Example: Python while Loop

# program to display numbers from 1 to 5

# initialize the variable


i=1
n=5

# while loop from i = 1 to 5


while i <= n:
print(i)
i=i+1

Output

1
2
3
4
5

Here's how the program works:

Variable Condition: i <= n Action

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

Example 2: Python while Loop to Display Game Level

current_level = 0
final_level = 5

game_completed = True

while current_level <= final_level:


if game_completed:
print('You have passed level', current_level)
current_level += 1

print('Level Ends')

Output

You have passed level 0


You have passed level 1
You have passed level 2
You have passed level 3
You have passed level 4
You have passed level 5
Level Ends

In the above example, we have used the while loop to check the current level and display it on

the console.

Infinite while Loop in Python

If the condition of a loop is always True, the loop runs for infinite times (until the memory is

full). For example,

# infinite while loop


while True:
# body of the loop

In the above example, the condition is always True. Hence, the loop body will run for infinite times.

Python While loop with else

A while loop can have an optional else block as well.

The else part is executed after the condition in the while loop evaluates to False. For example,
counter = 0

while counter < 3:


print('Inside loop')
counter = counter + 1
else:
print('Inside else')

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.

Python for vs while loops

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

Example Program with While 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:

 If the password is correct, the while loop will exit.


 If the password is not correct, the while loop will continue to execute.

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 = ''

while password != '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 = '' “

while password != 'password':


print('What is the password?')
password = input()

print('Yes, the password is ' + password + '. You may enter.')

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.

Save the program and run it

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

number = random.randint(1, 25)

At this point, we can get into our while loop, first initializing a variable and then creating the loop.

guess.py
import random

number = random.randint(1, 25)

number_of_guesses = 0

while number_of_guesses < 5:


print('Guess a number between 1 and 25:')

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.

The program is fully functioning, and we can run it.

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

while number_of_guesses < 5:


print('Guess a number between 1 and 25:')
guess = input()
guess = int(guess)

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 = random.randint(1, 25)

number_of_guesses = 0

while number_of_guesses < 5:


print('Guess a number between 1 and 25:')
guess = input()
guess = int(guess)
number_of_guesses = number_of_guesses + 1

if guess < number:


print('Your guess is too low')

if guess > number:


print('Your guess is too high')

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: __________________

PERFORMANCE TASK PL 101-13.1.1


WRITTEN WORK TITLE:

WRITTEN TASK OBJECTIVE:


MATERIALS:
 Pen and Paper
TOOLS & EQUIPMENT:
 None
ESTIMATED COST: None
Instruction:

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: __________________

PERFORMANCE OUTPUT CRITERIA CHECKLIST PL 101-13.1.1

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: ______________________

You might also like