raw_input问题,在接受输入之前需要根据列表检查输入

时间:2017-04-19 17:53:29

标签: python-2.7

对于那里的人来说,这将非常简单,但对于我来说,基本的新水平让我头疼。

我需要用户输入教育等级A,B,C,D,E或F.

我希望小写或大写是可以接受的,但是对于任何其他输入值,它要循环直到它们为止。

到目前为止,我已经写过:

grades = (raw_input("Please enter your educational grade either as A, B, C, D, E or F: "))

# checking for truthiness
while grades != ("A", "a", "B", "b", "C", "c", "D", "d", "E", "e", "F", "f"):
    print ("The grade you entered does not conform.")
    grades = (raw_input("Please enter your educational grade either as A, B, C, D, E or F: "))

# display valid input
print ("Your input is valid, you entered:  "), grades

谢谢, 克里斯

1 个答案:

答案 0 :(得分:0)

使用str.upper()str.lower()将用于检查用户输入,但要保持一致,使其与while循环中列表中使用的大小写相匹配。这有点重复/多余,但我认为满足您的要求:

grades = raw_input("Please enter your educational grade either as A, B, C, D, E or F: ").upper()

while grades not in(["A", "B", "C", "D", "E", "F"]): 
    print ("The grade you entered does not conform.")
    grades = raw_input("Please enter your educational grade either as A, B, C, D, E or F: ").upper()

print ("Your input is valid, you entered: "), grades

或者,while True:循环版本完成相同的操作,但会在循环内移动提示用户输入,从而减少代码重复。

while True:
    grades = raw_input("Please enter your educational grade either as A, B, C, D, E or F: ").upper()
    if grades not in(["A", "B", "C", "D", "E", "F"]):
        print ("The grade you entered does not conform.")
    else:
        print ("Your input is valid, you entered: "), grades
        break