python - UnboundLocalError:分配前引用的局部变量“ticketCost”
问题描述
因此,当我输入除儿童、成人和老年人或 3D 和 2D 以外的任何内容时,我希望出现一条错误消息,显示“抱歉,输入无效”。然后我希望它再次要求用户输入ticketType和movieType,但它想出了
"File "python", line 33, in <module>
File "python", line 27, in buyOneTicket
UnboundLocalError: local variable 'ticketCost' referenced before assignment"
.
print ('Welcome to RareCinema Ticketing System')
num = int(input('How many tickets would you like to buy?'))
def buyOneTicket() :
ticketType = input('Enter the type of ticket (Child/Adult/Senior)?')
movieType = input('Enter the movie type (2D/3D)?')
if ticketType == ("child"):
if movieType == ("2D"):
ticketCost = 16
elif movieType == ('3D'):
ticketCost = 19
elif ticketType == ('adult'):
if movieType == ('2D'):
ticketCost = 22
elif movieType == ('3D'):
ticketCost = 27
elif ticketType == ('senior'):
if movieType == ('2D'):
ticketCost = 14
elif movieType == ('3D'):
ticketCost = 18
return ticketCost
ticketCost=0
count = 1
while (count <= num):
ticketCost = ticketCost + buyOneTicket()
count = count + 1
if ticket_type != ('child') and ('adult') and ('senior'):
if movie_type != ('2D') and ('3D'):
print ('Sorry, you have entered an invalid input')
ticketType = input('Enter the type of ticket (Child/Adult/Senior)?')
movieType = input('Enter the movie type (2D/3D)?')
else:
print('Your total cost for ' +str(num)+ ' is ', ticketCost )
解决方案
def buyOneTicket() :
ticketType = input('Enter the type of ticket (Child/Adult/Senior)?')
movieType = input('Enter the movie type (2D/3D)?')
if ticketType == ("child"):
if movieType == ("2D"):
ticketCost = 16
elif movieType == ('3D'):
ticketCost = 19
elif ticketType == ('adult'):
if movieType == ('2D'):
ticketCost = 22
elif movieType == ('3D'):
ticketCost = 27
elif ticketType == ('senior'):
if movieType == ('2D'):
ticketCost = 14
elif movieType == ('3D'):
ticketCost = 18
return ticketCost
所以你buyOneTicket
方法的最后一行是发生这种情况的地方,原因是ticketCost
只有当你ticketType
匹配你列出的类别之一时才会创建它。您可以考虑在最后创建一个else
条件,该条件将再次询问用户:
def buyOneTicket() :
ticketType = input('Enter the type of ticket (Child/Adult/Senior)?')
movieType = input('Enter the movie type (2D/3D)?')
if ticketType == ("child"):
if movieType == ("2D"):
ticketCost = 16
elif movieType == ('3D'):
ticketCost = 19
elif ticketType == ('adult'):
if movieType == ('2D'):
ticketCost = 22
elif movieType == ('3D'):
ticketCost = 27
elif ticketType == ('senior'):
if movieType == ('2D'):
ticketCost = 14
elif movieType == ('3D'):
ticketCost = 18
else:
print('You did not pick a valid ticket type. Try again.')
return buyOneTicket()
return ticketCost
推荐阅读
- python - 将带有列表对象的 Dataframe 列转换为浮点数
- maven - Vaadin 8 + AudioVideo 插件:“加载小部件集失败”
- java - vertx中future的完成方法的用途是什么?
- r - 在图表中可视化 3 个变量
- python - 使用 chrome 驱动程序在自动脚本中共享屏幕的方法
- android - 改造:只允许一种 HTTP 方法。找到:GET 和 GET
- javascript - 使用 JavaScript 滚动标签栏项目
- asp.net-core - 使用 ASP Core 2.2 api 上传和下载大文件 ~50gb
- php - PHP - 使用命名空间创建 PDO 连接
- ansible - 在ansible playbook上安装后有没有办法登录和注销用户?