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

时间:2016-02-21 01:14:13

标签: python

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

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:")
    s = searchStock(stockList, stockPrice, s)

每次我运行程序到最后,它都不会因某种原因返回变量s。如果我用print替换return,它总是打印-1而不是stockPrice,如果它在列表中。我似乎无法让它工作。有人可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

尝试添加此打印件以帮助您进行调试:

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

此外,我更改了您的一个变量,它似乎比修改输入值然后返回它更好。