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

2024-04-29 18:59:12 发布

您现在位置: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而不是股价。我似乎不能让它工作。有人能帮我吗


Tags: oftheforinputifdefstockprice
1条回答
网友
1楼 · 发布于 2024-04-29 18:59:12

尝试添加此打印以帮助调试:

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

我还更改了一个变量,这似乎比修改输入值然后返回值要好

相关问题 更多 >