0

I recently started learning python (by which I mean, 35 minutes ago at the time of posting...) and I've wrote a few things e.g. square root generator, factorial generator, Fibonacci number generator, prime checker etc. After I wrote the prime checker, I thought I'd try modifying it so that instead of checking every number in the specified range, it would accept an input and check that one specifically.

DISCLAIMER: If I were better at Python then I would only check numbers up to sqrt(p) and I would add an option to check if it is even and not 2 then it automatically returns that it's not prime but let me walk before I run! :)

CODE:

p = input("Enter a potential prime.")

for n in range (2,p):
    if p % n == 0:
        print(p, "equals", n, "x", p//n, "so it isn't a prime number")
        break
else:
    print(p, "is a prime number.")

It works for p = 2 but that's it...

NB - Obviously the code is indented accordingly, it's just not formatted properly here.

Shashank
  • 13,713
  • 5
  • 37
  • 63
PythonNewbie
  • 43
  • 1
  • 4
  • For future reference, to format code properly, copy paste it here, highlight and control/cmd+k or press the button that looks like `{ }` – Shashank May 03 '15 at 18:20
  • http://meta.stackexchange.com/questions/22186/how-do-i-format-my-code-blocks – jgritty May 03 '15 at 18:20
  • 2
    Whats your question though? – rafaelc May 03 '15 at 18:24
  • Your code actually works fine in Python 2.x. In Python 3.x, you would need to cast the return value of input to int first. So, like Rafael, I'm not sure what your question is. – Shashank May 03 '15 at 18:31
  • Here's a video that might help you write some code: https://youtu.be/kcuLJXF44Dw?t=1m30s – jgritty May 03 '15 at 18:39
  • Check this. This is probably the best https://stackoverflow.com/a/71438297/3204942 – Gary Mar 11 '22 at 12:15

1 Answers1

2

I see some errors: You need to convert your user input to an int, plus you need to move the else: clause to beneath your for-loop instead of beneath your if-statement. The following code works for what you want:

p = int(input("Enter a potential prime."))
for n in range (2,p):
    if p % n == 0:
        print(p, "equals", n, "x", p//n, "so it isn't a prime number")
        break
else:
    print(p, "is a prime number.")

Yes, this is correct - the else: is NOT part of the if-statement, it is part of your for-loop. This syntax means that if your for-loop runs to a break, then it'll break as normally. If there is no break, then the else: clause will be executed. Thus, it'll do the basic trial division, and if the number passes the test, it'll print "is a prime number" only once. The code you posted will print "is a prime number" for every iteration of your loop.


Edit: Try the following code for your followup question.

def primeChecker():
    # Function that keeps prompting for input, and checks if it's prime. Enter "quit"
    # to exit:
    user_input = input("Enter a potential prime (or type 'quit' to exit): ")
    if user_input == 'quit':
        return
    else:
        p = int(user_input)

    # Trial division algorithm:
    for n in range (2,p):
        if p % n == 0:
            print(p, "equals", n, "x", p//n, "so it isn't a prime number")
            break
    else:
        print(p, "is a prime number.")

    # Recursive function call:
    primeChecker()

# Start by calling the main function:   
primeChecker()
AdmiralWen
  • 701
  • 6
  • 16
  • I know the else is part of the for-loop. I have the else at the same point in my code... I did implement your correction, thanks! Is there any easy way to loop back the script to the input so that you can enter another potential prime after the first has been checked? – PythonNewbie May 03 '15 at 19:40
  • Why not make your prime test a recursive function? At the end of the function, simply call the main function again. – AdmiralWen May 03 '15 at 20:11
  • I would but that's like telling me to drive a car by starting the engine and driving it. I have no idea how to do that. I tried Google but none of the pages on recursion are particularly informative about the general case, they tend to describe specific examples. – PythonNewbie May 05 '15 at 16:34
  • I edited my answer for what you need. You can define a function and call the function within itself (this is called recursion). I'm not sure if you have other programming experience; if not, you should start learning more basic stuff, like how functions work, before writing recursive ones. I think you should be able to understand the code from just reading it. – AdmiralWen May 05 '15 at 19:00