Python and User Inputs - Values Not Resetting
我在使用Python3.4中的用户输入时遇到了麻烦。在我的代码中的两个不同位置,我向用户请求输入,然后检查输入的有效性。如果用户第一次输入正确的值(在本例中为0或1),则此操作完全正常。但是,如果用户输入的值不正确,导致函数返回到开头,则原始输入将继续存在。
例如,如果用户键入"asdf",则会显示"您输入的规则编号无效"警告,并再次提示用户键入规则。但是,如果用户随后键入一个有效的数字,代码将再次循环,强制取消将导致以下错误:
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'
给我带来麻烦的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | def select_rule(): selected_rule = 0 selected_rule = input(" Please type the number corresponding with the" "prioritization rule you would like to use:" " 0 - No prioritization, ignore all resource constraints" " 1 - Lowest task number prioritization ") try: int(selected_rule) + 1 - 1 except: print(" You have entered an invalid rule number. Please try again. ") select_rule() if int(selected_rule) >= 0 and int(selected_rule) <= 1: selected_rule = int(selected_rule) return(selected_rule) else: print(" You have entered an invalid rule number. Please try again. ") select_rule() |
因为您不返回递归调用的结果,比如:
1 | return select_rule() |
在
只需返回上面所示的递归结果,它就可以工作了。
您缺少对select_rule()函数的返回
如果
1 2 3 4 5 6 7 8 | 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(" You have entered an invalid rule number. Please try again. ") return select_rule() |