繁体   English   中英

如何使用 For 循环范围和列表创建列表列表以在此上下文中显示不同的字符串输出

[英]How To Use A For Loop Range And List to create a List Of Lists To Display Different String Outputs In This Context

我正在尝试创建一个需要两个 prmtrs 的函数, num_of_employeeshrly_rate

该清单应包括每个员工的工作小时数和工资。 列表的大小应与员工人数相同。 它提示用户输入每个员工的工作小时数,计算工资,并创建一个小时数和工资列表,并将其添加到列表中。

如果人数少于 40,则工资标准为:工作小时数 * 小时费率 如果人数大于 40,则超过 40 小时的工资为小时费率 1.5。

代码应该显示此输出:#假设员工人数仅为 2,:

insert the number of worked hours: 60
insert the number of worked hours:20
the employee worked for 60 hours and the earned is 700.00$
the employee worked for 20 hours and the earned is 200.00$

但这是我的代码:

def calculate_total_pay_cad(num_employees, hrly_rate_CAD):
    rng = range(0, num_employees)
    for n in rng:
        num_hrs_worked = int(input(('Input the number of worked hours: ')))
    if num_hrs_worked < 40:
        pay = num_hrs_worked * hrly_rate_CAD
    if num_hrs_worked > 40:
        pay = num_hrs_worked * (hrly_rate_CAD * 1.5)
    for n in rng:
        print(f"the employee worked for {num_hrs_worked} and has earned {pay}")

num_employees = int(input(('enter number employees')))
hrly_rate_CAD = int(input(('enter hourly rate: ')))

calculate_total_pay_cad(num_employees,hrly_rate_CAD)

这是我的输出:

 Input the number of worked hours: 50
Input the number of worked hours: 20
the employee worked for 20 and has earned 300
the employee worked for 20 and has earned 300

摘要 = 我的代码仅在我的输入列表中输出最后一个插入。 我如何使它伴随正确的小时数和每条线路的工资计算?

提前谢谢了。

这是因为您的计算是在 for 循环之外完成的。 这意味着它将只使用最后输入的值进行所有计算。 相反,将所有内容移动到循环内,因为您想要每个员工的输出:

def calculate_total_pay_cad(num_employees, hrly_rate_CAD):
    rng = range(0, num_employees)
    for n in rng:
        num_hrs_worked = int(input(('Input the number of worked hours: ')))
        pay = 0.0
        if num_hrs_worked < 40:
            pay = num_hrs_worked * hrly_rate_CAD
        if num_hrs_worked > 40:
            pay = num_hrs_worked * (hrly_rate_CAD * 1.5)
        print(f"the employee worked for {num_hrs_worked} and has earned {pay}")

根据您的评论,如果您想先输入所有工作时间,然后输出工资,您应该使用list 在这里,您将首先提示并计算所有工资,将其保存到列表中,然后遍历显示工资的列表。

def calculate_total_pay_cad(num_employees, hrly_rate_CAD):
    rng = range(0, num_employees)
    pay_list = []
    for n in rng:
        num_hrs_worked = int(input(('Input the number of worked hours: ')))
        if num_hrs_worked < 40:
            pay_list.append((num_hrs_worked * hrly_rate_CAD, num_hrs_worked))
        if num_hrs_worked > 40:
            pay_list.append((num_hrs_worked * (hrly_rate_CAD * 1.5), num_hrs_worked))
    for pay, num_hrs_worked in pay_list:
        print(f"the employee worked for {num_hrs_worked} and has earned {pay}")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM