繁体   English   中英

python 3中的全局变量

[英]Global variables in python 3

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

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() ,它只打印变量的正确数字,但是如果我在函数外打印变量,它会给我默认数字。

在这个程序中,您的八条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)

只需展示全局变量的工作原理即可。 您可以看到全局变量的值是在函数本身中设置的,并且它已更改

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM