设置sentinel值并使用sentinel值停止循环

问题描述 投票:0回答:2

我已经想出了总数,他们正在按原样运行。一旦输入完成,我就无法让程序停止。它只是保持循环。我已将哨兵设为等于“完成”。有人可以帮忙吗?

# SuperMarket.py - This program creates a report that lists weekly hours worked 
# by employees of a supermarket. The report lists total hours for 
# each day of one week. 
# Input:  Interactive
# Output: Report. 
# Declare variables.
HEAD1 = "WEEKLY HOURS WORKED"
DAY_FOOTER = "Day Total "
SENTINEL = "done"   # Named constant for sentinel value
hoursWorked = 0     # Current record hours
hoursTotal = 0      # Hours total for a day
prevDay = ""        # Previous day of week
notDone = True      # loop control
# Print two blank lines.
print("\n\n")
# Print heading.
print("\t" + HEAD1)
# Print two blank lines.
print("\n\n")

# Read first record 
dayOfWeek = input("Enter day of week or done to quit: ")
if dayOfWeek  == SENTINEL:
    notDone = False
else:
    prevDay = dayOfWeek
    hoursWorked = input("Enter hours worked:")
    while notDone == True:
        dayOfWeek = input("Enter day of week or done to quit: ")
        hoursTotal = hoursTotal + int(hoursWorked)
        if prevDay != dayOfWeek:
            print("\t" + DAY_FOOTER + str(hoursTotal))
            prevDay = dayOfWeek #Include work done in the dayChange()function
            hoursTotal = 0
        hoursWorked = input("Enter hours worked:")
python loops sentinel accumulator
2个回答
0
投票

您的代码不会仅添加第一条记录上插入的hoursWorked。剩余的天数/输入(即在while循环内部)正常添加。如果这是你的问题,只需将最后的hoursWorked(在循环内)更改为:

hoursWorked = int(hoursWorked) + int(input("Enter hours worked:"))


0
投票

我想出了一切。我必须添加另一个if语句来使循环在while语句中中断!

# SuperMarket.py - This program creates a report that lists weekly hours worked 
# by employees of a supermarket. The report lists total hours for 
# each day of one week. 
# Input:  Interactive
# Output: Report. 
# Declare variables.
HEAD1 = "WEEKLY HOURS WORKED"
DAY_FOOTER = "Day Total "
SENTINEL = "done"   # Named constant for sentinel value
hoursWorked = 0     # Current record hours
hoursTotal = 0      # Hours total for a day
prevDay = ""        # Previous day of week
notDone = True      # loop control
# Print two blank lines.
print("\n\n")
# Print heading.
print("\t" + HEAD1)
# Print two blank lines.
print("\n\n")

# Read first record 
dayOfWeek = input("Enter day of week or done to quit: ")
if dayOfWeek  == SENTINEL:
    notDone = False
else:
    prevDay = dayOfWeek
    hoursWorked = input("Enter hours worked:")



    while notDone == True:
        dayOfWeek = input("Enter day of week or done to quit: ")
        hoursTotal = hoursTotal + int(hoursWorked)
        if prevDay != dayOfWeek:
            print("\t" + DAY_FOOTER + str(hoursTotal))
            if dayOfWeek == "done":
                break
            else:
                prevDay = dayOfWeek #Include work done in the dayChange()function
                hoursTotal = 0
        hoursWorked = input("Enter hours worked:")
© www.soinside.com 2019 - 2024. All rights reserved.