Problem with returning prime number in a simple calculation program

Discussion in 'Python' started by QHorizon@gmail.com, Mar 3, 2007.

  1. Guest

    Hello, I'm new to Python (I've learned everything up to iterators so
    far) and fairly new to Programming. This would be my first real
    program:

    #Coordinate Geometry (The whole program is not shown)

    import math
    import sys

    print "Welcome to the Coordinate Geometry Calculator!"
    print "Type 'terms' for a list of commands"

    def main():
    print
    command = raw_input("Command? ")
    if command == "terms":
    terms()
    main()
    elif command == "distance":
    distance()
    main()
    elif command == "slope":
    slope()
    main()
    elif command == "endpoint":
    endpoint()
    main()
    elif command == "midpoint":
    midpoint()
    main()
    elif command == "prime":
    prime()
    main()
    elif command == "quit":
    sys.exit
    else:
    print "Not a valid command"
    main()

    #...Declaring functions here...

    def prime():
    num = input("Number ")
    i = num - 1
    divcounter = 0
    while i > 1:
    if num % i != 0:
    divcounter += 1
    i -= 1
    if divcounter == num - 2:
    print num, "is a prime number"
    else:
    print num, "is not a prime number"

    #Start the program
    main()

    As it says in the title, I'm having trouble with the prime number
    function. It will print the sentence if the number is prime, but it
    if isn't, the program goes into a state in the terminal where the
    program never ends and you can just keep on typing. Maybe the else
    statement is ineffective? Any ideas on how to fix this?
    , Mar 3, 2007
    #1
    1. Advertising

  2. wrote:
    > [reformatted indentation]
    > def prime():
    > num = input("Number ")
    > i = num - 1
    > divcounter = 0
    > while i > 1:
    > if num % i != 0
    > divcounter += 1
    > i -= 1
    > if divcounter == num - 2:
    > print num, "is a prime number"
    > else:
    > print num, "is not a prime number"
    > [...]
    > As it says in the title, I'm having trouble with the prime number
    > function. It will print the sentence if the number is prime, but
    > it if isn't, the program goes into a state in the terminal where
    > the program never ends and you can just keep on typing.


    Sure thing. You designed the function to behave this way.

    Look at the while loop -- especially think what happens if
    (num % i == 0). i will never be decremented then and the function
    will not terminate.

    Try inserting print statements for debugging if you don't get what I
    meant here.

    > Maybe the else statement is ineffective?


    No one can read your thoughts. In which way effective?

    Regards,


    Björn

    --
    BOFH excuse #86:

    Runt packets
    Bjoern Schliessmann, Mar 3, 2007
    #2
    1. Advertising

  3. On Sat, 03 Mar 2007 15:36:36 -0800, QHorizon wrote:

    > Hello, I'm new to Python (I've learned everything up to iterators so
    > far) and fairly new to Programming. This would be my first real
    > program:
    >
    > #Coordinate Geometry (The whole program is not shown)
    >
    > import math
    > import sys
    >
    > print "Welcome to the Coordinate Geometry Calculator!"
    > print "Type 'terms' for a list of commands"
    >
    > def main():


    [snip big boring series of if...elif... statements]

    You're eventually going to run into a run time recursion error if you run
    that for long enough. Can you see why?

    A better way to do a command loop is something like this:


    def bad_command():
    # called when the user enters an unrecognized command
    print "Unknown command, please try again"

    class QuitException(Exception):
    # used for exiting the loop
    pass


    def main():
    # Make a "dispatch table" that maps the name of a command
    # (as typed by the user) with a function to call.
    dispatcher = {'slope': do_slope,
    'primes': do_primes,
    'quit': do_quit,
    # ... and more here
    }
    try:
    # loop forever (until we jump out of it)
    while True:
    cmd = get_command_from_user()
    # you have to write get_command_from_user yourself
    func = dispatcher.get(cmd, bad_command)
    result = func()
    print result
    except QuitException:
    print "Goodbye, come again soon!"


    Now you just need to define your individual functions do_slope, do_primes,
    etc. The only "special" one is do_quit.

    def do_quit():
    raise QuitException


    Now let's look at the do_primes function. (You call it "prime".)

    > def prime():
    > num = input("Number ")


    That's a good way to have malicious users do really, really really bad
    things to your PC.

    Safer is to do this:

    num = int(raw_input("Number "))

    > i = num - 1
    > divcounter = 0
    > while i > 1:
    > if num % i != 0:
    > divcounter += 1
    > i -= 1


    That's an inefficient algorithm, if it even works. I'm not sure that it
    works, and I'm too lazy to find out :)


    > if divcounter == num - 2:
    > print num, "is a prime number"
    > else:
    > print num, "is not a prime number"


    This will only work if divcounter happens to equal the original number
    less two. If it equals something else, nothing will be printed.

    Here's a simple algorithm to check if a number is prime.

    # Warning: untested.
    def do_primes():
    num = int(raw_input("Number ")
    if num <= 1:
    return "%n is not prime" % num
    if num == 2:
    return "%n is prime" % num
    elif num % 2 == 0:
    # even numbers other than 2 aren't prime
    return "%n is not prime" % num
    for i in range(3, num, 2):
    if num % i == 0:
    return "%n is not prime" % num
    return "%n is prime" % num


    Now, this is deliberately not an efficient algorithm. There are things you
    can do to make it more efficient, or you can re-write it completely.
    The thing to remember is, don't PRINT the result, RETURN it. Your
    do_primes() function should only calculate the result, and pass that
    result up to the main loop for printing (or writing to a text file, or
    emailing, or whatever).

    Have fun!



    --
    Steven.
    Steven D'Aprano, Mar 4, 2007
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. don

    prime number routine

    don, Feb 10, 2004, in forum: C++
    Replies:
    11
    Views:
    755
    Jonathan Turkanis
    Feb 11, 2004
  2. Cmorriskuerten

    Prime number algorithm in C

    Cmorriskuerten, Nov 17, 2003, in forum: C Programming
    Replies:
    33
    Views:
    54,387
    NaomiD
    Jul 22, 2009
  3. swisscheese

    Shortest prime number program

    swisscheese, Feb 11, 2006, in forum: Python
    Replies:
    19
    Views:
    633
    Tim Hochberg
    Feb 13, 2006
  4. Robert P. J. Day
    Replies:
    5
    Views:
    2,650
    mrdeath5493
    Jan 17, 2011
  5. Jeremy Fischer
    Replies:
    0
    Views:
    184
    Jeremy Fischer
    Jan 16, 2005
Loading...

Share This Page