Exercise 6.2
← Previous Module 6: Functions Next →
Statement
Solution

Python Exercise 6.2: Prime Number Generator

Write a function that returns a list of all prime numbers up to n.

Your program should:

  • Define a function get_primes(n) that returns a list of primes ≤ n.
  • Use a loop to check divisibility.
  • Test with user input for n.

Sample Interaction:

Input
Output
10
[2, 3, 5, 7]

Solution

Here is one way to generate prime numbers using a function.

def get_primes(n): primes = [] for num in range(2, n+1): is_prime = True for i in range(2, int(num**0.5) + 1): if num % i == 0: is_prime = False break if is_prime: primes.append(num) return primes # Test the function n = int(input("Enter n: ")) print(get_primes(n))

Key Concepts:

  • Functions can return lists.
  • Nested loops for checking primality.
  • range(2, int(num**0.5) + 1) optimizes the check.
Python 3
Test Console
Run code to see output...

Go Beyond Learning. Get Job-Ready.

Build in-demand skills for today's jobs with free expert-led courses and practical AI tools.

Explore All Courses
Scroll to Top