well I am learning on Udemy and I couldn't figure out why the result of this lines of code:
numbers = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
result = [num 3 for num in numbers if num % 2 == 0]
print(result)
are [5, 11, 37] and not [4, 4, 6, 8, 16, 24, 58]?
thank you for helping.
CodePudding user response:
if num % 2 == 0
means that you only want to execute the code if num is even. That way only the 2,8 and 34 are added to the list and incremented by 3.
The answer you expect (only the odd numbers incremented by 3) is when the last bit is like this:
if num % 2 != 0
CodePudding user response:
for num in numbers
iterates over elements of the list.
if num % 2 == 0
restricts to even numbers.
So you end up by adding 3 to : 2, 8 and 34 which gives the expected result.
A more explicit loop would be :
numbers = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
result = []
for num in numbers:
if num%2 == 0: # if it's even
result.append(num 3)
print(result)