2017-03-26 52 views
1

範圍打印工資我是一個絕對的初學者到Python和我有建立一個程序,做了幾件事情負責:Python的環路內的平均

  1. 輸入員工姓名到一個列表。
  2. 輸入員工在輸入姓名後的工資。
  3. 將清單中的工資總計爲(2個清單:名稱[]和薪水[])。
  4. 找到合計後的平均工資。
  5. 打印平均薪水在5,000美元以內(我卡住的地方)的員工。

請參閱下面我的代碼:

# function to total the salaries entered into the "newSalary" variable and "salaries[]". 
def totalSalaries(salaries): 
    total = 0 
    for i in salaries: 
     total += i 
    return total 

# Finds the average salary after adding and dividing salaries in "salaries[]". 
def averageSalaries(salaries): 
    l = len(salaries) 
    t = totalSalaries(salaries) 
    ave = t/l 
    return ave 

# Start main 
def main(): 
    # Empty names list for "name" variable. 
    names = [] 

    # Empty salaries list for "salary" and "newSalary" variables. 
    salaries = [] 

    # Starts the loop to input names and salaries. 
    done = False 
    while not done: 
     name = input("Please enter the employee name or * to finish: ") 
     salary = float(input("Please enter the salary in thousands for " + name + ": ")) 

     # Try/except to catch exceptions if a float isn't entered. 
     # The float entered then gets converted to thousands if it is a float. 
     try: 
      s = float(salary) 

     # Message to user if a float isn't entered. 
     except: 
      print("Please enter a valid float number.") 
      done = False 
     newSalary = salary * 1000 

     # Break in the loop, use * to finish inputting Names and Salaries. 
     if name == "*": 
      done = True 

     # Appends the names into name[] and salaries into salaries[] if * isn't entered. 
     # Restarts loop afterwards if * is not entered. 
     else: 
      names.append(name) 
      salaries.append(newSalary) 
    # STUCK HERE. Need to output Names + their salaries if it's $5,000 +- the total average salary. 
    for i in range(len(salaries)): 
     if newSalary is 5000 > ave < 5000: 
      print(name + ", " + str(newSalary)) 

    # Quick prints just to check my numbers after finishing with *. 
    print(totalSalaries(salaries)) 
    print(averageSalaries(salaries)) 


main() 

任何信息是極大的讚賞。我希望這個程序中的其他功能和邏輯是合理的。

+0

這裏有很多錯誤。首先,如果你想在該函數之外使用它,你需要在某處存儲來自averageSalaries的返回值。 –

+0

這是很多代碼。您可以先[參觀](http://stackoverflow.com/tour)並學習[如何提出一個好問題](http://stackoverflow.com/help/how-to-ask)並創建一個[最小,完整和可驗證](http://stackoverflow.com/help/mcve)示例。這使我們更容易幫助你。 –

回答

0

您沒有正確編寫您的迭代器。使用數組,您可以使用for element in array:,循環將通過將每個元素放入元素來遍歷數組。所以你的for循環變成for salary in salaries

另外,您需要將條件分成兩部分,並使用添加和減法。你的代碼應該檢查工資是高於還是等於平均值​​減去5000,如果它低於或等於平均值​​加上5000.如果你想用數學形式表示這將是: 薪水> =平均值 - 5000 和 工資< =平均+ 5000

因此,在線路條件變爲if salary >= (average - 5000) and salary <= (average + 5000)

最後,你不進入循環之前調用averageSalaries,所以平均工資還沒有計算呢。您應該調用該函數並在for循環之前將結果放入一個變量中。

+0

「ave」從哪裏來? –

+0

來自用戶的代碼。我沒有注意到他們沒有在for循環之前調用averageSalaries。 – Lunar

+0

非常感謝您的信息。我繼續並在循環之前添加了以下行:「ave = averageSalaries(工資),現在它可以正確地從列表中拉出用戶。 – BPeretz95