为什么这总是给输出0 0 0?

时间:2016-07-24 21:23:15

标签: python-3.x

由于某些原因,我无法更改全局变量total_hours。或者为什么输出总是0 0 0

hour = 1
day = 24
week = 168
part_day = 8
total_hours = int(0)
hours = total_hours % 168
days = ((total_hours % 168) // 7)
weeks = total_hours // 168

def sleep():
        global total_hours
        global week
        total_hours += week

def show_time():
        global hours
        global days
        global weeks
        print(hours, days, weeks)

sleep()

show_time()

1 个答案:

答案 0 :(得分:1)

您在此处执行的操作如下:

  1. 您将值0分配给变量total_hours
  2. 使用值为hour的变量days计算变量weektotal_hours0的值,并将结果分配给它们太
  3. 您更改变量total_hours
  4. 的值
  5. 您打印hourdaysweeks的值,就像它们在2中计算一样
  6. 为了更好地了解发生了什么,您应该使用print进行更多操作:

    hour = 1
    day = 24
    week = 168
    part_day = 8
    total_hours = int(0)
    hours = total_hours % 168
    days = ((total_hours % 168) // 7)
    weeks = total_hours // 168
    
    def sleep():
            global total_hours
            global week
            total_hours += week
    
    print 'values before `sleep`', hours, days, weeks, total_hours
    sleep()
    print 'values after `sleep`', hours, days, weeks, total_hours
    

    如果您想(重新)计算取决于total_hours的值,您可以执行以下操作:

    hour = 1
    day = 24
    week = 168
    part_day = 8
    total_hours = int(0)
    hours = total_hours % 168
    days = ((total_hours % 168) // 7)
    weeks = total_hours // 168
    
    def recalc():
        global weeks, days, hours, total_hours
        hours = total_hours % 168
        days = ((total_hours % 168) // 7)
        weeks = total_hours // 168
    
    def sleep():
        global total_hours, week
        total_hours += week
    
    def show_time():
        global hours, days, weeks
        print(hours, days, weeks)
    
    sleep()
    recalc()
    show_time()