我错过了什么?而Loop

时间:2017-01-07 13:33:54

标签: python-3.x pycharm

尝试使用while循环创建工资单计算器。我在这个过程中遇到了障碍。

    name='1'
    print('We pay your employees payroll!')
    while name != '0':
        name=input("\nEnter employee or Enter '0' to quit: ")
        pr=float(input("Enter Payrate: "))
        hrs=float(input("Enter Hours Worked: "))
        if hrs <= 40:
            print("Hours Worked: ", hrs)
            print("Payrate: ", pr)
            print("Basepay:", hrs*pr)
        elif hrs > 40:
            print('Hours Worked: ', hrs)
            print("Payrate: ", pr)
            print("Overtime Rate: ", pr*1.5)
            print("Overtime Hours: ", hrs-40)
            print("Basepay: ", (hrs-40)*pr)
            print("Overtime Pay: ", (pr*1.5)*(hrs-40))
            print("Grosspay: ", (pr*1.5)*(hrs-40)+(pr*hrs))
    print("Employees Paid, Goodbye!")

循环效果很好,问题是当输入'0'时,循环不会立即结束。相反,当输入'0'时,它会继续询问hrs(输入)和pr(输入),然后再运行第一个'if'语句,然后以“员工已付款再见!”结束程序。

2 个答案:

答案 0 :(得分:1)

问题是while循环条件除了在循环体执行之前的最开始时才被计算。当name设置为&#39; 0&#39;时,条件name != 0变为false,但while循环体的其余部分仍将再次执行。

下面的代码通过在用户输入员工姓名并在用户输入&#39; 0&#39;

之前提前退出循环体时测试此条件来纠正问题
print('We pay your employees payroll!')
while True:
    name = input("\nEnter employee or Enter '0' to quit: ")

    if name == '0':
        break

    pr = float(input("Enter Payrate: "))
    hrs = float(input("Enter Hours Worked: "))
    if hrs <= 40:
        print("Hours Worked: ", hrs)
        print("Payrate: ", pr)
        print("Basepay:", hrs * pr)
    elif hrs > 40:
        print('Hours Worked: ', hrs)
        print("Payrate: ", pr)
        print("Overtime Rate: ", pr * 1.5)
        print("Overtime Hours: ", hrs - 40)
        print("Basepay: ", (hrs - 40) * pr)
        print("Overtime Pay: ", (pr * 1.5) * (hrs - 40))
        print("Grosspay: ", (pr * 1.5) * (hrs - 40) + (pr * hrs))
print("Employees Paid, Goodbye!")

<强>输出

We pay your employees payroll!

Enter employee or Enter '0' to quit: 1
Enter Payrate: 2
Enter Hours Worked: 2
Hours Worked:  2.0
Payrate:  2.0
Basepay: 4.0

Enter employee or Enter '0' to quit: 0
Employees Paid, Goodbye!

答案 1 :(得分:0)

很抱歉没有清楚地理解这个问题。我知道正确的答案正在发布,但我已经纠正了我的错误。

x$`4`['mpg']
                mpg
Datsun 710     22.8
Merc 240D      24.4
Merc 230       22.8
Fiat 128       32.4
Honda Civic    30.4
Toyota Corolla 33.9
Toyota Corona  21.5
Fiat X1-9      27.3
Porsche 914-2  26.0
Lotus Europa   30.4
Volvo 142E     21.4

<强>输出

$`4.mpg`
 [1] 22.8 24.4 22.8 32.4 30.4 33.9 21.5 27.3 26.0 30.4 21.4