While Loops Review
Thursday, September 12th, 2024 | CSCI100: Intro to Computer Science
What are while loops and why do we use them?
While loop syntax
while boolean_expression:
# statements to run
# if boolean expression evaluates to True
i = 10
while i < 15:
print(i, “is less than 15”)
i += 1
print(“I’m not in the while loop”)
Code Reading Exercise
Code Reading Exercise
num1 is greater than 0 so go into the loop
Code Reading Exercise
num2 equals num2 * 10 (0) + num1 % 10 (3)
So num2 = 3
Code Reading Exercise
Divide the current value of num1 by 10 and update num1 to that quotient. Num1 is now 524
Code Reading Exercise
Num1 (524) is greater than 0 so go into the loop
Code Reading Exercise
Num2 (3) equals num2 * 10 (30) + num1 % 10 (4)
So num2 = 34
Code Reading Exercise
Divide the current value of num1 by 10 and update num1 to that quotient. Num1 is now 52
Code Reading Exercise
Num1 (52) is greater than 0 so go into the loop
Code Reading Exercise
Num2 (34) equals num2 * 10 (340) + num1 % 10 (2)
So num2 = 342
Code Reading Exercise
Divide the current value of num1 by 10 and update num1 to that quotient. Num1 is now 5
Code Reading Exercise
Num1 (5) is greater than 0 so go into the loop
Code Reading Exercise
Num2 (342) equals num2 * 10 (3450) + num1 % 10 (5)
So num2 = 3425
Code Reading Exercise
Divide the current value of num1 by 10 and update num1 to that quotient. Num1 is now 0
Code Reading Exercise
Num1 (0) is not greater than 0 so don’t go into the loop
Code Reading Exercise
Print the values of num 1 and num2
num1: 0
num2: 3425
Code Writing Exercise
While loop Tips