如何在函数中的while循环中获取函数才能正常工作?

时间:2014-12-16 10:46:01

标签: python

我已经看过并寻找答案,但我是python的新手,我发现的答案似乎超出了我的想法或者不是我需要的。我正在尝试将我的代码转换为多个函数,以完成从用户接收一些成绩并将输入显示回用户所需的简单任务。希望当你看到我的代码时,这将更加清晰。

import sys

gradeList = []

def validate_input():
    try:
        gradeList.append(int(grades))
    except:
        return False
    else:
        return True

def average(count, total):
    ave = total / count
    return ave

def exit(gradeList):
    if gradeList == []:
        print "You must enter at least one grade for this program to work. Good Bye."
        sys.exit()

#def get_info():
while True:
    grades = raw_input("Please input your grades.(or Enter once you have entered all of your grades): ")
    if not grades:
        break
    elif validate_input() == True:
        continue
    else:
        print "Please enter a number."
        continue

def give_answers(gradeList):    
    while True:
        print "\n",
        print "Please select what you would like to do with your grades."
        print "Press 1 for the Highest grade."
        print "Press 2 for the Lowest grade."
        print "Press 3 for the Average of the grades you entered."
        print "\n",
        print "Or you can press 'q' to quit."
        choice = raw_input("> ")
        if choice == 'q':
            break
        elif choice == '1':
            print "\n",
            print "The highest grade that you entered was %d.\n" % highest,
        elif choice == '2':
            print "\n",
            print "The lowest grade that you entered was %d.\n" % lowest,
        elif choice == '3':
            print "\n",
            print "Your average grade was %d.\n" % average,
        else:
            print "Please enter 1, 2, 3 or 'q'."


#get_info()
exit(gradeList)

gradeList.sort()
highest = gradeList[-1]
lowest = gradeList[0]
count = len(gradeList)
total = sum(gradeList)
average =  average( count, total)

give_answers(gradeList)

我粘贴代码时一切正常,但当我尝试定义get_info时,嵌套的validate_input()函数停止工作。它不再填充列表,因此exit()捕获并结束程序。循环似乎只是完全通过validate_input()函数,因为else语句在每次通过后都会跳转。我的问题是如何在用户按Enter键之前继续接受输入时让validate_input()函数正常工作?

1 个答案:

答案 0 :(得分:0)

将等级传递给您的函数validate_input,以便将等级添加到列表中,如:

def validate_input(grades):