【发布时间】:2017-03-26 20:33:28
【问题描述】:
我是 Python 的绝对初学者,我的任务是创建一个可以做一些事情的程序:
- 将员工姓名输入到列表中。
- 输入员工姓名后输入该员工的工资。
- 汇总列表中的薪水,(2 个列表:姓名[] 和薪水[])。
- 求合计后的平均工资。
- 打印收入低于平均工资 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()
非常感谢任何信息。我希望这个程序中的其余功能和逻辑是有意义的。
【问题讨论】:
-
这里有很多错误。首先,如果您想在该函数之外使用它,则需要将averageSalaries 的返回值存储在某个地方。
-
那是很多代码。您可以先take the tour 学习How to Ask a good question 并创建一个Minimal, Complete, and Verifiable 示例。这让我们更容易为您提供帮助。
标签: arrays python-3.x loops