通过用户输入在元组中打印出每次都不同的输出



我有一段代码,要求一个人输入6名不同员工的工作时间,每次都要求他们导入工作时间。然后它会询问每小时的工资金额。

然后,它应该打印出每个工人的总工资。然而,它只打印出已经输入的最后一个输入,所以无论工人6的输入是多少,都会得到次,然后打印6次。

有没有办法做到这一点,每次都更改数字,并为每个工人打印正确的金额,而不需要打印出6个不同的结果,每个结果都有一个var?

这是代码

my_list = [
("employee 1"),
("employee 2"),
("employee 3"),
("employee 4"),
("employee 5"),
("employee 6"),
]
my_list_money = []

for (employee) in my_list:
user = int(input("Enter the hours worked by {}.".format(employee)))

user_ = int(input("Enter the hourly pay rate: "))
total = (user * user_)

for (employee) in my_list:
print("Gross pay for {}.".format(employee),total)

这是我的输出:

Enter the hours worked by employee 1.7
Enter the hours worked by employee 2.8
Enter the hours worked by employee 3.7
Enter the hours worked by employee 4.6
Enter the hours worked by employee 5.6
Enter the hours worked by employee 6.9
Enter the hourly pay rate: 8
Gross pay for employee 1. 72
Gross pay for employee 2. 72
Gross pay for employee 3. 72
Gross pay for employee 4. 72
Gross pay for employee 5. 72
Gross pay for employee 6. 72

您定义了my_money_list,但从未使用过它。

方法如下:

my_list = [
("employee 1"),
("employee 2"),
("employee 3"),
("employee 4"),
("employee 5"),
("employee 6"),
]
my_list_money = []
for (employee) in my_list:
user = int(input(f"Enter the hours worked by {employee}. "))
my_list_money.append(user)

user_ = int(input("Enter the hourly pay rate: "))
for employee, user in zip(my_list, my_list_money):
total = user * user_
print(f"Gross pay for {employee}: {total}")

你甚至可以通过列表理解来做到这一点:

my_list = [
("employee 1"),
("employee 2"),
("employee 3"),
("employee 4"),
("employee 5"),
("employee 6"),
]
my_list_money = [int(input(f"Enter the hours worked by {employee}. ")) for employee in my_list]
user_ = int(input("Enter the hourly pay rate: "))
print('n'.join([f"Gross pay for {employee}: {user * user_}" for employee, user in zip(my_list, my_list_money)]))

输入:

Enter the hours worked by employee 1. 5
Enter the hours worked by employee 2. 2
Enter the hours worked by employee 3. 6
Enter the hours worked by employee 4. 3
Enter the hours worked by employee 5. 1
Enter the hours worked by employee 6. 3

输出:

Enter the hourly pay rate: 23
Gross pay for employee 1: 115
Gross pay for employee 2: 46
Gross pay for employee 3: 138
Gross pay for employee 4: 69
Gross pay for employee 5: 23
Gross pay for employee 6: 69

最新更新