2017-01-13 10 views
-2

Ich habe einige globale Variablen Zeug gelesen, aber mein Code wird einfach nicht funktionieren. Hier ist der Code:Globale Variablen 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) 

ich die Variablen alle global Definitionen geben, aber wenn ich rating_system() laufen, druckt es genau die richtige Anzahl für die Variablen, aber wenn ich die Variablen außerhalb der Funktion drucken es gibt mir die Standard Zahlen.

+9

Sie sind nicht 'Ta' mit' tb', 'tc' oder' td' innen die Funktion. Sie ändern nur 't1' und' t2' (das sind lokale * Kopien * von 'ta' und' td'). – chepner

+4

Sie lesen "durch einige globale variable Sachen"? Eines der ersten Dinge, die du gelesen hast, sollte sein: Benutze 'global' nicht! – Matthias

+1

Warum verwenden Sie überhaupt Globals? – jonrsharpe

Antwort

0

Zeigen Sie einfach, wie globale Variable funktioniert. Sie sehen können, dass der Wert auf globale Variable in der Funktion gesetzt selbst und seine

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 

Ausgang

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

Keine Ihrer acht global Linien geändert werden tatsächlich etwas in diesem Programm zu tun. Es ist nicht klar, aber ich vermute, dass Sie versuchen, zwei Zahlen in die Funktion einzugeben und sie durch die Ergebnisse der Funktion zu ersetzen. In diesem Fall alles, was Sie tun müssen, ist return die Ergebnisse und sie neu zuzuweisen, wenn Sie die Funktion aufrufen:

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) 
+0

Ok Mann. Das macht eine Menge Zeug, dank einer Tonne. – SamtheMan