2016-03-27 27 views
0

這是將輸入包含員工姓名及其相應薪水的二維數組的模塊。 這裏的程序只需要一個輸入和移動,而不是添加更多的輸入,直到用戶輸入「*」。我該如何解決?如何修復TypeError:'float'對象不可用並且不起作用的.append

salary = [] 
names = [] 

def floatInput(): 
    done = False 
    while not done: 
     nameIn = input("Please enter the employee name or * to finish: ") 
     salaryIn = input("Please enter the salary in thousands for " + nameIn + ": ") 
     try: 
      salaryIn = float(salaryIn)    
     except: 
      print("Program was expecting a positive integer or floating point number!") 
     if nameIn == "*": 
      done = True 
     else: 
      salary.append(salaryIn) 
      names.append(nameIn) 
     return salary 
     return names 

調用浮動輸入功能

floatInput() 

這裏我用一個for循環輸出,並通過姓名和工資的列表進行迭代。

for i in range(len(names)): 
    print(names[i] + ", " + str(salary[i])) 

這裏我找到了工資的平均值。

def salaryMean(): 
    mean = sum(salary)/float(len(salary)) 
    print("The mean of the salaries is: " + str(mean)) 
    return mean 

調用薪酬均值函數

salaryMean() 

在這裏,我的工資轉化爲數千人。

for i in range(len(names)): 
    salary = salary[i] * 1000 
print(salary) 

這裏我展示了一系列的5000 $內賺取平均 誰所有emplpyees這是我收到

"TypeError: 'float' object is not subscriptable" 

和它指向的線

"if salary[x] >= (mean - 5000) and salary[x] <= (mean + 500):" 

.... 我該如何解決?

def displayNames(): 
    done = False 
    x = 0 
    while not done: 
     if done: 
      break 
     if salary[x] >= (mean - 5000) and salary[x] <= (mean + 5000): 
      print(salary[x]) 
     x += 1 
     if x > len(salary): 
      done = True 

調用顯示名稱功能。

displayNames() 

回答

0

要解決你的問題.append(也是你的第二return語句永遠不會執行,見下文如何退回兩份名單):

你的循環不會繼續是因爲你回來在循環內部,從而終止該功能。在循環之外移動您的return聲明(單個unindent)。

while not done: 
    # do stuff 
return salary, names 

要解決您的TypeError我認爲這個問題是在這裏:

for i in range(len(names)): 
    salary = salary[i] * 1000 # Up to this point salary is a list, here it turns into the ith value of the list multiplied by 1000 
print(salary) 

相反,替換整個與循環:

salary = [s*1000 for s in salary] 
for s in salary: 
    print(s) # This should now print the multiplied salaries. 

其他一些問題 - 你有兩個return聲明之後是另一個 - 函數將在第一次返回後完成執行,並且從不執​​行下一個返回;如果您想要返回salarynames,請使用return names, salary(也可以將salary重命名爲salaries,以便人們可以輕鬆地分辨出這是一堆薪水,而不僅僅是一個)。

相關問題