变量没有收到金额? Python

Variables not receiving amounts? Python

当我 运行 我的程序时,我声明的 none 个变量正在获取它们的值。我确实记得使用 return 语句,但它似乎没有做任何事情。

def main():
    time_Amount = getTime()

    seconds = getSeconds(time_Amount)
    minutes = getMinutes(seconds)
    hours = getHours(minutes)
    days = getDays(hours)

    printBreakDown(days, hours, minutes, seconds)

def getTime():
    time_Amount = int(input("Enter time in seconds: "))
    while (time_Amount == 0):
        seconds = int(input("Enter a non-zero amount of seconds: "))
    return time_Amount

def getSeconds(time_Amount):
    seconds = time_Amount % 60
    return seconds
def getMinutes(seconds):
    minutes = seconds % 60
    return minutes
def getHours(minutes):
    hours = minutes % 24
    return hours
def getDays(hours):
    days = hours % 365
    return days

def printBreakDown(days, hours, minutes, seconds):
    print("--------Break Down--------")
    print(days, "day(s), ", hours, "hour(s), ",
          minutes, "minute(s), ", seconds, "second(s)")

main()

我首先看到的是你在下面的函数中写了 seconds 而不是 time_Amount

def getTime():
    time_Amount = int(input("Enter time in seconds: "))
    while (time_Amount == 0):
        # Check this line
        time_Amount = int(input("Enter a non-zero amount of seconds: "))
    return time_Amount

你拥有的是:

def getTime():
    time_Amount = int(input("Enter time in seconds: "))
    while (time_Amount == 0):
        seconds = int(input("Enter a non-zero amount of seconds: "))
    return time_Amount

如果用户在第一行输入 0,则将进入 while 循环,提示用户输入非零值。然后用户输入 10,seconds 被赋值为 10。请注意 time_Amount 仍然是 0,因为您从未修改过它。 loop 条件被检查,它停留在 while 循环内。

您不能按照您尝试的方式使用模数 (%) 运算符。如果您传递的值小于您的除数,您的值将保持不变。 这不是将分钟转换为小时的合适方法( 等等 ),并且会导致您的奇怪值。

您最有可能想要使用的是存储每个除法的精确值,并使用 floor division operator // 来确定有多少 days/hours/minutes/seconds。

为了说明%//的区别:

>>> 10 // 24
0
>>> 10 % 24
10

或者,您可以使用 datetime 模块来更简洁地计算:

from datetime import datetime,timedelta
def main():
    time_Amount = timedelta( seconds = int(input('Enter time in seconds: ')))

    while (time_Amount == timedelta(seconds = 0)):
        time_Amount = timedelta( seconds = int(input("Enter a non-zero amount of seconds: ")))    

    calc_time = datetime(1,1,1) + time_Amount
    print("--------Break Down--------")
    print("%d day(s), %d hour(s), %d minute(s), %d second(s)" %
          (calc_time.day-1, calc_time.hour, calc_time.minute, calc_time.second))

这是如何工作的:

  • 首先我们根据用户输入创建一个 timedelta 秒对象。本质上,这是一个反映 duration 的对象,可以用许多不同的时间单位表示。

  • datetime(1,1,1) + time_Amount 获取一个 1 年 1 个月 1 天的 datetime 对象,并添加我们的 timedelta 持续时间(以秒为单位)。

  • 我们使用字符串格式从我们的 datetime 对象中惯用地取出相应的日、时、分和秒。

如果你想要一个月份或年份变量,你必须为它们设置格式并相应地从中减去 1,分别使用 calc_time.monthcalc_time.year 访问。

输出:

>>>main()
Enter time in seconds: 10000
--------Break Down--------
0 day(s), 2 hour(s), 46 minute(s), 40 second(s)