0

I am writing a Python program to create projects on my computer for different programming languages. This starts off with the language for this specific project being chosen, and I was trying to do it in a way that handled errors reasonably well.

So far I have this code.

def prompt_user():
    print "Enter the number of the project you would like to create.\n"

    aOptions = ["1. Java", "2. C/C++", "3. Python", "4. Web"]
    for sOption in aOptions:
        print sOption

    try:    
        iOptionChosen = int(raw_input("> "))
        if not(1 <= iOptionChosen <= 4):
            raise ValueError
        else:
            return iOptionChosen
    except ValueError:
        print "\nInvalid value entered. Try again."
        prompt_user()

print prompt_user()

It works well for what I need it to do, except for the fact that after an exception is raised and the user is reprompted, it never reassigns the new variable to iOptionChosen. Why is this and is there a simple fix? It is so frustrating.

Thanks so much for the help!

user1472065
  • 115
  • 1
  • 10

2 Answers2

5

In the except case:

except ValueError:
    print "\nInvalid value entered. Try again."
    prompt_user()

you only call prompt_user recursively. Instead, you need to return the value it gives:

except ValueError:
    print "\nInvalid value entered. Try again."
    return prompt_user()
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • I will accept your answer as soon as I can! Quick question though, since I am new to programming. Why is the distinction between return prompt_user() and just prompt_user() important? – user1472065 Jun 09 '14 at 16:14
  • 2
    If you don't do something with the value returned by a function, it is thrown away. In this case you want to return the value, so you use `return`. In other situations you might store it in a variable. – kindall Jun 09 '14 at 16:17
1

You might consider adding a while to the logic; in this way you simply remain in the while loop until the input is valid.

user_deciding = True
while user_deciding:
    try:
        choice = int(raw_input("> "))
        if choice in list_of_choices:
            user_deciding = False
        else:
            raise ValueError
    except ValueError:
        print "Please make a valid choice."

handle_choice_made(choice)

Alternatively, you can use your if 5 > choice > 0 syntax, but it might be worthwhile to use a data structure that simply borrows against an existing list or dictionary instead of checking for a magic range that represents valid data entry.