0% found this document useful (0 votes)
2 views25 pages

Python Lesson 2a Notes - Updated 1

The document provides a comprehensive guide on looping in Python, focusing primarily on the while loop and its applications. It includes examples, explanations of syntax, and practical exercises such as a Guess Number game and summation of numbers. Key concepts like variable initialization, loop conditions, and the use of break and continue statements are also discussed to enhance understanding of loop control flow.

Uploaded by

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

Python Lesson 2a Notes - Updated 1

The document provides a comprehensive guide on looping in Python, focusing primarily on the while loop and its applications. It includes examples, explanations of syntax, and practical exercises such as a Guess Number game and summation of numbers. Key concepts like variable initialization, loop conditions, and the use of break and continue statements are also discussed to enhance understanding of loop control flow.

Uploaded by

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

P.

1 of 25

Contents

Looping in Python .......................................................................................................... 2


while loop............................................................................................................... 2
When shall we use looping? .......................................................................... 2
Elaboration of whileHello.py.................................................................. 4
Execution of while loop.................................................................. 5
Classwork 1 .................................................................................................... 5
More example of while loop – Summation from 1 to 10............................... 7
Elaboration of whileSum.py ................................................................... 8
How the Loop Works ...................................................................... 9
Premature Termination of while loop .......................................................... 11
The Guess Number Game - Extra while loop example ........................ 12
Elaboration of whileGuess.py ...................................................... 15
Classwork 2 .................................................................................................. 18
Classwork 3 .................................................................................................. 19
Usage of break and continue statement ...................................................... 20
Elaboration of whileGuessCountContinue.py ...................................... 22
P. 2 of 25

Looping in Python
Python provides 2 different kinds of loops:
1. while loop
2. for loop

At the beginning, we will go through the logic of while loop and next comes the for
loop.

while loop
Generally speaking, while loop repeats a statement or group of statements when a
given condition stays TRUE. It tests the condition before executing the loop body.

The basic syntax of a while loop in Python should be:

while conditional statement:


statement(s) to be executed when the conditioanl statement stays TRUE

When shall we use looping?


Let's consider a situation by the time you would like to print Hello, World ! for 6
times. Refer to the figure below for reference:
P. 3 of 25

The following program, repeatHello.py, can accomplish the mission.

print("Hello World !")


print("Hello World !")
print("Hello World !")
print("Hello World !")
print("Hello World !")
print("Hello World !")

But how about we would like to print Hello World ! for 10 times or more? In this
circumstance, we can write the same program with file name whileHello.py by using
while loop.

# Initialize the variable


theCounter = 1

while theCounter <= 6:


print("Hello World !")

# Update the variable by increase of 1 each time


theCounter += 1 # theCounter = theCounter + 1

ch = input("")
P. 4 of 25

Elaboration of whileHello.py

The above code demonstrates how to use a while loop to repeat a task (printing
"Hello World!") a certain number of times. Let’s break it down step by step:

1. Initializing the Variable


theCounter = 1

➢ A variable named theCounter is initialized with the value 1.


➢ This variable will be used to control the loop and determine how many times
the loop should execute.

2. Setting Up the while Loop


while theCounter <= 6:

➢ The while loop will continue to execute as long as the condition theCounter
<= 6 is True.
➢ In this case, the loop will run as long as theCounter is less than or equal to 6.

3. Printing "Hello World!"


print("Hello World!")

➢ Inside the loop, the program prints the string "Hello World!" to the console
each time the loop runs.

4. Updating the Counter Variable


theCounter += 1 # theCounter = theCounter + 1

➢ After printing, the value of theCounter is incremented by 1 using the


shorthand += 1.
➢ This ensures that the value of theCounter increases with each iteration of the
loop.
➢ Eventually, when theCounter becomes greater than 6, the loop condition
(theCounter <= 6) will evaluate to False, and the loop will stop.
P. 5 of 25

Execution of while loop


Here’s what happens during each iteration of the loop:

Condition Updated
Iteration Initial theCounter Action
(theCounter <= 6) theCounter
1 1 True Print "Hello World!" 2
2 2 True Print "Hello World!" 3
3 3 True Print "Hello World!" 4
4 4 True Print "Hello World!" 5
5 5 True Print "Hello World!" 6
6 6 True Print "Hello World!" 7
7 7 False Loop Ends -

