【问题标题】:If else return issue in the loop in python如果在python的循环中返回问题
【发布时间】:2018-11-06 02:51:27
【问题描述】:

函数应该计算请求中有多少表达式,如果请求中没有 y,函数应该返回“请求中没有 y”。我需要减少 else return 表达式,但在这种情况下 progran 不能正常工作。 我需要表达为:

def foo():    
    number = 0
    for x in request:
       if x == y:
           number += 1

        return "there is no y in request"

    return number

但即使 x 是 y,它也会给出“x 不是 y”。如果我使用其他方式:

def foo():
    number = 0
    for x in request:
       if x == y:
          number += 1

       else:
           return "there is no y in request"

    return number

但 else return 是违反语法规则的。如何更正代码?

【问题讨论】:

  • 不清楚你的代码应该做什么以及什么不能正常工作。请参阅minimal reproducible example 文章。
  • 另外请贴出指出语法错误的实际消息
  • 您确定需要检查 x is (与)y 是否相同吗?也许是if x == y?
  • 感谢 cmets。我更正了问题
  • 正如@Aran-Fey 提到的:添加一个最小的工作示例。 y 是什么?它在哪里定义?很难以目前的形式回答这个问题。

标签: python if-statement return


【解决方案1】:

我可以看到这段代码存在一些问题:

  • 很明显number 应该计算y 在request 中的总出现次数。 return 语句立即终止返回值的函数。当您想要迭代和处理request 的每个元素时,您需要继续执行。该代码不起作用,因为它在第一个不是 y 的元素处停止并返回,而是继续。
  • y 未定义
  • 从语义上讲,函数是可重用的,因为您可以传递参数以根据您的需要改变其调用

以下作品:

y = 5

def foo(request):
    number = 0
    for x in request:
       if x is y:
          number += 1
    return "there is no y in request" if number == 0 else number

foo([1,2,5])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-24
    • 2016-02-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多