类型错误:不支持的操作数类型 Int 和 NoneType

0 投票
2 回答
5753 浏览
提问于 2025-04-17 22:23

大家好,我正在写一个Python程序,但我在循环中总是遇到错误。这个循环本来是用来让用户重新输入一个数字的。我的问题是,它总是返回一个“无类型”(nonetype),这个“无类型”是不能用来进行操作的,而我在其他函数中需要用到它。希望能得到一些帮助,谢谢!

(这是我的代码,提前抱歉如果格式不太正确。)

def getTickets(limit):
   ticketSold=int(input("How many tickets were sold? "))
   if (ticketsValid(ticketSold,limit)):
        return ticketSold
   else:
        getTickets(limit)

#This function checks to make sure that the sold tickets are within the Limit of seats
def ticketsValid(sold,limit):

    if (sold>limit or sold<0):
        print ("ERROR: There must be tickets less than "+str(limit)+" and more than 0")
        return False
    return True
# This function calculates the price of the tickets sold in the section.
def calcIncome(ticketSold,price):
    return ticketSold*(price)

2 个回答

1

在Python中,如果一个函数没有返回任何东西,它默认会返回None。你有一个else的部分,它调用了一个函数,但没有对这个函数的结果做任何处理,结果就是函数就这样结束了。因此,如果程序走到了这个分支,你就会从那个函数得到None

2

你在else这个部分没有返回getTickets(limit)的结果:

def getTickets(limit):
   ticketSold=int(input("How many tickets were sold? "))
   if (ticketsValid(ticketSold,limit)):
        return ticketSold
   else:
        return getTickets(limit)  # You need to use return here

撰写回答