Python Lesson 2a Notes - Updated 1
Python Lesson 2a Notes - Updated 1
1 of 25
Contents
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.
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.
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:
➢ 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.
➢ Inside the loop, the program prints the string "Hello World!" to the console
each time the loop runs.
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
whileSum.py
while counter<=x:
sum=sum+counter
counter+=1 #counter=counter+1
ch = input('')
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.
➢ 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:
Final Output:
The sum of 1 to 10 is 55
➢ 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
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.
Hint:
The program needs to create a random number. Therefore it's necessary to include
the module "random" by statement import random
Screen 1
P. 13 of 25
Screen 2
P. 14 of 25
import random
#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.
➢ 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
➢ The variable userGuess is initialized to 0. This variable will store the user's
input during the game.
➢ The loop will continue running as long as the user's guess (userGuess) does
not match the random number (randomNumber).
➢ 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
➢ 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.
➢ 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
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
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.
import random
#Dubug Trace
#May comment out later
#print("The generated random number is %d\n" %(randomNumber))
userGuess=0
while userGuess!=randomNumber:
if counter == 6:
print("Sorry, you can't guess more than 6 times!")
break
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))
Elaboration of whileGuessCountContinue.py
import random
➢ The random module is imported, which will be used to generate a random
number.
➢ 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
➢ The loop continues as long as the user’s guess (userGuess) is not equal to the
randomly generated number (randomNumber).
➢ If the user has made 6 guesses (counter == 6), the program prints this
message and exits the loop using break.
➢ 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
➢ Once the input is valid, the counter is incremented by 1 to keep track of the
number of guesses.
➢ 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
➢ 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).