2017-04-20 74 views
0

我必須編寫一個程序,它接受輸入並寫出輸入的數字以及它的等級。我的程序工作,但顯然我只能使用局部變量。我需要改變什麼,以便它只是局部變量?下面的兩個變量是我目前用作全局變量的。如何在不使用全局變量的情況下編寫此代碼?

# 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

在此處發佈代碼以實現永久化。 – tdelaney

回答

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() 
+0

我得到一個錯誤的主要(),分數= getScores(數字),並沒有定義「NameError:名稱」號碼「 – Drizzy

+1

我的壞...我想一些複製/粘貼錯誤。更新後的代碼有效。 – tdelaney

相關問題