简体   繁体   English

两个代码有什么区别?

[英]what is the differences between two codes?

What are the differences between the last lines?最后几行有什么区别? Why the second one is correct, and the first one is not?为什么第二个是正确的,而第一个不正确? Instead, it seems normal.相反,这似乎很正常。

# I wanted to write this code like this but it is false.Because of
# line 7 and 8.
def is_authorized(my_list,m_name):
    for num in range(len(my_list)):
        if my_list[num].name==m_name and my_list[num].authorized==True:
            return True
        else:
            return False


# program accepts this one. If indentation of line 16 same as line
# 13.

def is_authorized(my_list,m_name):
    for num in range(len(my_list)):
        if my_list[num].name==m_name and my_list[num].authorized==True:
            return True
    return False

First code第一个代码


The first code would check only the first item, since it will return a value ( True or False ) even if the if condition is false.第一个代码将只检查第一项,因为即使if条件为假,它也会返回一个值( TrueFalse )。

while True:
    if (condition):
        return True
    else:
        return False

As you can see above, the loop will be executed only once.正如你在上面看到的,循环只会执行一次。

Second code第二个代码


You will check all the array, and return False only if the condition is false for each num in range(len(my_list)) .您将检查所有数组,并且仅当num in range(len(my_list))每个num in range(len(my_list))的条件为 false 时才返回False

while True:
    if (condition):
        return True
    return False

You second code has applications really similar to the any() built-in function.您的第二个代码具有与any()内置函数非常相似的应用程序。

Any任何


The Python built-in function any() , linked above, is used like this:上面链接的 Python 内置函数any()用法如下:

>>> any([True, False, True])
True
>>> any([False, False])
False
>>> array = [1, 2, 3, 4]
>>> booleans = [element > 2 for element in array]
>>> any(booleans)

In your case, you can do something like the code suggested by jak123:在您的情况下,您可以执行类似于 jak123 建议的代码的操作:

def is_authorized(my_list,m_name):
    return any(
        item.name == m_name and item.authorized
        for item in my_list
   )

As mentioned, the for loop returns after the first item in the first case.如前所述,在第一种情况下,for 循环在第一项之后返回。 Consider simplifying your code:考虑简化您的代码:

def is_authorized(my_list,m_name):
    return any(
        item.name == m_name and item.authorized
        for item in my_list
   )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM