目前我正在为我的程序中的输入编写一些验证代码,我似乎无法正确显示错误消息!
我在字符串列表中定义了我的类型,如下所示:
types = ['Guitar','Piano','Drums','Violin','Voice','Flute','Cello','Bass']
然后我的验证检查代码是:
typevalid = False
while typevalid == False:
Type = input("Please enter the tutor type: ").title()
for count in range (0,7):
if Type == types[count]:
typevalid = True
Tutor = (Name,Type)
insert_data(Tutor)
print("New data added")
print()
if Type != types[count]:
print("!!Please enter a correct type!!\n")
add = input("Do you wish to add another record? (y/n) ")
我已尝试更改并移动第二个如果类型代码,它会重复错误X次数,因为范围循环或它将显示错误消息两次。
有关如何使其发挥作用的任何建议?
答案 0 :(得分:3)
一些建议:
types = ["guitar", "piano", ...] # note case
while True:
type_ = str(input("Please enter the tutor type: "))
if type_.lower() in types: # checks all items in types in one line
break # leave while loop
print("Please enter a correct type!") # only happens once per loop
您可以围绕此核心逻辑添加其他功能。如果您希望稍后返回大写字母,可以使用type_.capitalize()
。
答案 1 :(得分:0)
一些问题 - types
有8个元素,但for
循环超过range(0,7)
。最好重写为for count in range(len(types)):
更重要的是,你的第二个if
语句不起作用 - 每次检查一个Type
(在循环中或在循环外)。您需要做的是检查是否找不到任何内容。试试这个:
typevalid = False
while typevalid == False:
Type = input("Please enter the tutor type: ").title()
for count in range(len(types)):
if Type == types[count]:
typevalid = True
Tutor = (Name,Type)
insert_data(Tutor)
print("New data added")
print()
if typevalid == False:
print("!!Please enter a correct type!!\n")
add = input("Do you wish to add another record? (y/n) ")
注意:刚看到jonrsharpe的回复 - 它更清晰,但这可以解释当前代码中出现的问题。
答案 2 :(得分:0)
你永远不会脱离循环:
for count in range(0,7):
if Type == types[count]:
# need to add the following lines:
typevalid == True
break
另外一些建议:
不是手动循环types
,而是使用内置成员资格检查功能
in
if Type in types:
代替for count in range(...
更好的是,由于您一遍又一遍地检查types
,因此使用set
:set(['Guitar', 'Piano', ...])
或(在Python 2.7+中)使用效率更高{'Guitar', 'Piano', ... }
。
大写变量通常用于python中的类名。您应该使用小写名称。如果您想避免覆盖内置type
变量,请使用尾随下划线(type_
),或者只是让变量更具描述性(例如tutor_type
)
在提出这些建议后,您的代码将如下所示:
tutor_types = {'guitar', 'piano', 'drums', 'violin', 'voice', 'flute', 'cello', 'bass'}
while True:
tutor_type = input('Please enter the tutor type: ').lower()
if tutor_type in tutor_types:
# Valid input logic here
break # don't forget to break out of the loop
print('The error message the user receives after entering incorrect info!')