2016-07-20 10 views
-2

Ich gehe durch LearnPythonTheHardWay Buch und ich bin auf ex35 fest. Ich beschloss, mein eigenes Spiel zu erstellen, als er nach Study Drills fragte. Ich habe gold_room Funktion, die genau wie seine ist, aber es erhöht die Fehler des Titels auf beiden Codes (seine und meine). Lokale Variable referenziert vor Zuweisung Python 3.4.5

def gold_room(): 

    print("You enter a room full of gold.") 
    print("Do you take the gold and run to the exit or you just walk out with nothing in your hands?") 

    choice = input("> ") 

    if choice == "take": 
     print("How much do you take?") 
     choice_two = input("> ") 

     if "0" in choice_two or "1" in choice_two: 
      how_much = int(choice_two) 
     else: 
      print("Man, learn to type a number.") 

     if how_much < 50: 
      print("You're not greedy. You win!") 
      exit(0) 
     else: 
      print("You greedy bastard!") 
      exit(0) 
    elif choice == "walk": 
     print("You're not greedy. You win!") 
     exit(0) 
    else: 
     print("I don't know what that means") 

UnboundLocalError: local variable 'how_much' referenced before assignment

Antwort

2

Sie erhalten diesen Fehler, weil Sie die Variable how_much verweisen, bevor ein Wert zugewiesen wird. :)

Dies geschieht in Zeile: if how_much < 50:

An diesem Punkt in der Ausführung von Code, ob how_much definiert ist oder nicht hängt davon ab, ob der vorherige Zustand (if "0" in choice_two or "1" in choice_two:) oder nicht.

Der Code wie geschrieben ist nicht wirklich sinnvoll; Sie sollten nur darüber nachdenken, wie viel how_much ist, wenn der Benutzer eine Nummer eingegeben hat, was diese erste Bedingung bestimmen soll.

versuchen, etwas wie diese, statt:

if "0" in choice_two or "1" in choice_two: 
    how_much = int(choice_two) 
    if how_much < 50: 
     print("You're not greedy. You win!") 
     exit(0) 
    else: 
     print("You greedy bastard!") 
     exit(0) 
else: 
    print("Man, learn to type a number.") 
+0

Ein while-Schleife helfen kann: Während choice_two nicht 0 oder 1 Abfrage ist der Eingang für choice_two wieder und wieder. –

+0

Vielen Dank! Jetzt bekomme ich es (: – andzedd

+0

@andzedd Wenn diese Antwort [adressiert Ihr Problem] (http://stackoverflow.com/help/someone-answers), bitte beachten Sie [akzeptieren] (http://meta.stackexchange.com/ questions/5234), indem Sie auf das Häkchen/Häkchen links neben der Antwort klicken und es grün drehen, damit die Frage zu Ihrer Zufriedenheit gelöst wird und [Reputation] (http://stackoverflow.com/help/whats (Reputation) – MattDMo

Verwandte Themen