give me task on pyhton
- User
give me task on pyhton
- Assistant
Sure! Here's a Python task for you:
Task:
Write a Python program that takes a list of numbers as input and returns a new list containing only the prime numbers from the original list.Example:
Input:[2, 3, 4, 5, 6, 7, 8, 9, 10]
Output:[2, 3, 5, 7]
If you'd like, I can also help you with hints or solutions. Just let me know!
- User
def is_prime(n): """Check if a number is prime.""" if n <= 1: return False for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True
def filter_primes(numbers): """Return a list of prime numbers from the given list.""" return [num for num in numbers if is_prime(num)]
Example usage
input_numbers = [2, 3, 4, 5, 6, 7, 8, 9, 10] output_primes = filter_primes(input_numbers) print(output_primes) # Output: [2, 3, 5, 7]
- Assistant
Your code looks great! It correctly defines a function to check if a number is prime and then filters a list of numbers to keep only the primes. When you run it, the output will be:
[2, 3, 5, 7]If you'd like, I can suggest some improvements or additional features, such as:
- Handling invalid inputs (e.g., non-integer values)
- Making the program interactive (taking user input)
- Optimizing for larger numbers
Let me know if you'd like help with any of these!