2016-04-08 3 views
1

Ich brauche einen Weg, um den Wert einer Variablen zu erhalten, die in einer Funktion außerhalb dieser Funktion definiert wurde. Es ist nicht notwendig, aber würde meinen Code so viel einfacher zu folgen. Habe noch keine fundierten Antworten dazu gefunden.Python: Wert einer Variablen, die in einer Funktion außerhalb dieser Funktion definiert ist

def pizzais(): 
    pizza = "yummy" 

pizzais() 
print(pizza) 

Dies wird einen Fehler zurückgeben, der besagt, dass Pizza nicht definiert ist. Gibt es einen Hack, um das zu umgehen?

Zu besser verstehe meine Situation hier ist mein Code, den ich es auch anwende.

def questions(): 
    user = input("What is your username?") #username 
    race = input("What is your race? (orc, human, elf, goblin)") #race 

#won't move on if the player fills an answer that is not an option 
    if race == "orc" or race == "human" or race == "elf" or race == "goblin": 
     pClass = input("What is your class? (archer, warrior, rogue or mage)") 


    else: 
     while race != "orc" and race != "human" and race != "goblin" and race != "elf": 
      race = input("What is your race? (orc, human, elf, goblin)") 
      if race == "orc" or race == "human" or race == "elf" or race == "goblin": 
       pClass = input("What is your class? (archer, warrior, rogue or mage)") 

#won't move on if the player fills an answer that is not an option    
    if pClass == "archer" or pClass == "warrior" or pClass == "rogue" or pClass == "mage": 
      correct = input("So you are " + user + ", the " + race + " " + pClass + "? (yes or no)") 

    else: 
     while pClass != "archer" and pClass != "warrior" and pClass != "rogue" and pClass != "mage": 
      pClass = input("What is your class? (archer, warrior, rogue or mage)") 
      if pClass == "archer" or pClass == "warrior" or pClass == "rogue" or pClass == "mage": 
       correct = input("So you are " + user + ", the " + race + " " + pClass + "? (yes or no)") 

    def correct_def(): 
     correct = input("So you are " + user + ", the " + race + " " + pClass + "? (yes or no)") 
     if correct == "yes": #if player likes their choices the game will begin 
      print("Enjoy the game " + user + "!") 

     elif correct == "no": #if player doesn't like their choices all questions are asked again 
      reAsk = input("What would you like to change?(username, race, class or all)") 

     else: 
      while correct != "yes" and correct != "no": 
       correct = input("So you are " + user + ", the " + race + " " + pClass + "? (yes or no)") 
      if correct == "yes": 
       print("Enjoy the game " + user + "!") 

      elif correct == "no": 
       questions() 

    if correct == "yes": #if player likes their choices the game will begin 
     print("Enjoy the game " + user + "!") 

    elif correct == "no": #if player doesn't like their choices all questions are asked again 
     reAsk = input("What would you like to change?(username, race, class or all)") 

     if reAsk == "username": 
      user = input("What is your username?") 
      correct_def() 

     elif reAsk == "race": 
      race = input("What is your race? (orc, human, elf, goblin)") 
      while race != "orc" and race != "human" and race != "goblin" and race != "elf": 
       race = input("What is your race? (orc, human, elf, goblin)") 
      correct_def() 

     elif reAsk == "class": 
      pClass = input("What is your class? (archer, warrior, rogue or mage)") 
      while pClass != "archer" and pClass != "warrior" and pClass != "rogue" and pClass != "mage": 
       pClass = input("What is your class? (archer, warrior, rogue or mage)") 
      correct_def() 

     elif reAsk == "all": 
      questions() 

     else: 
      while reAsk != "username" and reAsk != "race" and reAsk != "class" and reAsk != "all": 
       reAsk = input("What would you like to change?(username, race, class or all)") 
       if reAsk == "username": 
        user = input("What is your username?") 
        print("Enjoy the game " + user + "!") 

       elif reAsk == "race": 
        race = input("What is your race? (orc, human, elf, goblin)") 
        while race != "orc" and race != "human" and race != "goblin" and race != "elf": 
         race = input("What is your race? (orc, human, elf, goblin)") 
        print("Enjoy the game " + user + "!") 

       elif reAsk == "class": 
        pClass = input("What is your class? (archer, warrior, rogue or mage)") 
        while pClass != "archer" and pClass != "warrior" and pClass != "rogue" and pClass != "mage": 
         pClass = input("What is your class? (archer, warrior, rogue or mage)") 
        print("Enjoy the game " + user + "!") 

       elif reAsk == "all": 
        questions() 

#won't move on if the player fills an answer that is not an option 
    else: 
     while correct != "yes" and correct != "no": 
      correct = input("So you are " + user + ", the " + race + " " + pClass + "? (yes or no)") 
     if correct == "yes": 
      print("Enjoy the game " + user + "!") 

     elif correct == "no": 
      reAsk = input("What would you like to change?(username, race, class or all)") 

     if reAsk == "username": 
      user = input("What is your username?") 
      correct_def() 

     elif reAsk == "race": 
      race = input("What is your race? (orc, human, elf, goblin)") 
      while race != "orc" and race != "human" and race != "goblin" and race != "elf": 
       race = input("What is your race? (orc, human, elf, goblin)") 
      correct_def() 

     elif reAsk == "class": 
      pClass = input("What is your class? (archer, warrior, rogue or mage)") 
      while pClass != "archer" and pClass != "warrior" and pClass != "rogue" and pClass != "mage": 
       pClass = input("What is your class? (archer, warrior, rogue or mage)") 
      correct_def() 

     elif reAsk == "all": 
      questions() 

     else: 
      while reAsk != "username" and reAsk != "race" and reAsk != "class" and reAsk != "all": 
       reAsk = input("What would you like to change?(username, race, class or all)") 
       if reAsk == "username": 
        user = input("What is your username?") 
        print("Enjoy the game " + user + "!") 

       elif reAsk == "race": 
        race = input("What is your race? (orc, human, elf, goblin)") 
        while race != "orc" and race != "human" and race != "goblin" and race != "elf": 
         race = input("What is your race? (orc, human, elf, goblin)") 
        print("Enjoy the game " + user + "!") 

       elif reAsk == "class": 
        pClass = input("What is your class? (archer, warrior, rogue or mage)") 
        while pClass != "archer" and pClass != "warrior" and pClass != "rogue" and pClass != "mage": 
         pClass = input("What is your class? (archer, warrior, rogue or mage)") 
        print("Enjoy the game " + user + "!") 

       elif reAsk == "all": 
        questions() 
