Python循环打印平均范围内的工资

时间:2017-03-26 20:33:28

标签: arrays python-3.x loops

我是Python的绝对初学者,我的任务是创建一个可以做一些事情的程序:

  1. 将员工姓名输入列表。
  2. 输入员工姓名后的工资。
  3. 在工作清单中记录工资,(2个清单:姓名[]和工资[])。
  4. 查看总计后的平均工资。
  5. 打印那些平均薪水在5,000美元以内的员工(我被困的地方)。
  6. 请参阅下面的代码:

    # 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()
    

    非常感谢任何信息。我希望这个程序中的其余功能和逻辑是有意义的。

1 个答案:

答案 0 :(得分:0)

你的避风港没有正确编写你的迭代器。使用数组,您只需使用var,循环将通过将每个元素放在元素中来迭代数组。因此,您的for循环变为for element in array:

此外,您需要将您的条件分成两部分并使用添加和减法。你的代码应该检查工资是否高于或等于平均值​​减去5000,如果它低于或等于平均值​​加5000.如果你想用数学形式化它,那将是: 工资&gt; =平均值 - 5000 和 薪水&lt; =平均值+ 5000

因此,行的条件变为for salary in salaries

最后,在进入循环之前你不会调用averageSalaries,所以还没有计算平均工资。你应该调用函数并将结果放在for循环之前的变量中。