我必须编写一个程序来接收输入并写出输入的数字以及它的等级。我的程序工作,但显然我只应该使用局部变量。我需要更改什么,以便它只是局部变量?下面的两个变量是我目前用作全局变量的变量。
# 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()
我仍然应该有两个独立的功能。
答案 0 :(得分:1)
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()