How to print prime numbers in Python

Published on Aug. 22, 2023, 12:16 p.m.

To print prime numbers in Python, you can use a loop and a conditional statement to check if each number in a given range is divisible by any number other than 1 and itself. If a number is not divisible by any such number, it is a prime number and can be printed out in the loop. Here’s an example code to print all prime numbers between two numbers entered by the user:

lower_val = int(input("Enter the lower range value: "))
upper_val = int(input("Enter the upper range value: "))

print("Prime numbers between", lower_val, "and", upper_val, "are:")

for num in range(lower_val, upper_val + 1):
    if num > 1:
        for i in range(2, num):
            if (num % i) == 0:
                break
        else:
            print(num)

In this code, we first ask the user to input the lower and upper range values. We then use a for loop to iterate through each number in the given range. For each number, we use an inner for loop to check if it is divisible by any number other than 1 and itself. If it is not divisible by any such number, it is a prime number and can be printed out using the print() function.

Note that this code assumes that the user inputs an integer for the lower and upper range values. You may want to add additional input validation code to ensure that the user inputs only valid integer values. Also note that this approach can become very slow for very large ranges of numbers, since it checks each number individually. There are more optimized algorithms for finding prime numbers if performance is a concern.

Tags:

related content