简体   繁体   中英

Need more understanding on python statement :- return ["even", "odd"][num % 2]

Can someone please help me understand exactly how the logic is working in below statement of python -

return ["even", "odd"][num % 2]

This function is correctly returning even /odd values.

["even", "odd"] is a list with two elements, thus with the indexes 0 and 1.

It is indexed ( [] ) with num % 2 .

If num is even, num % 2 is 0 , and ["even", "odd"][0] is "even" .

If num is odd, num % 2 is 1 , and ["even", "odd"][1] is "odd" .

The % sign is the mathematical modulus function . num % 2 will return 0 when num is even, and 1 when num is odd. This value is then used to return the corresponding element of ["even", "odd"] .

It is simply returning a string. The proper value from list ["even", "odd"] is extracted using the remainder( num%2 ).

For example, let's say num is 4. So, num%2 is 0 . In this case the 0th element of the list (ie even ) will be returned.

Now if num is 5, the remainder will be 1 and the string in position 1 will be returned (in this case odd ). Notice there is no other possible outcome of num%2 even for negative numbers, so no chance of accessing an index which is out of range.

numbers_list = list(range(10))
def odd_even(any_list):
    odd = []
    even = []
    for element in any_list:
        if element % 2 == 0:
# 10 % 2 = 0, 10 % 3 = 1, 10 / 4 = 2(2) => 10 % 2 = 2
            even.append(element)
        else:
            odd.append(element)
    return odd, even
# there are two way for answers. first - when element % 2 = 0 , so this is even number
# and second - when element % 2 = 1, so this is odd number

print(odd_even(numbers_list))

# if we'll want to run the code output will like this:
# ([1, 3, 5, 7, 9], [0, 2, 4, 6, 8])

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