python函数不会返回基于条件的值

时间:2016-02-19 22:31:52

标签: function python-3.x return-value

我是新手,我正在寻求帮助。我目前陷入了一个我想要完成的计划。这是:

def printStock(stockList, stockPrice, p):
    for i in range(len(stockPrice)):
        if stockPrice[i] > p:
            p = stockList[i]
    print("The stocks with a higher value are:", p) 

def searchStock(stockList, stockPrice, s):
    for i in range(len(stockList)):
        if s == stockList[i]:
            s = stockPrice[i]
        elif s != stockList[i]:
            s = -1
    return s

def mainFun():
    stockList= []
    stockPrice = []
    l = 1
    while l > 0:
        stocks = str(input("Enter the name of the stock:"))
        stockList +=  [stocks]
        if stocks == "done"or stocks == 'done':
            l = l * -1
            stockList.remove("done")
        else:
            price = int(input("Enter the price of the stock:"))
        stockPrice += [price]
        l = l + 1
    print(stockList)
    print(stockPrice)
    s = input("Enter the name of the stock you're looking for:")
    searchStock(stockList, stockPrice, s)
    p = s
    printStock(stockList, stockPrice, p)

每次我运行程序到最后,它都不会因某种原因返回变量s。如果我用print替换return,它总是打印-1而不是stockPrice,如果它在列表中。我还得到一个错误,说“关于第3行的”无法解决的类型int()> str()“。基本上函数printStock采用三个参数,一旦函数完成,它应该打印高于值'p的股票的名称”。 'p'的值与调用searchStock函数后获得的值相同,但我似乎无法使其工作。有人可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

从函数返回

s,但返回值未分配给外部作用域上的任何变量。

只需替换

searchStock(stockList, stockPrice, s)

s=searchStock(stockList, stockPrice, s)

一切都应该按预期工作