我修改了引文以修复语法错误。现在我收到的错误是这个:
Traceback (most recent call last):
File "C:\Users\Alex\Desktop\Programming Concepts\Labs\Chapter 11\Lab 8.py", line 78, in <module>
main()
File "C:\Users\Alex\Desktop\Programming Concepts\Labs\Chapter 11\Lab 8.py", line 18, in main
totalPints = getTotal(pints)
File "C:\Users\Alex\Desktop\Programming Concepts\Labs\Chapter 11\Lab 8.py", line 42, in getTotal
totalPints += pints[counter]
UnboundLocalError: local variable 'totalPints' referenced before assignment
到目前为止,这是我的代码:
# Lab 8-3 Blood Drive
# The main function
def main():
endProgram = 'no'
print
while endProgram == 'no':
print
# Declare variables
pints = [0] * 7
# Function calls
pints = getPints(pints)
totalPints = getTotal(pints)
averagePints = getAverage(totalPints)
highPints = getHigh(pints)
lowPints = getLow(pints)
displayInfo(averagePints, highPints, lowPints)
endProgram = 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 = input('Do you want to end program? (Enter no or yes): ')
# The getPints function
def getPints(pints):
counter = 0
while counter < 7:
numEntered = input('Enter pints collected: ')
pints[counter] = int(numEntered)
counter += 1
return pints
# The getTotal function
def getTotal(pints):
counter = 0
while counter < 7:
totalPints += pints[counter]
counter += 1
return totalPints
# The getAverage function
def getAverage(totalPints):
averagePints = float(totalPints) / 7
return averagePints
# The getHigh function
def getHigh(pints):
highPints = pints[0]
counter = 1
while counter < 7:
if pints[counter] > highPints:
highPints = pints[counter]
counter += 1
return highPints
# The getLow function
def getLow():
lowPints = pints[0]
counter = 1
while counter < 7:
if pints[counter] < lowPints:\
lowPints = pints[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 number of pints donated is ', lowPints)
# Calls main
main()
如果有人可以将这些代码复制并粘贴到他们的python中并帮助排除故障,我会非常感激!
答案 0 :(得分:3)
您需要更改引号的所有‘
('
或"
)。您还需要在getPints
函数中检查缩进:
# The getPints function
def getPints(pints):
counter = 0
while counter < 7:
numEntered = input(‘Enter pints collected: ‘)
pints[counter] = int(numEntered)
counter += 1
return pints
在函数定义之后再缩进一个级别,就像在main
函数中一样:
# The getPints function
def getPints(pints):
counter = 0
while counter < 7:
numEntered = input(‘Enter pints collected: ‘)
pints[counter] = int(numEntered)
counter += 1
return pints
答案 1 :(得分:0)
“赋值前引用的变量”只表示您正在使用尚不存在的变量。在您的代码中,问题是这一行:
totalPints += pints[counter]
这是totalPints的第一次出现。请记住,“+ =”构造完全等同于
totalPints = totalPints + pints[counter]
这是python反对的右手事件。要解决此问题,请使用
初始化变量totalPints = 0
进入循环之前。
答案 2 :(得分:0)
这很容易解决。 您只需在向其添加内容之前分配变量即可。
totalPins = 0
或
totalPins = ""
在进入循环之前应该可以做到。