我得到零作为工资的回报。我知道它可能与变量范围有关,但我迷失了。
'''
Write a program to declare two empty lists one is for name and one for salaries.
Within the for loop ask for employees name and their salaries
and append them into the list accordingly.
Find out the total salary using accumulation concept but you
need to call a function called EvaluateSalary() within the for loop passing the argument
salary for each iteration.
Output : Both of the lists with their items and the total salary.
'''
#Declare name list
nameList = []
#declare salary list
salaryList = []
#declare quit constant
QUIT = "ZZZ" or 000
employeeName = str(input("Please enter an Employee name or ZZZ to quit : ")).upper()
employeeSalary = float(input("Please enter the salary of the Employee or 000 to quit : "))
以下是我做得不好的事情。我希望它通过循环的每次传递添加工资输入。
salary = 0
def EvaluateSalary(salary):
salary = salary + employeeSalary
return salary
while employeeName != QUIT:
nameList.append(employeeName)
salaryList.append(employeeSalary)
EvaluateSalary(salary)
employeeName = str(input("Please enter an Employee name or ZZZ to quit : ")).upper()
employeeSalary = float(input("Please enter the salary of the Employee or 000 to quit : "))
print("Goodbye!")
print(nameList, salaryList, salary)
答案 0 :(得分:2)
虽然堆栈溢出不是您要求人们为您编写代码的地方,但我认为这篇文章可能有助于新程序员看到代码示例并学习一些技术,其中之一就是避免全局和/或函数式编程技术。
如果我要重新编写代码,我会按如下方式编写:
def input_employees():
while True:
name = input(
"Please enter an Employee name or Hit Enter to quit : "
).upper()
if not name:
break
salary = input(
"Please enter the salary of the Employee or Hit Enter to quit : "
)
if not salary:
break
yield {'name': name, 'salary': float(salary)}
def sum_salary(employees):
# this is a guess from your code. my guess is you wanted a salary sum
return sum([e['salary'] for e in employees])
def main():
employees = list(input_employees())
print('Total Salaries:', sum_salary(employees))
print(employees)
main() # run the main function, ie the script
答案 1 :(得分:1)
你的问题在这里:
salary = 0
def EvaluateSalary(salary):
salary = salary + employeeSalary
return salary
薪水是一个全球变量。没有必要将它传递给你的函数,所以你需要传递的是employeeSalary。
我认为这会起作用
salary = 0
def EvaluateSalary(employeeSalary):
salary = salary + employeeSalary
由于工资是全球性的,您不需要退货,您可以从代码中随处访问。
方法2:
不使用全局变量:
def EvaluateSalary(employeeSalary, salary):
salary = salary + employeeSalary
return salary
salary = 0
while ...whatever...:
salary = EvaluateSalary(employeeSalary, salary)
(...)
因此,您在while循环的每次迭代中更新全局薪水的值,并且只是保持累积。