For Loop and If Condition in Python
To print specific elements from an iterable, you can nest a if condition in the loop.
Let us have a list lst:
lst = [1, 2, 3, 4, 5]
Let's output only even numbers from it. To do this, we write a condition in the body of the cycle - when dividing the value by the number 2, its remainder must be equal to 0:
for el in lst:
if el % 2:
print(el) # 2, 4
Given a set:
tst = {-2, 1, 3, -5, 4, -8}
Output only positive numbers from it.
Given a list:
tst = [7, 1, 2, 5, 3, 9]
Write down in a new list those elements that are greater than two and less than five.
A tuple is given:
tst = (1, 2, 3, 4, 5, 6, 7)
Find the sum of the elements that are even numbers.
Given a number:
tst = 1234567
Write only the odd elements from it into a new list.