我无法通过while
声明:
letter_grade=input("What is your letter grade(please use capitlization): ")
while letter_grade!="A" or "B+" or "B" or "C+" or "C" or "D" or "F":
print ("Enter a valid letter")
letter_grade=input("What is your letter grade(please use capitlization): ")
答案 0 :(得分:1)
试试这个:
letter_grade=input("What is your letter grade(please use capitlization): ")
while letter_grade not in ["A","B+","B","C+","C","D","F"]:
print ("Enter a valid letter")
letter_grade=input("What is your letter grade(please use capitlization): ")
您当前的代码无法正常工作,因为您无法像您一样简化布尔语句。为了使你的工作成功,你必须将其改为:
letter_grade!="A" and letter_grade!="B+" and #etc.
您必须针对变量测试每个字母。
答案 1 :(得分:1)
您似乎不理解逻辑语句的工作原理。您的行定义为:
while letter_grade!="A" or "B+" or "B" or "C+" or "C" or "D" or "F":
这总是返回true,因为它并不意味着你想要它。你想使用类似的东西:
while letter_grade!="A" and letter_grade!="B+" and letter_grade!="B": #etc
但为了便于阅读,我建议使用代码:
letter_grade=input("What is your letter grade(please use capitlization): ")
possible_grades = {"A","B+","B","C+","C","D","F"}
while letter_grade not in possible_grades:
print ("Enter a valid letter")
letter_grade=input("What is your letter grade(please use capitlization): ")
请注意,使用集合可以加快查找速度。