Python : Generate Random 500 number between 101, 999 and exclude prime numbers from it

python @ Freshers.in

Here’s a Python code snippet that generates a list of 500 random numbers between 11 and 99:

import random
random_numbers = [random.randint(101, 999) for _ in range(500)]
print(random_numbers)

To exclude prime numbers from the list comprehension, you can add a condition using a helper function to check if each number is prime or not. Here’s an updated code snippet that generates a list of 5 random numbers between 101 and 999, excluding prime numbers:

import random
def is_prime(num):
    if num < 2:
        return False
    for i in range(2, int(num**0.5) + 1):
        if num % i == 0:
            return False
    return True

random_numbers = []
while len(random_numbers) < 500:
    number = random.randint(101, 099)
    if not is_prime(number):
        random_numbers.append(number)

print(random_numbers)

In this code, the is_prime() function checks if a number is prime. It iterates from 2 up to the square root of the number and checks if the number is divisible by any of the values in that range. If a divisor is found, the number is not prime and the function returns False. Otherwise, it returns True.

The while loop continues generating random numbers between 11 and 99 until the list random_numbers has a length of 5. Each generated number is checked using the is_prime() function, and if the number is not prime, it is added to the list. Finally, the resulting list of non-prime random numbers is printed to the console.

Refer more on python here :

Author: user

Leave a Reply