由于某些原因,我无法更改全局变量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()
答案 0 :(得分:1)
您在此处执行的操作如下:
0
分配给变量total_hours
hour
的变量days
计算变量week
,total_hours
和0
的值,并将结果分配给它们太total_hours
hour
,days
和weeks
的值,就像它们在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()