首页 > 解决方案 > 名称“ticketType”未定义

问题描述

我已经使循环工作,因此它可以重复给定次数。虽然,我无法总结票价,这给了我一个错误

'ticketType' not defined

我试过了ticketType = 0,但totalCost结果是0。

这是 python 代码的链接:https ://repl.it/repls/IrratingBlankOs

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)?')
    return ticketCost
    return ticketType
    return movieType


ticketCost=0

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

count = 1
while (count <= num):
    ticketCost = ticketCost + buyOneTicket() 
    count = count + 1

print('Your total cost for ' + str(num) + ' is ', ticketCost)

知道为什么它没有按预期工作吗?

标签: python

解决方案


正确的程序:

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
print('Your total cost for ' +str(num)+ ' is ', ticketCost )

我希望你能理解发生了什么变化。祝你好运 !

你也可以写得更短:

print ('Welcome to RareCinema Ticketing System')
num = int(input('How many tickets would you like to buy?'))
ticket = {("child", "2D"):16,("child", "3D"):19,
          ("adult", "2D"):22,("adult", "3D"):27,
          ("senior", "2D"):14,("senior", "3D"):18,}
def buyOneTicket() :
    ticketType = input('Enter the type of ticket (Child/Adult/Senior)?').lower()
    movieType = input('Enter the movie type (2D/3D)?').upper()
    return ticket[(ticketType, movieType)]

ticketCost=0
count = 1
while (count <= num):
    ticketCost = ticketCost  + buyOneTicket() 
    count = count + 1

print('Your total cost for ' +str(num)+ ' is ', ticketCost )

推荐阅读