首页 > 解决方案 > 如何在python中制作单独的if语句

问题描述

我正在尝试编写一个程序,该程序将整数秒作为输入并将其返回为 n 年、n 天、n 小时、n 分钟和 n 秒。(每个 n 可能不同)

但由于某种原因,它没有出现在第二个 if 语句中。我已经将 print("x") 用于测试它是否进入 if 语句,但程序只打印出一个 "x",它在第一个 if 语句中,它不会进入其他语句。

我一直试图弄清楚它为什么会这样,但我似乎做不到。我还在互联网上查找了一些东西,这样我就不会用一个答案相当简单的问题来打扰某人,但我找不到任何东西。

这是我的代码:

def format_duration(seconds):
    decimal_list = []

    second_decimal = seconds % 60
    seconds -= second_decimal
    seconds /= 60

    decimal_list.append(int(second_decimal))

    if seconds >= 60:
        minute_decimal = seconds % 60
        seconds -= minute_decimal
        seconds /= 60

        decimal_list.append(int(minute_decimal))
        print("x")

        if minute_decimal > 1:
            minute_txt = "minutes"
    
        else:
            minute_txt = "minute"

    if seconds >= 3600:
        hour_decimal = seconds % 24
        seconds -= hour_decimal
        seconds /= 24

        decimal_list.append(int(hour_decimal))
        print("x")

        if hour_decimal > 1:
            hour_txt = "hours"
            
        else:
            hour_txt = "hour"

    if seconds >= 86400:
        day_decimal = seconds % 365
        seconds -= day_decimal
        seconds /= 365

        decimal_list.append(int(day_decimal))
        print("x")

        if day_decimal > 1:
            day_txt = "days"
                
        else:
            day_txt = "day"

    if seconds >= 31536000:
        year_decimal = seconds

        decimal_list.append(int(year_decimal))
        print("x")

        if year_decimal > 1:
            year_txt = "years"
                    
        else:
            year_txt = "year"

    for i in range(len(decimal_list)):
        if decimal_list[i] == 0:
            decimal_list.remove(decimal_list[i])

    print(decimal_list)

format_duration(2354678)

标签: pythonpython-3.xif-statement

解决方案


我在您的代码中添加了一些简单的跟踪:

if seconds >= 60:
    print("TRACE seconds > 60", seconds)
    minute_decimal = seconds % 60
    seconds -= minute_decimal
    seconds /= 60

    decimal_list.append(int(minute_decimal))

    if minute_decimal > 1:
        minute_txt = "minutes"

    else:
        minute_txt = "minute"

print("TRACE minutes were coverted", minute_decimal, seconds)

if seconds >= 3600:
    print("TRACE seconds > 3600", seconds)

输出:

TRACE seconds > 60
 39244.0
TRACE minutes were coverted 4.0 654.0
[38, 4]

您的习惯问题在于,您在整个程序中通过名称调用了许多不同的值;seconds我认为你把他们弄糊涂了。最值得注意的是,线条

    minute_decimal = seconds % 60
    seconds -= minute_decimal
    seconds /= 60

从完整值中提取亚分钟秒数,将其分配给变量minute_decimal,然后将余数转换为分钟...然后您继续调用seconds,并对其进行测试。

你写了很多代码,但没有进行太多测试。放入一些有用的print语句,在编写时跟踪每个部分,在调试完该部分之前不要继续。


推荐阅读