Нужна помощь в повторении файла CSV. Был только один сотрудник, для которого была выведена сводка по заработной плате - PullRequest
0 голосов
/ 09 мая 2020

Я хочу перебрать каждого сотрудника в «employeetest.csv». Программа пропускает двух сотрудников, а затем дублирует одного и того же сотрудника снова и снова. Я пытался сделать это просто списком, а не диктовкой, но это не сработало. Я не знаю, как я могу перебирать строки с помощью этой функции getData (): возможно, я использовал неправильный аргумент «for в reader:». Основное внимание, вероятно, уделяется функциям getData (): и payrollSummaryReport. Задайте любые вопросы для уточнения.

Вот цель программы:

  • Вычислить обычные отработанные часы (40 часов и ниже)
  • Вычислить отработанные сверхурочные часы (те, кто превышает 40 часов)
  • Вычислите обычную оплату (обычные часы, умноженные на обычную оплату)
  • Вычислите оплату сверхурочных (сверхурочные часы, умноженные на обычную оплату, умноженные на 1,5)
  • Подсчитайте заработную плату брутто
  • Вычислите сумму удержанного федерального налога (15,1% от заработной платы брутто)
  • Вычислите сумму удержанного налога штата (5,5% от заработной платы брутто)
  • Подсчитайте сумму удерживаемой медицинской помощи (1,2% от заработной платы брутто)
  • Вычислите сумму удержанного социального обеспечения (4,8% от заработной платы брутто)
  • Подсчитайте общие удержания (федеральный налог + налог штата + medicare + социальное обеспечение)
  • Рассчитайте net заработную плату (валовая заработная плата - вычеты)
  • Вычислите общую (общую для всех) net оплату
  • Печать ( на экран) чистый итоговый отчет (см. результат выше)
  • Распечатать (на экран) общую сумму net оплату
  • Ожидаемый выход: Или Идеальный выход

Лучше Фактический результат Изображение

ФАЙЛ CSV

First,Last,Hours,Pay
Matthew,Hightower,42,10
Samuel,Jackson,53,12.65
Catherine,Jones,35,19.43
Charlton,Heston,52,10
Karen,Black,40,12
Sid,Caesar,38,15
George,Kennedy,25,35
Linda,Blair,42,18.6
Beverly,Garland,63,10
Jerry,Stiller,52,15
Efrem,Zimbalist,34,16
Linda,Harrison,24,14
Erik,Estrada,41,15.5
Myrna,Loy,40,14.23

Программный код.

import csv

def main():

    results = get_data("employeestest.csv")

    payrollSummaryReport(results)
    print(results)
def get_data(fname):


    results = {} # return value 
    with open(fname, 'r', newline='') as f:
    reader = csv.reader(f)
    # Skip header row
    next(reader)

    print(reader)

    result = {} # will be used to grab all of the results then return them to the last function
# reader yield lists, but since we know each list will have
# the same number of elements we can unpack them into
# four separate variables - this is more readable than 
# referencing by index.
    for first_name, last_name, hours, pay_rate in reader:

          hours = float(hours)
          pay_rate = float(pay_rate)

      #Calculatations
          employeeRegularHours, employeeOvertimeHours = calculateRegularHours(hours)
          employeeOvertimeHours = calculateOvertimeHours(hours)
          regularPayAmount = calculateRegularPay(pay_rate, employeeRegularHours)
          overtimePayAmount = calculateOvertimePay(pay_rate, employeeOvertimeHours)
          grossPayAmount = calculateGrossPay(regularPayAmount, overtimePayAmount)
          federalTaxWithheld = calculateFederalTax(grossPayAmount)
          stateTaxWithheld = calculateStateTax(grossPayAmount)
          medicareTaxWithheld = calculateMedicareTax(grossPayAmount)
           = calculateSocSecTax(grossPayAmount)
          totalTaxesWithheld = calculateTotalTaxes(federalTaxWithheld, stateTaxWithheld,       medicareTaxWithheld, socSecTaxWithheld)
          netPayAmount = calculateNetPay(grossPayAmount, totalTaxesWithheld)

          #Add items to dictionary
          result["LastName"] = last_name
          result["FirstName"] = first_name
          result["Hours"] = hours
          result["RegHours"] = employeeRegularHours
          result["OTHours"] = employeeOvertimeHours
          result["RegPay"] = regularPayAmount
          result["OTPay"] = overtimePayAmount
          result["GrossPay"] = grossPayAmount
          result["Deductions"] = totalTaxesWithheld
          result["NetPay"] = netPayAmount







    return result

