2016-07-24 126 views
0

出於某種原因,我無法更改全局變量total_hours。或者爲什麼總是輸出0 0 0爲什麼總是給輸出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

您從未更改過「小時」,「天」或「周」的值。你改變的只是'total_hours'。變量被分配給值,而不是「total_hours」的分數。 – zondo

+0

但是,如果我更改total_hours本身的值,它可以工作... –

+0

如果您在創建其他變量之前更改它,那麼是的。如果我給你打電話給Eric,告訴我的鄰居給Eric一些東西,他會給你。如果在我告訴他之前,我告訴他我的兄弟是埃裏克,他會把這件事給我的兄弟,而不是你。如果我以後告訴他*我的兄弟是埃裏克,那不會改變他已經做過的事情。你仍然不會擁有它。 – zondo

回答

1

你在這裏做什麼是以下幾點:

  1. 您可以通過使用變量total_hours價值0賦給變量total_hours
  2. 您計算值的變量hourdaysweek與值0並將結果也分配給它們
  3. 您更改變量的值total_hours
  4. 您打印的hourdaysweeks值,就像他們在2

計算,以更好地瞭解發生了什麼,你應該發揮一點點與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()