对外面的人来说,这会很简单,但对我来说,对于一个基本的新手来说,这让我头疼。
我需要一个用户输入一个教育等级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谢谢,克里斯
发布于 2017-04-19 18:13:43
使用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
breakhttps://stackoverflow.com/questions/43502851
复制相似问题