【问题标题】:At which level do return statements need to be written if there is also an 'if' statement above it?如果上面还有一个'if'语句,return语句需要写在哪个级别?
【发布时间】:2017-10-13 18:08:29
【问题描述】:

让我先说我对编码还很陌生,所以要温柔。

我一直在写以下内容:

def execute_move(player, house_choice, houses):

next_house=houses[house_choice]
chosen_house=houses[house_choice-1]
chosen_house_seeds=chosen_house[1]
for i in range(chosen_house_seeds):
    if player=='P1': # skips the store of the opposite player
        if next_house==houses[13]:
            next_house_index=houses.index(next_house) 
            new_nhi=next_house_index+1
            next_house=houses[new_nhi]
    elif player=='P2':
        if next_house==houses[6]:
            next_house_index=houses.index(next_house) 
            new_nhi=next_house_index+1
            next_house=houses[new_nhi]
    [(next_house[0], (next_house[1]+1)) if x==next_house else x for x in houses]
    next_house_index=houses.index(next_house) 
    new_nhi=next_house_index+1
    next_house=houses[new_nhi] 
[(chosen_house[0], (chosen_house[1]-chosen_house_seeds)) if x==chosen_house else x for x in houses]
return houses

我的目标是替换列表“houses”中的一些元组,然后返回新的元组列表。

由于某种原因,我稍后在代码中分配调用的 var 仅在打印时生成原始列表。

我认为这可能与'if'语句的缩进或return语句的缩进有关。

非常感谢您的帮助!

【问题讨论】:

    标签: python return indentation


    【解决方案1】:

    与其他 Python 语句相比,return 语句本质上没有什么特别之处。

    因此,您应该像其他任何操作一样缩进它(即,将return 行放在对您的特定算法有意义的块内)。

    【讨论】:

      【解决方案2】:

      任何控制结构(例如 if 语句)都希望下一行缩进。当代码开始回到原来的层次时,控制结构就结束了

      https://docs.python.org/3/reference/lexical_analysis.html#indentation

      def function(input):
          input = input * 2
          if (input > 5):
              input * 2
              return input
          input +1
          return input
      

      所以在这种情况下,如果输入 2.5,则返回 * 4

      这可能只是一个糟糕的剪切和粘贴,但函数的主体也必须缩进。

      【讨论】:

        【解决方案3】:

        你的列表理解语句,那些看起来像 [(next_house[0], ...] 的语句正在构建列表,但它没有分配给任何东西,所以它被丢弃了。尝试将结果设置为变量...

        list_of_next_house_tuples = [(next_house[0], (next_house[1]+1)) if x==next_house else x for x in houses]
        

        然后确定你要如何处理这个新列表。

        【讨论】:

        • 谢谢!这就是解决办法。
        猜你喜欢
        • 1970-01-01
        • 2017-02-05
        • 1970-01-01
        • 2018-08-24
        • 2022-12-09
        • 2017-08-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多