简体   繁体   中英

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.

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)) .

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

You second code has applications really similar to the any() built-in function.

Any


The Python built-in function any() , linked above, is used like this:

>>> 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:

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. 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
   )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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