While Loop
© Faculty of Management
While Statement
Create a loop that executes a block of code repeatedly as long as a
given condition is true.
while condition:
Code Block #Code to be executed repeatedly
• The expression or condition provided in the while statement is a Boolean
expression that evaluates to either True or False.
• The indented code block following the while statement is the set of
instructions that will be executed repeatedly as long as the condition
remains true.
Example: While statement
Print numbers from 1 to 5
num=1 # initialize variable
while num <6: # condition
# code block
print(num)
# update statement
num+=1 # num=num+1
Updating Statement in While Statement
What if you forget the updating statement within the loop?
num=1 # initialize variable
Be careful!
while num <6: # condition Incorrect or improperly designed
# code block conditions might lead to an infinite
print(num) loop, causing the program to run
# update statement indefinitely!
num+=1 # num=num+1
Example: Guess the Number
Create a game where the computer selects a random number between a given
range (e.g., 1 to 50), and the player's objective is to guess that number.
Guess the Number 30
Too large
Number=24 Guess the Number 20
Too small
Guess the Number 24
Correct!
• The player enters their guesses, and the game provides feedback, "Too small" or
"Too large".
• Once the player correctly guesses the number, it congratulates the player with a
"Correct!" message.
Guess the Number: Random module
Random Module
The built-in module provides functions for generating random numbers
and making random selections.
import random
• random.randint(a,b): Return a random
integer N such that a <= N <= b. for i in range(5):
• random.choice(seq): Return a random rand_int=random.randint(1,10)
element from the non-empty print(rand_int)
sequence seq.
Guess the Number: Using a loop
Outside of the loop
import random
answer = random.randint(1, 50)
#Set up a boolean variable to control the loop
guess_correct = False
Guess the Number: Defining the conditions
while not guess_correct:
user_guess = int(input("Enter your guess: "))
if user_guess == answer:
print("Correct! You guessed the right number.")
guess_correct = True # Set the Boolean variable to True to terminate the loop
else:
if user_guess < answer:
print("Too small. Try again.")
else:
print("Too large. Try again.")
Example: Random number list
Generate a list that contains 5 random integers ranging from 1 to 10.
e.g.,) list_random=[3, 1, 6, 7, 9]
Random Number List: Using while loops
Generate a list that contains 5 random integers ranging from 1 to 10.
e.g.,) list_random=[3, 1, 6, 7, 9]
import random
# Initialize an empty list to store random integers
list_random = []
# Use a while loop to generate 5 random integers
while len(list_random) < 5:
random_int = random.randint(1, 10)
list_random.append(random_int)
print("Using while loop:", list_random)
Random Number List: Using for loops
Generate a list that contains 5 random integers ranging from 1 to 10.
e.g.,) list_random=[3, 1, 6, 7, 9]
import random
# Initialize an empty list to store random integers
list_random = []
# Use a for loop to generate 5 random integers
for i in range(5):
random_int = random.randint(1, 10) For-loops can be
list_random.append(random_int) also useful.
print("Using for loop:", list_random)
For vs While
For-statement While-statement
for Repeat Variable in Sequence: while Condition :
Code Block Code Block
For loops are useful when While loops are useful when
• You want to perform the same • You do not know the number of
operations on each item. iterations.
• Need to repeat instructions until
a particular condition is met.
Summary
For Statement While Statement
Purpose Used to iterate over a sequence (e.g., Used to repeatedly execute a code
list, tuple, string) block based on a condition
Interaction Controlled by the length of the Controlled by a Boolean condition
Control sequence or iterable object
Initialization The iteration variable is automatically Initialization of loop control variables is
assigned to each item done explicitly before the loop
Loop Control The iteration variable is automatically The loop control variable needs to be
Variable updated explicitly updated within the loop
Termination Iteration stops when all items are Iteration stops when the condition
processed becomes false
Flexibility Suitable when the number of Suitable when the number of iterations
iterations is known or predetermined is uncertain or based on a condition
Break & Continue
© Faculty of Management
Break & Continue
We can use the break and continue statement to modify the control
flow of loops (e.g., for and while loops).
• Break statement: It can be used inside a loop to terminate it
prematurely
• Continue statement: It can be used inside a loop to skip the current
iterations and immediately proceed to the next iteration
Break
When encountered, it immediately exists the loop, and the program
continues executing the code after the loop.
Example: Shopping Application
Develop an online shopping application allowing users to add products
to their cart.
The loop repeatedly asks users if they want to add products.
• If the user chooses to add a product, they input the
product’s ID to be added to the cart.
• The loop continues until the user decides to stop
adding products by entering "N" for "No."
Example: Break
# Initialize an empty list to store product IDs added to the cart
cart_items = []
# The while loop will run indefinitely until the user decides to stop adding products
while True:
add_to_cart = input("Add to Cart? Y/N : ")
# If the user chooses to add a product to the cart
if add_to_cart.upper() == "Y":
product_id = input("Enter the Product ID to add to the cart: ")
cart_items.append(product_id)
else:
# If the user enters "N" for "No", the loop will be terminated using the break statement
break
print("Products added to the cart:", cart_items)
Continue
When encountered, it stops the current iteration’s execution and jumps
back to the beginning of the loop to start the next iteration.
Example: Total Revenue
Calculate the total revenue generated by customers.
customer_data={
'mem_01':50,'mem_02':-30,'mem_03':400,'mem_04':1500,'mem_05':2000,
'mem_06':5000,'mem_07':0,'mem_08':4000,'mem_09':1500,'mem_10':1200,
}
total_revenue = 0
for mem_id in customer_data:
# Calculate total revenue
total_revenue += customer_data[mem_id]
print(total_revenue)
Example: Continue
customer_data={
'mem_01':50,'mem_02':-30,'mem_03':400,'mem_04':1500,'mem_05':2000,
'mem_06':5000,'mem_07':0,'mem_08':4000,'mem_09':1500,'mem_10':1200,
}
total_revenue = 0
for mem_id in customer_data:
# Skip customers with no purchase amount or invalid data
if customer_data[mem_id] <0:
continue
# Calculate total revenue
total_revenue += purchase_amount
print(total_revenue)
Summary
Break Continue
Functions (I)
© Faculty of Management
Function
A function is a block of reusable code that performs a specific task.
• Define: Creating a named section of code that performs a specific
task
• Call: The action of running or executing a specific function in a
program
• Return: The return statement is used within a function to send a
value or result back to the function's caller. When a function is
executed, it may perform certain operations and optionally produce
a value.
Example: Using functions
• The idea of a function is to organize and encapsulate a set of
instructions that can be executed multiple times within a program.
Define Function
Define function: "describe" specifically how a named code behaves in
a specific way
def FunctionName (parameter):
#Code Block
return FunctionResult
Function (cont.)
Define function: "describe" specifically how a named code behaves in a
specific way
• The function can take parameter to pass information to be processed.
• The function return the computed result to the place where the function was
called (return value).
Function without Parameters & Return Values
(Case 1)
Define
def promo(): # define promo function
print("Spend over $50 for a 10% discount coupon.")
Call Result
promo() Spend over $50 for a 10% discount coupon.
promo() Spend over $50 for a 10% discount coupon.
Function with Parameters
(Case 2)
Define
def promo(min_amount, discount_rate): # define promo function
print("Spend over", min_amount, "for a" , discount_rate, " % discount coupon.")
Call Result
promo(50, 30) Spend over $50 for a 30% discount coupon.
promo(30, 10) Spend over $30 for a 10% discount coupon.
Function with Parameters & Return Values
(Case 3)
Define
def promo_order_pay(order_amount, min_amount, discount_rate):
if order_amount>min_amount:
pay_amount=order_amount*(100-discount_rate)/100
else:
pay_amount=order_amount
return pay_amount
Case 3: Call & Result
(Case 3)
Call
pay_amount=promo_order_pay(100, 50,10) # $90
sales_tax=14.975
pay_amount_tax=pay_amount*(1+(sales_tax/100)) # $90*1.14975
print(f"${pay_amount_tax}")
Result
$103.4775
Question
What’s the difference between return and print function?
with return statement without return statement
def abs(arg): def abs2(arg):
if arg<0: if arg<0:
result=-1*arg result=-1*arg
else: else:
result=arg result=arg
return result print result
value=abs(-10) value2=abs2(-10)
Error!