【问题标题】:Short-Circuit And Float短路和浮动
【发布时间】:2020-03-02 02:31:23
【问题描述】:

我试图在 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))))

【问题讨论】:

  • 试试%.2f 而不是%2.f
  • 出现“日薪465.000000”你知道为什么吗?
  • 是的,因为你没有写%.2f。这是一个简单的错字。

标签: python short short-circuiting


【解决方案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}
    rate  = rates.get(post)

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

在 Python 3.8 中,您可以使用 assignment expression 进一步收紧它。

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

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

【讨论】:

  • 是的,我明白了。我的建议:不要。
猜你喜欢
  • 1970-01-01
  • 2023-03-06
  • 2018-05-03
  • 1970-01-01
  • 2015-04-11
  • 2012-09-09
  • 1970-01-01
  • 2011-05-07
  • 2021-10-20
相关资源
最近更新 更多