似乎无法弄清楚如何用Python编写循环

时间:2019-03-01 12:59:02

标签: python

我必须计算员工的总工资并显示结果。您的程序将接受员工的姓名,工作时间和员工的工资率。该程序还将需要计算加班时间。加班费的定义是,超过40小时的工资是正常工资的1.5倍。该程序应打印员工的姓名,总工资金额,并且只有在加班的情况下,才应打印加班工资金额。最后,程序应根据需要重复执行,直到用户输入前哨值。

public class UserToken {
    @OneToOne(targetEntity = User.class)
    @JoinColumn(nullable = false, name = "user_id")
    private long tokenId;

}

public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "user_id", unique = true, nullable = false)
    private long userId;

}

这就是我所拥有的,程序中没有循环。我似乎无法弄清楚这个东西,我在这里疯了。我只希望有人帮我分解一下。谢谢!

3 个答案:

答案 0 :(得分:1)

您可以做的是将所有要重复的代码循环多次。它看起来像:

    while True:
        # code you want to repeat
        if some_condition:
            break

或:

    flag = False
    while not flag:
        # code you want to repeat
        if some_condition:
            flag = True

答案 1 :(得分:0)

您可以像这样使用for循环:

print("Payroll Calculator")

count = 2
for i in range(count):
    EmployeesName = input("Please enter employees Name :")
    WeeklyHours = int(input("Please Enter Hours Worked:"))
    PayRate = int(input("Please Enter Pay Rate:"))
    print("Normal Pay Rate is:", 40 * PayRate)
    if(WeeklyHours > 40):
        Overtime = PayRate * 1.5
        if(WeeklyHours > 40):
            print("Your Overtime Hours are:", WeeklyHours - 40)
            print("Your Overtime Rate is:", Overtime * 1.5)
    print("Your Gross Pay is:", WeeklyHours * Overtime)

    finish = input('Would you like to continue? (y/n) :')
    if finish == 'n':
        count = 0
    elif finish == 'y':
        count += 1

此外,您的变量GrossPay未被使用。

答案 2 :(得分:0)

我会先将“前哨变量”设置为不间断值,而不是使用True时。使老师高兴。 给定例如sentinel变量将是“ 0”作为EmployeeName,您会这样做

print("Payroll Calculator")
EmployeesName = None
while EmployeesName != '0': # 0 in python2
   EmployeesName = input("Please enter employees Name or 0 to quit:")
   If EmployeesName != '0':
       WeeklyHours = int(input("Please Enter Hours Worked:"))
       PayRate = int(input("Please Enter Pay Rate:"))
       print("Normal Pay Rate is:", 40 * PayRate)
       if(WeeklyHours > 40):
           Overtime = PayRate * 1.5
           if(WeeklyHours > 40):
               print("Your Overtime Hours are:", WeeklyHours - 40)
               print("Your Overtime Rate is:", Overtime * 1.5)
           GrossPay = WeeklyHours * Overtime
           print("Your Gross Pay is:", WeeklyHours * Overtime)

但是您也可以定义一些自定义变量来处理此问题:

stop = False
while not stop:
   ...
   # check now if if we should stop
   if (EmployeesName == '0'):
       stop = True

您始终可以使用while True:break方法,但是我不推荐这样做,因为该任务要求在while条件下使用变量,并且应避免在true循环之前使用imho while循环,直到您真正了解循环为止。

while True:
   ...
   # check now if if we should stop
   if (EmployeesName == '0'):
       break # exits loop.

在这个例子中有道理。

注意:Python2将为input()返回一个整数,Python3将返回一个字符串。将示例编辑为python3。