Search code examples
pythoninputuser-input

Python and User Inputs - Values Not Resetting


I am running into trouble trying to work with user inputs in Python 3.4. In two different locations in my code, I am asking a user for an input and then checking it for validity. If the user inputs a correct value the first time (in this case, 0 or 1), this works perfectly. However, if the user inputs an incorrect value, causing the function to loop back to the beginning, the original input persists.

For example, if a user types "asdf," the "You have entered an invalid rule number" warning shows up, and the user is again prompted to type the rule. However, if the user then types a valid number, the code loops again, and a forcible cancellation gives me the following error:

File "", line 1, in File "/home/squigglily/gitstore/RCPSP-RAB/RCPSP.py", line 9, in main selected_rule = select_rule() File "/home/squigglily/gitstore/RCPSP-RAB/RCPSP.py", line 572, in select_rule if int(selected_rule) >= 0 and int(selected_rule) <= 1: ValueError: invalid literal for int() with base 10: 'asklawer'

The code that's giving me trouble:

def select_rule():
    selected_rule = 0
    selected_rule = input("\nPlease type the number corresponding with the " 
    "prioritization rule you would like to use: "
    "\n    0 - No prioritization, ignore all resource constraints"
    "\n    1 - Lowest task number prioritization\n")

    try:
        int(selected_rule) + 1 - 1
    except:
        print("\nYou have entered an invalid rule number.  Please try again.\n")
        select_rule()

    if int(selected_rule) >= 0 and int(selected_rule) <= 1:
        selected_rule = int(selected_rule)
        return(selected_rule)
    else:
        print("\nYou have entered an invalid rule number.  Please try again.\n")
        select_rule()

Solution

  • You are missing the return to the select_rule() function

    You can also do everything in one if

    if type(selected_rule) == int and int(selected_rule) >= 0 and int(selected_rule) <= 1:
        selected_rule = int(selected_rule)
        return(selected_rule)
    else:
        print("\nYou have entered an invalid rule number.  Please try again.\n")
        return select_rule()