0

我在尝试编写的程序时遇到了真正的麻烦。如下所示的代码应该要求用户输入,然后连续打印结果,直到输入非法值。在我的代码设计中,我可以使答案无限循环,或者如下所示,询问两次并退出。我怎样才能循环这个函数来做我想做的事?非常感谢!

#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()
4

3 回答 3

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!".
于 2013-10-15T17:03:49.170 回答
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) 
于 2013-10-15T17:08:46.760 回答
-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'
于 2013-10-15T18:09:56.567 回答