Stenchik
Stenchik

Reputation: 19

Closing a program when a condition is met

I am just starting out and can't figure this one out.

I am writing a program to do some simple calculations for me at school.

Different calculations will be accessible through input of simple numbers from 1 to X. Every number will call a function just for that calculation.

My problem is this: I want that if the user enters an empty string when prompted for a number, the program will ask the user to re enter a number for a certain amount of times before closing. Here's my code:

def pick_procedure():
    procedure = raw_input("> ")

    if not procedure:
        counter = 0
        print "Enter a value. "

        while counter <4:
            counter = counter + 1
            main()
            if counter == 4:
                break

def main():
    print "\nStudy helper 1.0.\n"
    print """Procedure list:

    1.Area of circle.
    2. Circumference of a circle.

    Please pick a procedure: """
    pick_procedure()

main()

No matter how many times an empty string is entered, the program does not close.

How to do it correctly and cleaner?

Upvotes: 1

Views: 88

Answers (2)

Martin Evans
Martin Evans

Reputation: 46759

As you say, you need to reorganise your code:

def pick_procedure(valid_choices):
    print "Enter a value. "

    for _ in range(4):    # prompt for a choice up to 4 times
        choice = raw_input("> ")

        if choice in valid_choices:
            return choice

    return None  # A valid choice was not entered


def main():
    print "\nStudy helper 1.0.\n"
    choice = 1

    while choice:
        print """Procedure list: 

1. Area of circle.

2. Circumference of a circle.

Please pick a procedure: """ 

        choice = pick_procedure(["1", "2"])

        if choice:
            print "Doing choice", choice

main()

The following approach makes use of a while choice loop to keep prompting if a valid choice is entered. If no choice is entered 4 times, the pick_procedure() function returns None causing the while loop to exit cleanly. If a valid choice is entered, it returns that choice.

I also pass the list of valid responses to the function, that way the function can be used for other questions simply by passing a different list of valid responses.

Upvotes: 1

gdaras
gdaras

Reputation: 10109

You created a vicious circle.

First time that procedure is false, pick_procedure calls main and then main calls again pick_procedure. It continues recursively.

If you just want to finish the program when an event is fired, you can use sys.exit(0) and your problems are solved.

Upvotes: 0

Related Questions