python 3中的全局变量

时间:2017-01-13 21:02:11

标签: python python-3.x

我已经阅读了一些全局变量,但我的代码不起作用。 这是代码:

global ta
global tb
global tc
global td

ta = 1
tb = 1.25
tc = 1.5
td = 2

def rating_system(t1, t2):
    global ta
    global tb
    global tc
    global td

    if t1 < t2 and t2/t1 <= 4:
        rating = (t2/t1) * 0.25 
        t1 += rating
        t2 -= rating
    else:
        rating = (t2/t1) * 0.4
        t1 += rating
        t2 -= rating
    print(str(t1) + " and " + str(t2))

 rating_system(ta, td)

我给变量提供了所有global个定义,但是当我运行rating_system()时,它只输出正确的变量数,但如果我在函数外打印变量,它会给我默认数字

2 个答案:

答案 0 :(得分:5)

您的八条global行中没有一条在此程序中实际执行任何操作。它不清楚,但我猜你正在尝试做的是将两个数字传递给函数并用函数的结果替换它们。在这种情况下,您需要做的只是return结果并在调用函数时重新分配它们:

def rating_system(t1, t2):
    if t1 < t2 and t2/t1 <= 4:
        rating = (t2/t1) * 0.25 
        t1 += rating
        t2 -= rating
    else:
        rating = (t2/t1) * 0.4
        t1 += rating
        t2 -= rating
    return (t1, t2)

(ta, td) = rating_system(ta, td)

答案 1 :(得分:0)

只显示全局变量的工作原理。你可以看到全局变量的值是在函数本身及其改变的

中设置的
global ta
global tb
global tc
global td

ta = 1
tb = 1.25
tc = 1.5
td = 2

def rating_system(t1, t2):
    global ta
    global tb
    global tc
    global td

    if t1 < t2 and t2/t1 <= 4:
        rating = (t2/t1) * 0.25 
        t1 += rating
        t2 -= rating

    else:
        rating = (t2/t1) * 0.4
        t1 += rating
        t2 -= rating
    print "From Function"   
    print(str(t1) + " and " + str(t2))
    ta =t1
    tb =t2
print "Before"
print ta,tb,tc,td    
rating_system(ta, td)
print "After"
print ta,tb,tc,td

输出

Before
1 1.25 1.5 2
From Function
1.5 and 1.5
After
1.5 1.5 1.5 2