asked 222k views
3 votes
Even or Odd Tuple: Create a program that takes a tuple of integers as input and returns a new tuple containing the numbers that are even or odd.

Your program should:

- Ask the user for a comma-separated list of integers.

- Your program should create a tuple from the list of integers.

- Define a function that takes the tuple as input and returns a new tuple containing the even or odd numbers.

- Ask the user to filter for odd or even numbers.

- If even, display True.

- If odd, display False.

- Display the resulting tuple.


Could someone help me with this?

This is a python exercise by the way!!!

asked
User Fugogugo
by
8.6k points

1 Answer

1 vote

Sure! Here's a Python program that satisfies the requirements:

# Ask user for comma-separated list of integers

input_str = input("Enter a comma-separated list of integers: ")

# Convert input string to tuple of integers

int_tuple = tuple(map(int, input_str.split(",")))

# Define function to filter even or odd numbers

def filter_even_odd(num_tuple, is_even):

if is_even:

return tuple(filter(lambda x: x % 2 == 0, num_tuple))

else:

return tuple(filter(lambda x: x % 2 != 0, num_tuple))

# Ask user to filter for even or odd numbers

even_or_odd = input("Do you want to filter for even or odd numbers? (enter 'even' or 'odd'): ")

# Filter tuple for even or odd numbers

if even_or_odd.lower() == "even":

result_tuple = filter_even_odd(int_tuple, True)

print(True)

else:

result_tuple = filter_even_odd(int_tuple, False)

print(False)

Here's an example output:

# Display resulting tuple

print(result_tuple)Enter a comma-separated list of integers: 1,2,3,4,5,6,7,8,9

Do you want to filter for even or odd numbers? (enter 'even' or 'odd'): even

True

(2, 4, 6, 8)

In this example, the user enters a comma-separated list of integers, and the program converts it into a tuple of integers. Then, the program defines a function that filters even or odd numbers from a given tuple. The user is prompted to filter for even or odd numbers, and the program calls the function accordingly. Finally, the program displays the resulting tuple.

answered
User Guinn
by
7.8k points