【发布时间】:2013-04-01 15:24:42
【问题描述】:
我正在尝试使用 python 创建一个小型查找程序,该程序将显示理论投资组合的所有当前价格,然后提供基本刷新您的投资组合的选项,或查找您选择的新报价.
我可以让程序中的一切正常工作,我遇到的问题是定义的函数。
如果您查看 run_price1(),您会注意到它与 run_price() 相同;但是 run_price() 位于更新函数中。
如果我将它从更新功能中取出,更新功能将不起作用。如果我没有在更新功能之外的某个地方也列出它,那么以后的用户输入将不起作用。
问题:我正在寻找一种方法来调用在另一个函数中定义的函数,或者一种在辅助函数中使用先前定义的函数的方法。
我的代码:
import mechanize
from bs4 import BeautifulSoup
def run_price1():
myBrowser = mechanize.Browser()
htmlPage=myBrowser.open(web_address)
htmlText=htmlPage.get_data()
mySoup = BeautifulSoup(htmlText)
myTags = mySoup.find_all("span", id=tag_id)
myPrice = myTags[0].string
print"The current price of, {} is: {}".format(ticker.upper(), myPrice)
def update():
my_stocks = ["aapl","goog","sne","msft","spy","trgt","petm","fslr","fb","f","t"]
counter = 0
while counter < len(my_stocks):
web_address = "http://finance.yahoo.com/q?s={}".format(my_stocks[counter])
ticker = my_stocks[counter]
#'yfs_l84_yhoo' - that 1(one) is really a lowercase "L"
tag_id = "yfs_l84_{}".format(ticker.lower())
def run_price():
myBrowser = mechanize.Browser()
htmlPage=myBrowser.open(web_address)
htmlText=htmlPage.get_data()
mySoup = BeautifulSoup(htmlText)
myTags = mySoup.find_all("span", id=tag_id)
myPrice = myTags[0].string
print"The current price of, {} is: {}".format(ticker.upper(), myPrice)
run_price()
counter=counter+1
update()
ticker = ""
while ticker != "end":
ticker = raw_input("Type 'update', to rerun portfolio, 'end' to stop program, or a lowercase ticker to see price: ")
web_address = "http://finance.yahoo.com/q?s={}".format(ticker.lower())
tag_id = "yfs_l84_{}".format(ticker.lower())
if ticker == "end":
print"Good Bye"
elif ticker == "update":
update()
else:
run_price1()
【问题讨论】:
-
为什么不直接调用
run_price1而不是run_price并完全删除后者?你没有有在update中定义它。 -
我试过了,我更愿意这样做,但它不起作用。我收到错误 - NameError:未定义全局名称“web_address”
标签: python list function python-2.7