Print Primes 1 to N

Print all prime numbers from 1 to n.

Logic BuildingIntermediate
Logic Building
# Helper function
def is_prime(n):
    if n < 2:
        return False
    for i in range(2, int(n ** 0.5) + 1):
        if n % i == 0:
            return False
    return True

# Take n
n = int(input("Enter n: "))

# Print primes
print(f"Primes from 1 to {n}:")
for num in range(1, n + 1):
    if is_prime(num):
        print(num, end=" ")
print()

Output

Enter n: 20
Primes from 1 to 20:
2 3 5 7 11 13 17 19

Loop through range and check each number.

Key Concepts:

  • Use helper function
  • Loop from 1 to n
  • Check and print primes