在Python中,如果用户输入的值不正确,如何使输入验证继续循环

时间:2014-07-16 01:34:14

标签: python python-3.x

如果用户输入的数字低于0或高于100或未输入整数,如何让我的代码循环回输入(并再次检查值)

NameList = []
Name1List = []
def Va():
    while True:
        try:
            int(NameMSplit[1])
            if int(NameMSplit[1]) > 0 and int(NameMSplit[1]) < 100:
                return NameMSplit[1]
            else:
                print ("Number is not between 0 and 100")
        except ValueError:
             print("Please make sure it's a number ")

#Main Code
NameMarks = input("Please input your name followed by your marks seperated by spaces ")
NameMSplit = NameMarks.split()
V = Va()
while NameMarks != 'Q':
    Name =(NameMSplit[0])
    Name1 = (NameMSplit[1])
    NameList.append(Name)
    Name1List.append(Name1)
    NameMarks = input("Please input your name followed by your marks seperated by spaces ")
    NameMSplit = NameMarks.split()
print (Name1List, NameList) 

1 个答案:

答案 0 :(得分:0)

您可以在函数中包含输入,如下所示:

def Va():
    while True:
        NameMarks = input("Please input your name followed by your marks seperated by spaces ")
        NameMSplit = NameMarks.split()
        try:
            int(NameMSplit[1])
            if int(NameMSplit[1]) > 0 and int(NameMSplit[1]) < 100:
                return NameMarks
            else:
                print ("Number is not between 0 and 100")
        except ValueError:
             print("Please make sure it's a number ")

#Main Code
NameMarks = Va()
...