这是作业。这所特殊的学校提供0帮助,教授不太乐于助人。我只是在寻找指导,为什么这段代码不起作用。我有使用Python 2.7。当我运行程序时,它要求我输入适当数量的品脱,但什么都不做。
# This program finds the average number of pints collected, the highest amount, and the lowest amount
# Lab 9-4 Blood drive
#the main function
def main():
endProgram = 'no'
print
while endProgram == 'no':
print
# declare variables
pints = [0] * 7
totalPints = 0
averagePints = 0
highPints = 0
lowPints = 0
# function calls
pints = getPints(pints)
totalPints = getTotal(pints, totalPints)
averagePints = getAverage(totalPints, averagePints)
highPints = getHigh(pints, highPints)
lowPints = getLow(pints, lowPints)
displayInfo(averagePints, highPints, lowPints)
endProgram = raw_input('Do you want to end program? (Enter no or yes): ')
while not (endProgram == 'yes' or endProgram == 'no'):
print 'Please enter a yes or no'
endProgram = raw_input('Do you want to end program? (Enter no or yes): ')
#the getPints function
def getPints(pints):
counter = 0
while counter < 7:
pints[counter] = input('Enter pints collected: ')
counter = counter + 1
return pints
#the getTotal function
def getTotal(pints, totalPints):
counter = 0
while counter < 7:
totalPints = totalPints + pints[counter]
counter = counter + 1
return totalPints
#the getAverage function
def getAverage(totalPints, averagePints):
averagePints = totalPints / 7
return averagePints
#the getHigh function
def getHigh(pints, highPints):
highPints = pints[0]
counter = 1
while counter < 7:
if pints[counter] > highPints:
highPints = pints[counter]
counter = counter + 1
return highPints
#the getLow function
def getLow(pints, lowPints):
lowPints = pints[0]
counter = 1
while counter < 7:
if pints[counter] < lowPints:
lowPints = pints[counter]
counter = counter + 1
return lowPints
#the displayInfo function
def displayInfo(averagePints, highPints, lowPints):
print "The average number of pints donated is ", averagePints
print "The highest pints donated is ", highPints
print "The lowest pints donated is ", lowPints
# calls main
main()
答案 0 :(得分:2)
函数getLow()
中存在无限循环,因为counter
仅在当前值小于先前值时递增。例如输入值1, 2, 3, 4, 5, 6, 7
将导致无限循环,但是,如果您输入7, 6, 5, 4, 3, 2, 1
,则循环将终止。
函数getHigh()
有类似的问题,但如果要避免无限循环,则值必须是递增的。请注意,getLow()
或getHigh()
中的一个将始终在您的代码中生成一个循环。
提示:看看使用Python的min()
和max()
函数。