Chapter 4: Refactoring

Refactoring your prime number generator

face Josiah Wang

Ok, now below I have my code for my prime number generator from Lesson 4. Recall that the task is to read a “maximum number” from the user, and print out all prime numbers from 1 to this maximum number. A much more complex program than checking whether a single number is prime.

last_number = int(input("Please enter an integer: "))
n = 2
while n <= last_number:
    divisor = 2
    is_prime_number = True

    while divisor < n:
        if n % divisor == 0:
            is_prime_number = False
            break
        else:
            divisor = divisor + 1

    if is_prime_number:
        print(n)

    n = n + 1

Again, the code looks quite complicated! It takes time to understand what my code is doing!

But wait, do some bits actually look familiar? Did we not have something like this earlier in our is_prime_number() function?

Can we reuse that function then? There is a principle in Software Engineering called Don’t Repeat Yourself (DRY). So always reuse when possible!

Over to you (again!)

Now, try refactoring the prime number generator program.

Reuse your existing functions like is_prime_number() and read_integer() from the previous page as much as possible. I have provided my implementation below for your convenience, but feel free to use your own version. Remember - make it as easily understandable and readable as you can!

You might also find it easier to just rewrite the prime number generator (using your existing functions), rather than attempting to modify the code above. Go for it if that is easier for you!

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
def read_integer():
    entry = input("Please enter an integer: ")
    return int(entry)


def is_divisible_by(number, divisor):
    return number % divisor == 0


def is_prime_number(number):
    if number <= 1:
        return False

    divisor = 2
    while divisor < number:
        if is_divisible_by(number, divisor):
            return False
        else:
            divisor += 1
    return True


n = read_integer()
if is_prime_number(n):
    print(f"{n} is a prime number")
else:
    print(f"{n} is not a prime number")

Try this before moving on. Remember to test that your code works correctly once you are done!