def calculateRegularHours(employeeHoursWorked) :
    #print(employeeHoursWorked)

    if employeeHoursWorked  < 40.0 :
        employeeRegularHours = employeeHoursWorked
        employeeOvertimeHours = 0.0
    else:

        employeeRegularHours = 40.0
        employeeOvertimeHours = 0.0
        employeeOvertimeHours = employeeHoursWorked - 40.0


    return employeeRegularHours, employeeOvertimeHours

def calculateOvertimeHours(employeeHoursWorked) :
    if employeeHoursWorked > 40.0 :
       employeeOvertimeHours = employeeHoursWorked - 40.0

       employeeOvertimeHours = 0.0
    else :
        employeeOvertimeHours = 0.0

    return employeeOvertimeHours


def calculateRegularPay(employeePayRate, employeeHoursWorked) :

    regularPayAmount = employeePayRate * employeeHoursWorked
    return regularPayAmount

def calculateOvertimePay(employeePayRate, employeeOvertimeHours) :
    overtimePayRate = 1.5
    overtimePayAmount = (employeePayRate * employeeOvertimeHours) * overtimePayRate
    return overtimePayAmount

def calculateGrossPay(regularPayAmount, overtimePayAmount) :
    grossPayAmount = regularPayAmount + overtimePayAmount
    return grossPayAmount

def calculateFederalTax(grossPayAmount) :
    federalTaxRate = 0.151
    federalTaxWithheld = grossPayAmount * federalTaxRate
    return federalTaxWithheld

def calculateStateTax(grossPayAmount) :
    stateTaxRate = 0.055
    stateTaxWithheld = grossPayAmount * stateTaxRate
    return stateTaxWithheld

def calculateMedicareTax(grossPayAmount) :
    medicareTaxRate = 0.012
    medicareTaxWithheld = grossPayAmount * medicareTaxRate
    return medicareTaxWithheld

def calculateSocSecTax(grossPayAmount) :
    socSecTaxRate = 0.048
    socSecTaxWithheld = grossPayAmount * socSecTaxRate
    return socSecTaxWithheld

def calculateTotalTaxes(federalTaxWithheld, stateTaxWithheld, medicareTaxWithheld, socSecTaxWithheld) :
    totalTaxesWithheld = federalTaxWithheld + stateTaxWithheld + medicareTaxWithheld +     socSecTaxWithheld
    return totalTaxesWithheld

def calculateNetPay(grossPayAmount, totalTaxesWithheld) :
    netPayAmount = grossPayAmount - totalTaxesWithheld
    return netPayAmount

def payrollSummaryReport(vals):
    print()
    print("\t\t\t\t\t\tPayroll Summary Report")
    print()
    print("%-12s%-12s%-8s%-10s%-10s%-12s%-10s%-11s%-13s%-10s" % ("LastName", "FirstName", "Hours", "RegHours", "OTHours", "RegPay", "OTPay", "GrossPay", "Deductions", "NetPay"))
    for i in vals:
    print("%-12s%-12s%-8.2f%-10.2f%-10.2f$%-11.2f$%-9.2f$%-10.2f$%-12.2f$%-10.2f" %\
   (vals["LastName"], vals["FirstName"], vals["Hours"], vals["RegHours"], vals["OTHours"], vals["RegPay"], vals["OTPay"], vals["GrossPay"], vals["Deductions"], vals["NetPay"]))
    return vals    
main()   

#print('Total Net Pay')
#print('\t\t $%.2f' % netPayAmount)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...