短路和浮线

问题描述 投票:-2回答:1

[我试图在Python中使用短路来打印一些数据,但是尽管我写了.2f,但浮点数后并没有出现2号

((DidHourPlus == 1) and (StartWeek == 1) and (post == "r") and print("The daily salary is %2.f" %  ((hours - 8) * 35 + 8 * 30)))
((DidHourPlus == 1) and (StartWeek == 1) and (post == "s") and print("The daily salary is %2.f" % (1.20*((hours - 8) * 35 + 8 * 30))))
((DidHourPlus == 1) and (StartWeek == 1) and (post == "m") and print("The daily salary is %2.f" % (1.50*((hours - 8) * 35 + 8 * 30))))
python short short-circuiting
1个回答
1
投票

这是短路的滥用。不要以这种方式使用and。使用if语句。

对于两个小数位,将2放在小数点后:%.2f而不是%2.f

if DidHourPlus == 1 and StartWeek == 1 and post == "r": print("The daily salary is %.2f" %  ((hours - 8) * 35 + 8 * 30)))
if DidHourPlus == 1 and StartWeek == 1 and post == "s": print("The daily salary is %.2f" % (1.20*((hours - 8) * 35 + 8 * 30)))
if DidHourPlus == 1 and StartWeek == 1 and post == "m": print("The daily salary is %.2f" % (1.50*((hours - 8) * 35 + 8 * 30)))

您可以将重复的测试提取到单个if中:

if DidHourPlus == 1 and StartWeek == 1:
    if post == "r": print("The daily salary is %.2f" %  ((hours - 8) * 35 + 8 * 30)))
    if post == "s": print("The daily salary is %.2f" % (1.20*((hours - 8) * 35 + 8 * 30)))
    if post == "m": print("The daily salary is %.2f" % (1.50*((hours - 8) * 35 + 8 * 30)))

然后提取打印输出:

if DidHourPlus == 1 and StartWeek == 1:
    salary = None

    if post == "r": salary = (hours - 8) * 35 + 8 * 30
    if post == "s": salary = 1.20*((hours - 8) * 35 + 8 * 30)
    if post == "m": salary = 1.50*((hours - 8) * 35 + 8 * 30)

    if salary:
        print("The daily salary is %.2f" % salary)

然后提取工资计算:

if DidHourPlus == 1 and StartWeek == 1:
    rate = None

    if post == "r": rate = 1.00
    if post == "s": rate = 1.20
    if post == "m": rate = 1.50

    if rate:
        salary = rate * ((hours - 8) * 35 + 8 * 30)
        print("The daily salary is %.2f" % salary)

您可以在这里停下来,但是如果您想成为更高级的人,可以在词典中查询价格。

if DidHourPlus == 1 and StartWeek == 1:
    rates = {"r": 1.00, "s": 1.20, "m": 1.50}

    if post in rates:
        salary = rates[post] * ((hours - 8) * 35 + 8 * 30)
        print("The daily salary is %.2f" % salary)
© www.soinside.com 2019 - 2024. All rights reserved.