import random
# use an accumulator pattern to track the total and the number of rolls
runningTotal:int = 0 # initialize to a starting value of 0
numRolls = 0 # initialize to a starting value of 0
# while we haven't reached 20
while runningTotal <= 20:
# roll the die
dieRoll:int = random.randint(1,6)
# accumulate into the number of rolls
numRolls += 1
# accumulate into the running total
runningTotal += dieRoll
# print the result
print( f"After {numRolls} rolls, the total is {runningTotal}.")
Use a while loop to compute the squares of the numbers 1,2,3,... until the sum of the squares exceeds 1000.
# Use a while loop to compute the squares of the numbers 1,2,3,... until the sum of the squares exceeds 1000.
# accumulator pattern
sum:int = 0 # initialize running sum to 0
currentValue:int = 1 # start the loop variable at 1
# while the sum hasn't exceeded 1000
while sum <= 1000:
# square the current value and add it to the sum
sum += currentValue*currentValue
# update the loop variable
currentValue += 1
print( f"The sum of the squares of the numbers from 1 to {currentValue - 1} is {sum}.")
Use a while loop to prompt the user for a number and maintain a running product. Continue prompting for input until the use enters 0.
# Use a while loop to prompt the user for a number and maintain a running product.
# Continue prompting for input until the use enters 0.
# accumulator pattern
product:int = 1 # initialize running product to 1
# loop variable for determining whether we continue
# let's make this a string type, since we know that is what the input function returns
# initialize by prompting the user for a value
userInput:str = input( "Please enter a number or 0 to quit: " )
# while the user's input is not "0"
while userInput != "0":
# turn the input to a number
userNum:float = float(userInput)
# multiply into the running product
product *= userNum
# update the loop variable by prompting the user to enter a value
userInput = input( "Please enter a number or 0 to quit: " )
print( f"The product of all your numbers is {product}.")