Even elements. Given a list of numbers, find and print all elements that are even numbers. Use a for-loop that iterates directly over the list elements, not over their indices (i.e., do not use range()
).
|
numbers = input().split() for num in numbers: if int(num) % 2 == 0: print(num) |
Explanation of the Code
- Reading Input:
numbers = input().split()
- The
input()
function reads a line of text from the user.
- The
split()
method splits this line into a list of strings based on spaces and stores it in the variable numbers
.
- Iterating Through the List and Printing Even Elements:
for num in numbers:
if int(num) % 2 == 0:
print(num)
- Use a
for
loop to iterate through each element in the list numbers
.
- Convert each element to an integer using
int()
.
- If the integer is even (i.e.,
num % 2 == 0
), print the element.