我如何在没有全局变量的情况下写这篇文章



我必须编写一个程序,以输入输入并写出与成绩一起输入的编号。我的程序有效,但显然我只应该使用本地变量。我需要更改什么,以便它只是局部变量?以下两个变量是我目前用作全局变量的变量。

# This program takes intger inputs and provides a grade value for each number entered
number = 1
myNumbers = []
print("Please enter as many integer numbers as you would like. Enter -999 to exit loop")
# This function has the user input values and exit with a sentinel value -999
def getScores(number):
    sentinelValue = -999
    while(number != sentinelValue):
        number = eval(input("Enter an integer: "))
        if number > -1:
             myNumbers.append(number)
    print("Numbers entered: ")
    print(myNumbers, "n")

# This function prints out the values with the appropriate letter grade
def printScores():
    print("Length of array = ", len(myNumbers))
    for i in range(0, len(myNumbers)):
        if myNumbers[i] >= 90:
            print(myNumbers[i], "is an A")
        if myNumbers[i] >= 80 and myNumbers[i] < 90:
            print(myNumbers[i], "is a B")
        if myNumbers[i] >= 70 and myNumbers[i] < 80:
            print(myNumbers[i], "is a C")
        if myNumbers[i] >= 60 and myNumbers[i] < 70:
            print(myNumbers[i], "is a D")
        if myNumbers[i] >= 0 and myNumbers[i] < 60:
            print(myNumbers[i], "is an F")
# The main function is where we will call the other functions and print out the results
def main():
    getScores(number)
    printScores()
# Call the main
main()

我仍然应该具有两个单独的功能。

getScores不需要输入上的数字...它可以在循环之前创建一个默认值。它可以返回其创建的列表,而不是编写全局变量。呼叫者记得返回值并在下一个呼叫中使用它。

# This program takes intger inputs and provides a grade value for each number entered
print("Please enter as many integer numbers as you would like. Enter -999 to exit loop")
# This function has the user input values and exit with a sentinel value -999
def getScores():
    sentinelValue = -999
    number = ''
    myNumbers = []
    while(number != sentinelValue):
        number = eval(input("Enter an integer: "))
        if number > -1:
             myNumbers.append(number)
    print("Numbers entered: ")
    print(myNumbers, "n")
    return myNumbers
# This function prints out the values with the appropriate letter grade
def printScores(myNumbers):
    print("Length of array = ", len(myNumbers))
    # omit the rest for brevity...
# The main function is where we will call the other functions and print out the results
def main():
    scores = getScores()
    printScores(scores)
# Call the main
main()

相关内容

  • 没有找到相关文章

最新更新