Week8 Group1
Week8 Group1
The first two variables are initialized with 1729 and 0 before
the loop is entered.
n = 1729
total = 0
while n > 0 :
digit = n % 10
total = total + digit
n = n // 10
print(total)
PBL 5: THIẾT KẾ HỆ THỐNG ĐIỀU KHIỂN
n = 1729
total = 0
while n > 0 : Because n equals zero,
digit = n % 10 this condition is not
total = total + digit true.
n = n // 10
print(total)
PBL 5: THIẾT KẾ HỆ THỐNG ĐIỀU KHIỂN
This statement is an output statement. The value that is output is the value of total, which
is 19.
Of course, you can get the same answer by just running the code. However, hand-tracing
can give you insight that you would not get if you simply ran the code. Consider again what
happens in each iteration:
• We extract the last digit of n.
• We add that digit to total.
• We strip the digit off of n.
PBL 5: THIẾT KẾ HỆ THỐNG ĐIỀU KHIỂN
while . . . :
salary = float(input("Enter a salary or -1 to finish: "))
if salary >= 0.0 :
total = total + salary
count = count + 1
• Any negative number can end the loop, but we prompt for a sentinel of –1 so that the
user need not ponder which negative number to enter. Note that we stay in the loop
while the sentinel value is not detected.
After the loop has finished, we compute and print the average.
PBL 5: THIẾT KẾ HỆ THỐNG ĐIỀU KHIỂN
PBL 5: THIẾT KẾ HỆ THỐNG ĐIỀU KHIỂN
If the first value entered by the user is the sentinel, then the body of the loop is never
executed. Otherwise, the value is processed just as it was in the earlier version of the loop.
The input operation before the loop is known as the priming read, because it prepares or
initializes the loop variable.
PBL 5: THIẾT KẾ HỆ THỐNG ĐIỀU KHIỂN