【问题标题】:Why this Loop Logic by using .request does not work properly?为什么这个使用 .request 的循环逻辑不能正常工作?
【发布时间】:2021-10-12 11:10:04
【问题描述】:

谁能帮我解释一下我的逻辑有什么错误?

目标: 得到结果后(可以通过输入 f.e ibm 找到 url),我想通过input 输入另一个stock 符号。我不想总是从头开始执行这个小程序。

我尝试使用 try&except 来完成,而 for[if]、继续、通过、中断。

要么我得到结果

  1. 多次
  2. 只得到“无数据”
  3. 一个空的数据框 --> []

无论我得到什么,我都想在执行第一个 while 循环后使用另一个 input。

stock = input("Please enter a ticker symbol: ")
url = f"https://www.alphavantage.co/query?function=EMA&symbol={stock}&interval=weekly&time_" \
      f"period=10&series_type=open&apikey=MyAPI"
request = requests.get(url)
data = request.json()
df = pd.DataFrame(data)
#pd.set_option('display.max_columns',37)

while request.raise_for_status() == 200:
  print(df.head(37))
  print(input("Please enter a ticker smybol: "))
  if request.raise_for_status() != 200:
     print("no data")
     print(input("Please enter a ticker smybol: "))

非常感谢

【问题讨论】:

    标签: html pandas loops while-loop request


    【解决方案1】:

    你的循环放错了地方。这是一个工作示例。 如果您在没有输入的情况下输入 enter,则结束,如果您输入有效股票,则打印数据框,如果股票无效,则打印“无数据”。

    import requests
    while True:
        # get user input, expects a ticker symbol (e.g. ibm)
        stock = input("Please enter a ticker symbol: ")
        print('checking stock:', stock)
        # if user pressed enter (empty string), then finish
        if not stock:
            break # this breaks out of the while loop
        # craft URL, request the webpage and create the dataframe from the JSON data
        url = f"https://www.alphavantage.co/query?function=EMA&symbol={stock}&interval=weekly&time_" \
              f"period=10&series_type=open&apikey=MyAPI"
        request = requests.get(url)
        data = request.json()
        df = pd.DataFrame(data)
        # if there is data, df.size will be greater than 0
        if df.size: # this is equivalent to df.size > 0
            print(df)
        else:
            print('no data')
    # we are out of the loop
    print('end')
    

    注意。此时无需添加进一步验证,但如果需要,您可以将请求包装在 try/except 块中。

    【讨论】:

    • 感谢您的工作 :) 不幸的是,它无法正常工作...因为如果您输入 fe 'ibm',结果必须找到它,但它不会...它会导致 'Process以退出代码 0' 完成...我将 import pandas as pd 添加到您的方法中,因为 df = pd.Dataframe(data).它似乎在 print('checking stock:', stock) 之前就已经停止了
    • 我在 jupyter notebook 中测试了代码,它对我来说运行良好。我得到了 IBM 的数据,垃圾的“无数据”,在空白输入后停止
    • 它有效,谢谢 :) 但老实说我不明白......在 True 期间:.. 代码分别从哪里知道从哪里寻找?在测试“if not stock:”之前没有网址?
    • 'if not stock' 测试用户输入是否为空并在这种情况下中断循环。然后它制作 url,发出请求,数据测试发生在“if df.size”,如果数据框为空,则为 0。
    • 我对代码进行了注释,以便您更轻松地了解发生了什么。让我知道这是否适合您。缩进在 python 中很重要,所以一定要复制/粘贴代码,就像这里一样;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多