简体   繁体   中英

Global variables in python 3

I've read through some global variable stuff, but my code just won't work. Here's the code:

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)

I give the variables all global definitions, but when I run rating_system() , it just prints the right number for the variables, but if I print the variables outside the function it gives me the default numbers.

None of your eight global lines are actually doing anything in this program. It's not clear, but I'm going to guess that what you're trying to do is pass two numbers into the function and replace them with the results of the function. In that case, all you need to do is return the results and reassign them when you call the function:

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)

Just show how global variable works. you could see that the value to Global Variable is set within the function itself and its changed

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

output

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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