Key Points:
1. Initialization:
➢ The variable theCounter is initialized before the loop starts.

2. Condition:
➢ The while loop checks the condition (theCounter <= 6) at the beginning of
each iteration. If the condition is False, the loop stops.

3. Update:
➢ The variable theCounter is updated inside the loop to ensure the loop
eventually terminates.

4. Controlled Repetition:
➢ The loop ensures that "Hello World!" is printed exactly 6 times because the
loop starts with theCounter = 1 and stops when theCounter > 6.

Classwork 1
Try to modify program whileHello.py as whileHelloCounter.py which can produce
the following output:
P. 6 of 25
P. 7 of 25

More example of while loop – Summation from 1 to 10


The following Python program calculates the sum of the numbers from 1 to 10. That
is 0+1+2+3+4+ …10

Take a look at the code for reference:

whileSum.py

x=10 #x is the maximum boundary


sum=0 #initialize sum to 0
counter=1

while counter<=x:
sum=sum+counter
counter+=1 #counter=counter+1

print("The sum of 1 to %d is %d" %(x,sum))

ch = input('')

The output of the above program should be:


P. 8 of 25

Elaboration of whileSum.py

The above Python code calculates the sum of integers from 1 to 10 using a while
loop. Let’s break it down step by step.

1. Variable Initialization
x = 10 # x is the maximum boundary
sum = 0 # initialize sum to 0
counter = 1

➢ x is set to 10, meaning the program will calculate the sum of integers from 1
to 10.
➢ sum is initialized to 0 and will be used to store the cumulative sum of
numbers during the loop.
➢ counter is initialized to 1 and will be the variable we use to iterate from 1 to x.

2. The while Loop


while counter <= x:
sum = sum + counter
counter += 1 # counter = counter + 1

➢ The while loop runs as long as the condition counter <= x is True.
➢ Inside the loop:
✓ The current value of counter is added to sum:

sum = sum + counter

This accumulates the sum of all integers from 1 to x.


➢ The counter is incremented by 1 using the shorthand counter += 1. This
ensures that the loop progresses to the next number.
P. 9 of 25

3. Printing the Result


print("The sum of 1 to %d is %d" %(x, sum))

➢ This line prints the result of the summation in a formatted string.


➢ The %d format specifier is used to insert integers into the string:
✓ %d is replaced with the value of x (in this case, 10).
✓ %d is replaced with the value of sum (the total sum calculated by the
loop).

Final Output:
The sum of 1 to 10 is 55

How the Loop Works


Let’s go through the loop step by step for x = 10:

counter (before counter (after


Iteration sum = sum + counter
addition) increment)
1 1 0+1=1 2
2 2 1+2=3 3
3 3 3+3=6 4
4 4 6 + 4 = 10 5
5 5 10 + 5 = 15 6
6 6 15 + 6 = 21 7
7 7 21 + 7 = 28 8
8 8 28 + 8 = 36 9
9 9 36 + 9 = 45 10
10 10 45 + 10 = 55 11

➢ After the 10th iteration, counter becomes 11, so the condition counter <= x
evaluates to False, and the loop ends.
P. 10 of 25

Key Points:

1. Initialization:
➢ The variables sum and counter are initialized before the loop starts.

2. Condition:
➢ The while loop ensures that the code inside runs repeatedly until
counter > x.

3. Updating Variables:
➢ The counter is incremented in each loop iteration (counter += 1),
ensuring the loop progresses and eventually terminates.

4. Summation Calculation:
➢ The cumulative sum is calculated by adding the current value of
counter to sum during each iteration.

5. Output:
➢ The result is printed using formatted strings with placeholders (%d).
P. 11 of 25

Premature Termination of while loop


So far, a while loop only ends, if the condition in the loop head is fulfilled. With the
help of a break statement a while loop can be left prematurely, i.e. as soon as the
control flow of the program comes to a break inside of a while loop (or other loops)
the loop will be immediately left. "break" shouldn't be confused with the continue
statement. "continue" stops the current iteration of the loop and starts the next
iteration by checking the condition again.
P. 12 of 25

The Guess Number Game - Extra while loop example

