Function for prime numbers

Viewed 118

Im having a problem with an excercise in python. I should get a function is_prime(n): to define prime numbers. the program should give 3 types of output; 1. n is the multiplicative identity 2. n is not a prime number (n * d = n). 3. n is a prime.

im having a problem to get the 2. work right my output is: 12 is not a prime number.(2, '*', 6, '=', 12)

but should be

12 is not a prime number (2 * 6 = 12).

my code;

def is_prime(n):
    msg1 = "is the multiplicative identity."
    msg2 = "is not a prime number."
    msg3 = "is a prime."
    if n == 1:
        return str(n) + msg1

    for d in range(2, n):
        msg4 = (d, "*", n // d, "=", n)
        pass
        if (n % d) == 0:
         return str(n) + " " + msg2 + str(msg4)

else:
    return str(n) + " " + msg3

print(is_prime(12))
2 Answers

Use string formatting to return instead of concatenation.

This is using f string formatting:

return f'{n} {msg2} {msg4}'

Anything inside the brackets {} is going to be evaluated like standard Python should be or will return that value. It will be converted to a string on it's own so you don't need to str() on it.

All code:

def is_prime(n):
    msg1 = "is the multiplicative identity."
    msg2 = "is not a prime number"
    msg3 = "is a prime."
    if n == 1:
        return f'{n} {msg1}'
    for d in range(2, n):
        msg4 = f'({d} * {n // d} = {n})'
        if (n % d) == 0:
            return f'{n} {msg2} {msg4}.'
    return f'{n} {msg3}'

print(is_prime(12))

Please use below code as you need to use str() function in order to print the expected result.

msg4 = str(d) + '*' + str(n // d) +'='+ str(n)

If you want to use () then below is the whole code.

def is_prime(n):
    msg1 = "is the multiplicative identity."
    msg2 = "is not a prime number."
    msg3 = "is a prime."
    if n == 1:
        return str(n) + msg1

    for d in range(2, n):
        msg4 = "(" + str(d) + '*' + str(n // d) +'='+ str(n)+ ")"
        pass
        if (n % d) == 0:
            return str(n) + " " + msg2 + str(msg4)

        else:
            return str(n) + " " + msg3
Related