检查字符串是否正确输入

时间:2019-04-12 12:26:15

标签: python python-3.x

我正在做一项活动以扩展现有代码以检查用户输入,而我无法使其正常工作。

  • 第一次尝试:
while 5 > appcounter:
    StudentGender.append (input(StudentName[namecount]+",Please Enter Student Gender M or F:"))
    if StudentGender[appcounter] == "M":
        appcounter = appcounter + 1
        namecount = namecount + 1
    elif StudentGender[appcounter] == "F":
        appcounter = appcounter + 1
        namecount = namecount + 1
    else:
        print("Not a valid input")
  • 第二次尝试
for Counter in range (ConstNoStudents+1):
    try:
        StudentGender[Counter] = (input(StudentName[namecount]+",are you Male or Female, Please use M or F:") )
        StudentGender[Counter] = "M" or "F" or "f" or "m"
        namecount = listcount+1
    except:
        print("That is not a valid number")

理想情况下,我希望它能识别用户输入的类型不是M或F in,并让用户重新输入该值,而无需在列表中添加任何其他内容

3 个答案:

答案 0 :(得分:1)

您需要在循环中获取输入,并检查是否输入了正确的值之一,如果没有输入,请重复该循环。

您也可以将<?xml version="1.0" encoding="ISO-8859-1"?> <LATree> <LA className="BTT00NE" fdn="NE=9739"> <attr name="fdn">NE=9739</attr> <attr name="IP">10.157.144.100</attr> <attr name="realLatitude">0D0&apos;0&quot;S</attr> <attr name="realLongitude">0D0&apos;0&quot;W</attr> <attr name="DaylightSaveInfo">NO</attr> </LA> </LATree> 应用于性别选择,而不必指定性别值的小写版本。

.upper()

答案 1 :(得分:1)

使用此模式:

accepted_inputs = ["M", "F"]
while True:
    user_input = input("message")
    if user_input in accepted_inputs:
        break
    print("Bad input, try again")

答案 2 :(得分:1)

重新排列代码,如果用户输入无效,则需要再次提示用户。您可以使用while循环进行此操作:

for index in range(ConstNoStudents+1):
    input = input(StudentName[index]+", are you Male or Female, Please use M or F:")
    while not input.upper() in ["M", "F"]:
        input = input("Invalid input. Please use M or F :")
    StudentGender[index] = input
相关问题