Lima
Lima

Reputation: 159

What is the differences between two codes?

What are the differences between the last lines? Why is the second one is correct, and the first one is not?

# 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

Upvotes: 0

Views: 173

Answers (2)

FLAK-ZOSO
FLAK-ZOSO

Reputation: 4137

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)

According to the Python 3.10 documentation any is defined like this:

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False

Code

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
   )

Upvotes: 0

jak123
jak123

Reputation: 362

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
   )

Upvotes: 3

Related Questions