基于条件的函数不会返回值-python
我是新手,我正在寻求帮助。我目前正努力完成一个项目。这是:基于条件的函数不会返回值-python,python,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():
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,而不是列表上的股票价格。我似乎无法让它工作。有人能帮我吗?尝试添加此打印以帮助您调试:
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
此外,我还更改了一个变量,这似乎比修改输入值然后返回要好。提示:循环会一直运行,直到您停止它,或者它到达其终点。循环不是在s==stockList[I]时到达终点吗@NJZK2N不,没有理由。我想我可以通过摆脱“elif s!”来阻止它股票列表[i]s=-1',但我需要那一行。我还能做些什么来阻止循环,一旦它有了s的股票价格[i]@NJZK2提前退出循环的关键字是
break
。但是您不需要其他部分,只需在循环之前移动s=-1
。