This behaviour can be elaborated in the following example – a simple Guess Number
game.

Game rule:
A player has to guess a number between 1 and 100. The player inputs his guess. Then,
the program will inform the player, if this number is larger, smaller or equal to the
secret number, i.e. the number which the program has randomly created.

If the player wants to give up, he or she can input 0.

Hint:
The program needs to create a random number. Therefore it's necessary to include
the module "random" by statement import random

Here is the output for your reference:

Screen 1
P. 13 of 25

Screen 2
P. 14 of 25

Try to study the code of whileGuess.py now.

import random

# randint() is a built-in function of Python


# It can generate random intger with the range
# specified in the 2 arguments
# In this case, it can generate an Integer betwen 1 and 100
randomNumber = random.randint(1, 100)

#Dubug Trace
#For testing only. May comment out later
#print("The generated random number is %d\n" %(randomNumber))

userGuess=0

while userGuess!=randomNumber:
userGuess=int(input("Please make a guess -> "))

if userGuess>0:
if userGuess<randomNumber:
print("Your guess is too small\n")
elif userGuess>randomNumber:
print("Your guess is too large\n")
else:
print("\nSo sorry that you give up !\n")
break
else:
print("Congratulations! You have made a right guess!")
P. 15 of 25

Elaboration of whileGuess.py
This python program is a number guessing game where:
i. The program generates a random number between 1 and 100.
ii. The user repeatedly guesses the number until they either guess correctly or
choose to quit.

1. Importing the random Module


import random

➢ The program imports Python's built-in random module, which provides


functions for generating random numbers.

2. Generating a Random Number


randomNumber = random.randint(1, 100)

➢ The random.randint(a, b) function generates a random integer between the


two specified numbers a and b (inclusive).
➢ In this case, the random number will be between 1 and 100.

3. Debugging Line (Optional)


# print("The generated random number is %d\n"
%(randomNumber))

➢ This line (currently commented out) prints the randomly generated number. It
is useful for debugging purposes during development.
➢ In the final version of the game, this line should remain commented or
removed to prevent revealing the answer to the user.
P. 16 of 25

4. Initializing the User's Guess


userGuess = 0

➢ The variable userGuess is initialized to 0. This variable will store the user's
input during the game.

5. Starting the while Loop


while userGuess != randomNumber:

➢ The loop will continue running as long as the user's guess (userGuess) does
not match the random number (randomNumber).

6. Taking User Input


userGuess = int(input("Please make a guess -> "))

➢ The program prompts the user to enter a guess using input().


➢ The input is converted to an integer using int(input(...)).

7. Handling Positive Guesses


if userGuess > 0:
if userGuess < randomNumber:
print("Your guess is too small\n")
elif userGuess > randomNumber:
print("Your guess is too large\n")

➢ If the user's guess is greater than 0, the program compares the guess with the
random number:
✓ Case 1: If userGuess < randomNumber, the program prints:
Your guess is too small

✓ Case 2: If userGuess > randomNumber, the program prints:


Your guess is too large
P. 17 of 25

8. Handling Negative Input


else:
print("\nSo sorry that you give up!\n")
break

➢ If the user's guess is less than or equal to 0, the program assumes that the
user wants to quit the game.
➢ It prints a message indicating the user has given up and exits the loop using
break.

9. The else Block of the Loop


else:
print("Congratulations! You have made a right guess!")

➢ The else block of a while loop in Python executes if the loop terminates
normally (i.e., without encountering a break statement).
➢ If the user's guess matches the random number, the loop ends, and this block
is executed to congratulate the user.
P. 18 of 25

Classwork 2
Try to modify the the code in whileGuess.py, so that the program can count out the
number of times the user has tried before getting the correct guess. Save the new
code in file whileGuessCount.py

See the following figure for reference.


P. 19 of 25

Classwork 3
Try to modify the the code in whileGuessCount.py, so that the program can restrict
user making guess not more than 6 times. Save the new code in file
whileGuessCount6.py

See the following figure for reference.


P. 20 of 25

Usage of break and continue statement


In the previous examples, you can see that the break statement terminates the
current loop and resumes to the next statement immediately.

On the contrary, the continue statement can be used to reject all the remaining
statements in the while loop and back to the beginning of the while loop.

