【问题标题】:How to prevent a for loop from stopping?如何防止 for 循环停止?
【发布时间】:2019-03-27 01:32:54
【问题描述】:

在我的 for 循环中,当 if 语句都为真时,它会做它应该做的事情,然后它就结束并且不会继续整个循环。我尝试在柜台买卖后使用continue 声明。它在存储变量的总和时起作用,但后来我在返回变量上出现错误,显示内置模块的 NoneType 对象。

如果我省略 continue 语句,它只会存储与 if 语句匹配的第一个价格,但它会中断并停止汇总与这些语句匹配的其他价格。

我知道问题是它在添加计数器后从 for 循环中中断,也许是返回严重缩进?

buy = 0
sell = 0
def checking(x,y):
    for i in range (17):
        if x[i]>x[i-1]:
            if y[i] >y[i-1]:
                global buy, sell
                buy += y[i]
                try:
                    sell +=y[i+1]
                except:
                    sell +=y[i]

                continue
                return sell-buy

gains = checking(volume,close)

gains

我需要创建一个读取 2 个数据框的函数,一个是股票的交易量,另一个是收盘价。我希望该函数检查今天的交易量是否大于昨天的交易量,如果是这样,那么它会进入另一个 if 语句,询问今天的收盘价是否大于昨天的收盘价。如果这也是真的,那么它将那些日子的价格存储并汇总在“买入”变量中,并将 [i+1] 之后的一天的价格存储并汇总在“卖出”变量中。最后它返回这两者之间的差异。

【问题讨论】:

    标签: python pandas loops for-loop


    【解决方案1】:

    你是对的,return 语句的缩进是不正确的。这是固定的代码:

    buy = 0
    sell = 0
    def checking(x,y):
        for i in range (17):
            if x[i]>x[i-1]:
                if y[i] >y[i-1]:
                    global buy, sell
                    buy += y[i]
                    try:
                        sell +=y[i+1]
                    except:
                        sell +=y[i]
    
        return sell-buy
    
    gains = checking(volume,close)
    

    【讨论】:

    • @GuillermoCampollo 如果答案解决了您的问题,您可以投票并接受它。
    • 试图支持它,但它告诉我我需要 15 声望,不管这意味着什么。不过我已经接受了,再次感谢
    • @GuillermoCampollo 见What is reputation?Upvote privilege
    【解决方案2】:
    buy = 0
    sell = 0
    def checking(x,y):
        for i in range (17):
            if x[i]>x[i-1]:
                if y[i] >y[i-1]:
                    global buy, sell
                    buy += y[i]
                    try:
                        sell +=y[i+1]
                    except:
                        sell +=y[i]
    
    
        return sell-buy
    
    gains = checking(volume,close)
    

    【讨论】:

      猜你喜欢
      • 2022-01-11
      • 1970-01-01
      • 1970-01-01
      • 2021-04-16
      • 1970-01-01
      • 2016-03-10
      • 2018-07-13
      相关资源
      最近更新 更多