questions() 
+2

Warum würden Sie "hacken"? Dafür ist 'return' gedacht. – tzaman

+2

Welchen Teil in der Codewand sollen wir betrachten, um Ihre Frage besser zu verstehen? Wo ist dein Problem? – Keatinge

+0

Grundsätzlich möchte ich in der Lage sein, race, pClass, Benutzernamen außerhalb von Fragen zu verwenden() – Shniper

Antwort

2

Sie sollten wahrscheinlich durch die Tutorial section on functions lesen - das ist nur über die einfachste Sache, die Sie Funktionen für verwenden.

Ihr Codebeispiel ist ein Riesendurcheinander, aber hier ist ein kleines Beispiel von dem, was Sie scheinen zu tun versuchen zu werden:

def ask_race(): 
    race = None 
    options = ['orc', 'human', 'elf', 'goblin'] 
    while race not in options: 
     race = input('What is your race? ({})'.format(','.join(options))) 
    return race 

Wiederholen Sie für Ihre andere Optionen, dann können Sie so etwas wie:

def questions(): 
    race = ask_race() 
    character_class = ask_class() 

Es gibt viel mehr Reinigung, die getan werden könnte, aber das sollte Sie auf eine etwas gesundere Struktur bringen.

+0

Ja, ich weiß, dass es ein Durcheinander ist, ich habe mir selbst js beigebracht und muss ein Python-Spiel für einen meiner Kurse erstellen, mit sehr begrenztem Wissen, das ich vom Professor bekommen habe. Also spiele ich hauptsächlich damit, wie man js in Python verwandelt. Sorry – Shniper

+1

Das zweite Snippet ist nicht gültig, da 'class' kein gültiger Variablenname ist. –

+0

Oh derp, fixed. – tzaman

2

Zwei Möglichkeiten, dies zu tun, eine empfohlen und eine nicht so sehr. Sie sollten nicht mit globalen Variablen herumspielen, wenn Sie nicht wissen, was Sie tun. Was Sie versuchen, sollte 100% eine Rendite verwenden. Aber um inclusive zu sein, habe ich es eingefügt, weil es könnte theoretisch erreichen, was Sie versuchen zu tun.

Best Practice: Verwenden eines Return

def pizzais(): 
    return "yummy" 

pizza = pizzais() 
print(pizza) 

Schlechte Idee: Die Verwendung von globalen Variablen

pizza = "" 

def pizzais(): 
    global pizza 
    pizza = "yummy" 


pizzais() 

print(pizza) 

Rückkehr Mehrere Variablen

def get_three_variables(): 
    var1 = "text1" 
    var2 = "text2" 
    var3 = "text3" 
    return (var1, var2, var3) 


response = get_three_variables() 
print(response) 
#this prints: ('text1', 'text2', 'text3') 

print(response[0]) 
#this prints text1 

print(response[1]) 
#this prints text2 
+0

Also, wenn ich mehrere Variablen in einer Funktion habe und jede Variable in der Funktion zurückgeben, wie kann ich den Wert jeder dieser Variablen außerhalb der Funktion erhalten? – Shniper

+0

gibt ein Tupel mit mehreren Variablen zurück – Keatinge

+2

Technisch gesehen ist 'global' das Gegenteil - es benutzt eine Variable, die außerhalb * der Funktion definiert ist. – tzaman

0

Sie versuchen, pizza zu drucken, aber was ist Pizza? Du hast es nirgends außer in deiner Funktion definiert und du gibst nichts zurück. Es ist eine lokale Variable, während der Versuch, Pizza außerhalb des Umfangs Ihrer Funktion zu drucken ist auf der Suche nach einer globalen Variable. Sie können diese question für lokale vs globale Variablen auschecken. Sie könnten pizza = pizzais() und dann print(pizza) setzen, wenn Sie return "yummy" am Ende Ihrer Funktion setzen. Ohne Verwendung von return am Ende Ihrer Funktion wird standardmäßig None zurückgegeben.

1
  1. Return mehrere Werte in einem Tupel return x, y, z und den Rückgabewert wie x, y, z = func() entpacken.
  2. Sie können globale Variablen verwenden. Wenn Sie Werte innerhalb einer Funktion setzen, deklarieren Sie zuerst global x und dann x = something.Aber globale Variablen werden am besten vermieden.
  3. Wenn Sie feststellen, dass sich der globale Zustand stark ändert, ist die Verwendung einer class geeigneter.
  4. Sie können Verschlüsse verwenden, um den Status beizubehalten. Aber das braucht ein anderes Design und Sie sollten es tun, wenn Sie mit Funktionen höherer Ordnung vertraut sind. Verschlüsse sind im Prinzip leichtgewichtig und viel schneller als Klassen (Beazly).
Verwandte Themen