【问题标题】:Python loop to print salaries within range of the averagePython循环打印平均范围内的工资
【发布时间】:2017-03-26 20:33:28
【问题描述】:

我是 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()

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

【问题讨论】:

标签: arrays python-3.x loops


【解决方案1】:

您没有正确编写迭代器。使用数组,您可以只使用for element in array:,循环将通过将每个元素放入元素中来迭代数组。所以你的 for 循环变成了for salary in salaries

此外,您需要将条件一分为二并使用加法和减法。您的代码应该检查薪水是否高于或等于平均值​​ - 5000,以及是否低于或等于平均值​​加上 5000。如果您想以数学方式将其形式化,它将是: 薪水 >= 平均 - 5000 和 薪水

所以行的条件变成if salary &gt;= (average - 5000) and salary &lt;= (average + 5000)

最后,您在进入循环之前没有调用 averageSalaries,因此尚未计算平均工资。您应该调用该函数并将结果放入 for 循环之前的变量中。

【讨论】:

  • ave 来自哪里?
  • 来自用户的代码。我没有注意到他们没有在 for 循环之前调用 averageSalaries。
  • 非常感谢您的信息。我继续在循环之前添加了以下行:“ave = averageSalaries(salaries),它现在可以正确地从列表中拉出用户。
猜你喜欢
  • 2021-07-01
  • 2018-11-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-01
  • 1970-01-01
相关资源
最近更新 更多