我正在尝试编写的程序遇到麻烦。如下所示的代码应该询问用户输入,然后连续打印结果,直到输入非法值。在我的代码设计中,我可以无限制地进行应答循环,或者如下所示,请求两次并退出。我怎样才能循环这个功能来做我想要的呢?非常感谢!
#define the function getLetterGrade and enter conditions of the function
def getLetterGrade (numGrade):
if numGrade >= 95 and numGrade <= 100:
print (" A+")
elif numGrade >= 90 and numGrade <95:
print (" A")
elif numGrade >= 85 and numGrade <90:
print (" A-")
elif numGrade >= 80 and numGrade <85:
print (" B+")
elif numGrade >= 75 and numGrade <80:
print (" B")
elif numGrade >= 70 and numGrade <75:
print (" B-")
elif numGrade >= 65 and numGrade <70:
print (" C+")
elif numGrade >= 60 and numGrade <65:
print (" C")
elif numGrade >= 55 and numGrade <60:
print (" C-")
elif numGrade >= 50 and numGrade <55:
print (" P")
elif numGrade < 50 and numGrade >=0:
print (" F")
elif numGrade < 0 or numGrade > 100:
print (" invalid, please enter a score between 0 and 100.")
def main():
#Ask the user for input
numGrade = eval(input("Enter your mark in percent"))
while numGrade >= 0 or numGrade <= 100:
print("The grade for", numGrade, "is", end = '')
getLetterGrade(numGrade) # Call the function getLetterGrade as defined above
break
numGrade = eval(input("Enter your mark in percent"))
while numGrade >= 0 or numGrade <= 100:
print("The grade for", numGrade, "is", end = '')
getLetterGrade(numGrade) # Call the function getLetterGrade as defined above
break
if __name__ == '__main__':
main()
答案 0 :(得分:0)
# Loop until the mark inserted is not correct
numGrade = input("Enter your mark in percent")
while numGrade >= 0 or numGrade <= 100:
print("The grade for", numGrade, "is", end = '')
getLetterGrade(numGrade) # Call the function getLetterGrade as defined above
numGrade = input("Enter your mark in percent")
print "Invalid mark. Bye!".
答案 1 :(得分:0)
使用while True
并在输入非法值时从循环中断。
def main():
while True:
num_grade = input("Enter your mark in percent")
if num_grade < 0 or num_grade > 100:
break
print("The grade for", num_grade, "is", end = '')
get_letter_grade(num_grade)
答案 2 :(得分:-1)
我的解决方案
>>> def get_grade_input():
... val = int(raw_input("Enter Grade:"))
... return val if 0 <= val <= 100 else -1
...
>>> grades = list(iter(get_grade_input,-1))
>>> def get_grade(pct_grade):
... return "FDCBA"[(pct_grade-50)//10]
...
>>> get_grade(66)
'D'
>>> get_grade(73)
'C'