UnboundLocalError:局部变量'mp'在赋值前被引用
我在测试的时候遇到了这个错误:
Please enter the customer's name: 1
Please enter the customer's Phone Number:01506890639
Please enter the size of group: 4
Please enter the rating of the meal: 3
Do you wish to continue: Y/N?n
The largest group that visited had a cohort of:4
Traceback (most recent call last):
File "E:/CWtsk/code2.1.py", line 93, in <module>
main()
File "E:/CWtsk/code2.1.py", line 12, in main
mealrating(score)
File "E:/CWtsk/code2.1.py", line 67, in mealrating
mp = mp + 1
UnboundLocalError: local variable 'mp' referenced before assignment
我对这个引用的事情有点不太明白,因为在我的代码里,它之前并没有被引用过。
def main():
name = []
phone = []
groupno = []
score = []
review = []
q="y"
data(name, phone, groupno, score, q)
maxi(groupno)
mealrating(score)
poorest(name, phone, groupno, score, review)
# Gathering Data ---------------------------------------------------
def data(n, p, g, s, q):
while q != "n":
name = input("Please enter the customer's name: ")
n.append(name)
phone = ""
while len(str(phone)) != 11:
try:
phone = input("Please enter the customer's Phone Number:")
except ValueError:
phone = ""
p.append(phone)
groupno = int(input('Please enter the size of group: '))
while groupno < 1 or groupno > 20:
groupsizes= int(input('Please enter a valid group size: '))
g.append(groupno)
score = int(input('Please enter the rating of the meal: '))
while score < 1 or score > 10:
score = int(input('Please enter the rating of the meal- between 1 and 10: '))
s.append(score)
q=input("Do you wish to continue: Y/N?")
# finding largest group size ---------------------------------------
def maxi(groupno):
xGroup = groupno[0]
for x in range(0,len(groupno)):
if groupno[x] > xGroup:
xGroup = groupno[x]
print('\n')
print('The largest group that visited had a cohort of:' + str(xGroup))
# determining the meal rating and counting number of applied ratings and priniting --------------------------------------------------------------------------------
def mealrating(score):
for x in range(0,len(score)):
if score[x] >= 1 and score[x] <= 3:
mp = mp + 1
if score[x] >= 4 and score[x] <= 6:
mg = mg + 1
if score[x] >= 7 and score[x] <= 10:
me = me + 1
print('\n')
print("The customer rated tonight's meal as:")
print('%10s' % ('Poor:', mp ))
print('%10s' % ('Good:', mg ))
print('%10s' % ('Excellent:', me ))
# finding the poor meals -------------------------------------------
def poorest(name, score, review):
for x in range (len.name):
if review[x] == poor:
print("Contact Name: " % name[x])
print("Phone Number: " % phone[x])
print("Rating: " % score[x])
main()
我也不太清楚这是什么。虽然我需要调整最后一个函数,因为我在排查问题的时候忘记了它。
1 个回答
0
你还没有定义mp,但你已经在赋值的右边使用了它。这就导致了错误。你可以很简单地通过以下方式来修复这个问题:
mp = 0 # <- Add this line and change the 0 if you expect something different
if score[x] >= 1 and score[x] <= 3:
mp = mp + 1