For the above Guess Number Game, we can check if user inputs a number between 1
and 100. By the time user does not fulfill this requirement, we can use the continue
statement for enforcing the flow of program back to the beginning of while loop
instantly.

Study python program whileGuessCountContinue.py below for further illustration:

import random

randomNumber = random.randint(1, 100)

#Dubug Trace
#May comment out later
#print("The generated random number is %d\n" %(randomNumber))

userGuess=0

#count the number of times that user guesses


counter=0

while userGuess!=randomNumber:
if counter == 6:
print("Sorry, you can't guess more than 6 times!")
break

userGuess=int(input("Please make a guess -> "))


P. 21 of 25

if userGuess < 0 or userGuess > 100:


print("You must input number between 1 and 100 inclusively!\n")
continue

counter+=1

if userGuess>0:
if userGuess<randomNumber:
print("Your guess is too small\n")
elif userGuess>randomNumber:
print("Your guess is too large\n")
else:
#print("\nSo sorry that you give up !\n")
print("\nSo sorry that you give up after %d times!\n" %(counter-1))
break
else:
print("\nCongratulations! You have made a right guess after %d times!"
%(counter))

See the following figure for reference:


P. 22 of 25

Elaboration of whileGuessCountContinue.py

This python program is an advanced version of a number guessing game. It adds a


limit on the number of guesses and checks for input validity (ensuring guesses are
within the range of 1 to 100). Let’s break it down step by step:

import random
➢ The random module is imported, which will be used to generate a random
number.

1. Generating the Random Number


randomNumber = random.randint(1, 100)

➢ random.randint(1, 100) generates a random integer between 1 and 100


(inclusive).
➢ This is the number the user will try to guess.

2. Debugging Line (Optional)


# print("The generated random number is %d\n"
%(randomNumber))

➢ This line prints the randomly generated number, useful for debugging but
should be commented out when playing the game.

3. Initializing Variables
userGuess = 0 # Variable to store the user's guess
counter = 0 # Counter to track the number of guesses

➢ userGuess is initialized to 0 and will store the player's input.


➢ counter is initialized to 0 and is used to count the number of guesses the user
has made.
P. 23 of 25

4. Starting the while Loop


while userGuess != randomNumber:

➢ The loop continues as long as the user’s guess (userGuess) is not equal to the
randomly generated number (randomNumber).

5. Limiting the Number of Guesses


if counter == 6:
print("Sorry, you can't guess more than 6 times!")
break

➢ If the user has made 6 guesses (counter == 6), the program prints this
message and exits the loop using break.

6. Taking User Input


userGuess = int(input("Please make a guess -> "))

➢ The program prompts the user to input a guess.


➢ The input is converted to an integer using int(), as the guess must be a
number.

7. Validating the Input


if userGuess < 0 or userGuess > 100:
print("You must input number between 1 and 100
inclusively!\n")
continue

➢ If the user enters a number that is less than 1 or greater than 100, the
program:
✓ Prints a warning message.
✓ Skips the rest of the loop using continue, prompting the user for
another guess.
P. 24 of 25

8. Incrementing the Counter


counter += 1

➢ Once the input is valid, the counter is incremented by 1 to keep track of the
number of guesses.

9. Checking the User’s Guess


if userGuess > 0:
if userGuess < randomNumber:
print("Your guess is too small\n")
elif userGuess > randomNumber:
print("Your guess is too large\n")

➢ If the user guesses a valid positive number:


✓ Too Small: If userGuess < randomNumber, the program prints:
Your guess is too small

✓ Too Large: If userGuess > randomNumber, the program prints:


Your guess is too large

10. Handling User Giving Up


else:
print("\nSo sorry that you give up after %d times!\n"
%(counter-1))
break

➢ If the user guesses 0 (or any other value that triggers the else block), the
program assumes the user has given up.
➢ It prints a message indicating the user gave up and exits the loop using break.
P. 25 of 25

11. Winning the Game


else:
print("\nCongratulations! You have made a right guess
after %d times!" %(counter))

➢ The else block of the while loop runs if the loop ends normally (i.e., without
encountering a break statement).
➢ If the user guesses the correct number, the program congratulates them and
displays the number of attempts (counter).

You might also like